angular.js 922 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915
  1. /**
  2. * @license AngularJS v1.3.4
  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.4/' +
  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. isBlob: true,
  105. isBoolean: true,
  106. isPromiseLike: true,
  107. trim: true,
  108. escapeForRegexp: true,
  109. isElement: true,
  110. makeMap: true,
  111. includes: true,
  112. arrayRemove: true,
  113. copy: true,
  114. shallowCopy: true,
  115. equals: true,
  116. csp: true,
  117. concat: true,
  118. sliceArgs: true,
  119. bind: true,
  120. toJsonReplacer: true,
  121. toJson: true,
  122. fromJson: true,
  123. startingTag: true,
  124. tryDecodeURIComponent: true,
  125. parseKeyValue: true,
  126. toKeyValue: true,
  127. encodeUriSegment: true,
  128. encodeUriQuery: true,
  129. angularInit: true,
  130. bootstrap: true,
  131. getTestability: true,
  132. snake_case: true,
  133. bindJQuery: true,
  134. assertArg: true,
  135. assertArgFn: true,
  136. assertNotHasOwnProperty: true,
  137. getter: true,
  138. getBlockNodes: true,
  139. hasOwnProperty: true,
  140. createMap: true,
  141. NODE_TYPE_ELEMENT: true,
  142. NODE_TYPE_TEXT: true,
  143. NODE_TYPE_COMMENT: true,
  144. NODE_TYPE_DOCUMENT: true,
  145. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  146. */
  147. ////////////////////////////////////
  148. /**
  149. * @ngdoc module
  150. * @name ng
  151. * @module ng
  152. * @description
  153. *
  154. * # ng (core module)
  155. * The ng module is loaded by default when an AngularJS application is started. The module itself
  156. * contains the essential components for an AngularJS application to function. The table below
  157. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  158. * components available within this core module.
  159. *
  160. * <div doc-module-components="ng"></div>
  161. */
  162. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  163. // The name of a form control's ValidityState property.
  164. // This is used so that it's possible for internal tests to create mock ValidityStates.
  165. var VALIDITY_STATE_PROPERTY = 'validity';
  166. /**
  167. * @ngdoc function
  168. * @name angular.lowercase
  169. * @module ng
  170. * @kind function
  171. *
  172. * @description Converts the specified string to lowercase.
  173. * @param {string} string String to be converted to lowercase.
  174. * @returns {string} Lowercased string.
  175. */
  176. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  177. var hasOwnProperty = Object.prototype.hasOwnProperty;
  178. /**
  179. * @ngdoc function
  180. * @name angular.uppercase
  181. * @module ng
  182. * @kind function
  183. *
  184. * @description Converts the specified string to uppercase.
  185. * @param {string} string String to be converted to uppercase.
  186. * @returns {string} Uppercased string.
  187. */
  188. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  189. var manualLowercase = function(s) {
  190. /* jshint bitwise: false */
  191. return isString(s)
  192. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  193. : s;
  194. };
  195. var manualUppercase = function(s) {
  196. /* jshint bitwise: false */
  197. return isString(s)
  198. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  199. : s;
  200. };
  201. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  202. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  203. // with correct but slower alternatives.
  204. if ('i' !== 'I'.toLowerCase()) {
  205. lowercase = manualLowercase;
  206. uppercase = manualUppercase;
  207. }
  208. var /** holds major version number for IE or NaN for real browsers */
  209. msie,
  210. jqLite, // delay binding since jQuery could be loaded after us.
  211. jQuery, // delay binding
  212. slice = [].slice,
  213. splice = [].splice,
  214. push = [].push,
  215. toString = Object.prototype.toString,
  216. ngMinErr = minErr('ng'),
  217. /** @name angular */
  218. angular = window.angular || (window.angular = {}),
  219. angularModule,
  220. uid = 0;
  221. /**
  222. * documentMode is an IE-only property
  223. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  224. */
  225. msie = document.documentMode;
  226. /**
  227. * @private
  228. * @param {*} obj
  229. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  230. * String ...)
  231. */
  232. function isArrayLike(obj) {
  233. if (obj == null || isWindow(obj)) {
  234. return false;
  235. }
  236. var length = obj.length;
  237. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  238. return true;
  239. }
  240. return isString(obj) || isArray(obj) || length === 0 ||
  241. typeof length === 'number' && length > 0 && (length - 1) in obj;
  242. }
  243. /**
  244. * @ngdoc function
  245. * @name angular.forEach
  246. * @module ng
  247. * @kind function
  248. *
  249. * @description
  250. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  251. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  252. * is the value of an object property or an array element, `key` is the object property key or
  253. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  254. *
  255. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  256. * using the `hasOwnProperty` method.
  257. *
  258. * Unlike ES262's
  259. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  260. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  261. * return the value provided.
  262. *
  263. ```js
  264. var values = {name: 'misko', gender: 'male'};
  265. var log = [];
  266. angular.forEach(values, function(value, key) {
  267. this.push(key + ': ' + value);
  268. }, log);
  269. expect(log).toEqual(['name: misko', 'gender: male']);
  270. ```
  271. *
  272. * @param {Object|Array} obj Object to iterate over.
  273. * @param {Function} iterator Iterator function.
  274. * @param {Object=} context Object to become context (`this`) for the iterator function.
  275. * @returns {Object|Array} Reference to `obj`.
  276. */
  277. function forEach(obj, iterator, context) {
  278. var key, length;
  279. if (obj) {
  280. if (isFunction(obj)) {
  281. for (key in obj) {
  282. // Need to check if hasOwnProperty exists,
  283. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  284. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  285. iterator.call(context, obj[key], key, obj);
  286. }
  287. }
  288. } else if (isArray(obj) || isArrayLike(obj)) {
  289. var isPrimitive = typeof obj !== 'object';
  290. for (key = 0, length = obj.length; key < length; key++) {
  291. if (isPrimitive || key in obj) {
  292. iterator.call(context, obj[key], key, obj);
  293. }
  294. }
  295. } else if (obj.forEach && obj.forEach !== forEach) {
  296. obj.forEach(iterator, context, obj);
  297. } else {
  298. for (key in obj) {
  299. if (obj.hasOwnProperty(key)) {
  300. iterator.call(context, obj[key], key, obj);
  301. }
  302. }
  303. }
  304. }
  305. return obj;
  306. }
  307. function sortedKeys(obj) {
  308. return Object.keys(obj).sort();
  309. }
  310. function forEachSorted(obj, iterator, context) {
  311. var keys = sortedKeys(obj);
  312. for (var i = 0; i < keys.length; i++) {
  313. iterator.call(context, obj[keys[i]], keys[i]);
  314. }
  315. return keys;
  316. }
  317. /**
  318. * when using forEach the params are value, key, but it is often useful to have key, value.
  319. * @param {function(string, *)} iteratorFn
  320. * @returns {function(*, string)}
  321. */
  322. function reverseParams(iteratorFn) {
  323. return function(value, key) { iteratorFn(key, value); };
  324. }
  325. /**
  326. * A consistent way of creating unique IDs in angular.
  327. *
  328. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  329. * we hit number precision issues in JavaScript.
  330. *
  331. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  332. *
  333. * @returns {number} an unique alpha-numeric string
  334. */
  335. function nextUid() {
  336. return ++uid;
  337. }
  338. /**
  339. * Set or clear the hashkey for an object.
  340. * @param obj object
  341. * @param h the hashkey (!truthy to delete the hashkey)
  342. */
  343. function setHashKey(obj, h) {
  344. if (h) {
  345. obj.$$hashKey = h;
  346. }
  347. else {
  348. delete obj.$$hashKey;
  349. }
  350. }
  351. /**
  352. * @ngdoc function
  353. * @name angular.extend
  354. * @module ng
  355. * @kind function
  356. *
  357. * @description
  358. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  359. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  360. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  361. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
  362. *
  363. * @param {Object} dst Destination object.
  364. * @param {...Object} src Source object(s).
  365. * @returns {Object} Reference to `dst`.
  366. */
  367. function extend(dst) {
  368. var h = dst.$$hashKey;
  369. for (var i = 1, ii = arguments.length; i < ii; i++) {
  370. var obj = arguments[i];
  371. if (obj) {
  372. var keys = Object.keys(obj);
  373. for (var j = 0, jj = keys.length; j < jj; j++) {
  374. var key = keys[j];
  375. dst[key] = obj[key];
  376. }
  377. }
  378. }
  379. setHashKey(dst, h);
  380. return dst;
  381. }
  382. function int(str) {
  383. return parseInt(str, 10);
  384. }
  385. function inherit(parent, extra) {
  386. return extend(Object.create(parent), extra);
  387. }
  388. /**
  389. * @ngdoc function
  390. * @name angular.noop
  391. * @module ng
  392. * @kind function
  393. *
  394. * @description
  395. * A function that performs no operations. This function can be useful when writing code in the
  396. * functional style.
  397. ```js
  398. function foo(callback) {
  399. var result = calculateResult();
  400. (callback || angular.noop)(result);
  401. }
  402. ```
  403. */
  404. function noop() {}
  405. noop.$inject = [];
  406. /**
  407. * @ngdoc function
  408. * @name angular.identity
  409. * @module ng
  410. * @kind function
  411. *
  412. * @description
  413. * A function that returns its first argument. This function is useful when writing code in the
  414. * functional style.
  415. *
  416. ```js
  417. function transformer(transformationFn, value) {
  418. return (transformationFn || angular.identity)(value);
  419. };
  420. ```
  421. */
  422. function identity($) {return $;}
  423. identity.$inject = [];
  424. function valueFn(value) {return function() {return value;};}
  425. /**
  426. * @ngdoc function
  427. * @name angular.isUndefined
  428. * @module ng
  429. * @kind function
  430. *
  431. * @description
  432. * Determines if a reference is undefined.
  433. *
  434. * @param {*} value Reference to check.
  435. * @returns {boolean} True if `value` is undefined.
  436. */
  437. function isUndefined(value) {return typeof value === 'undefined';}
  438. /**
  439. * @ngdoc function
  440. * @name angular.isDefined
  441. * @module ng
  442. * @kind function
  443. *
  444. * @description
  445. * Determines if a reference is defined.
  446. *
  447. * @param {*} value Reference to check.
  448. * @returns {boolean} True if `value` is defined.
  449. */
  450. function isDefined(value) {return typeof value !== 'undefined';}
  451. /**
  452. * @ngdoc function
  453. * @name angular.isObject
  454. * @module ng
  455. * @kind function
  456. *
  457. * @description
  458. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  459. * considered to be objects. Note that JavaScript arrays are objects.
  460. *
  461. * @param {*} value Reference to check.
  462. * @returns {boolean} True if `value` is an `Object` but not `null`.
  463. */
  464. function isObject(value) {
  465. // http://jsperf.com/isobject4
  466. return value !== null && typeof value === 'object';
  467. }
  468. /**
  469. * @ngdoc function
  470. * @name angular.isString
  471. * @module ng
  472. * @kind function
  473. *
  474. * @description
  475. * Determines if a reference is a `String`.
  476. *
  477. * @param {*} value Reference to check.
  478. * @returns {boolean} True if `value` is a `String`.
  479. */
  480. function isString(value) {return typeof value === 'string';}
  481. /**
  482. * @ngdoc function
  483. * @name angular.isNumber
  484. * @module ng
  485. * @kind function
  486. *
  487. * @description
  488. * Determines if a reference is a `Number`.
  489. *
  490. * @param {*} value Reference to check.
  491. * @returns {boolean} True if `value` is a `Number`.
  492. */
  493. function isNumber(value) {return typeof value === 'number';}
  494. /**
  495. * @ngdoc function
  496. * @name angular.isDate
  497. * @module ng
  498. * @kind function
  499. *
  500. * @description
  501. * Determines if a value is a date.
  502. *
  503. * @param {*} value Reference to check.
  504. * @returns {boolean} True if `value` is a `Date`.
  505. */
  506. function isDate(value) {
  507. return toString.call(value) === '[object Date]';
  508. }
  509. /**
  510. * @ngdoc function
  511. * @name angular.isArray
  512. * @module ng
  513. * @kind function
  514. *
  515. * @description
  516. * Determines if a reference is an `Array`.
  517. *
  518. * @param {*} value Reference to check.
  519. * @returns {boolean} True if `value` is an `Array`.
  520. */
  521. var isArray = Array.isArray;
  522. /**
  523. * @ngdoc function
  524. * @name angular.isFunction
  525. * @module ng
  526. * @kind function
  527. *
  528. * @description
  529. * Determines if a reference is a `Function`.
  530. *
  531. * @param {*} value Reference to check.
  532. * @returns {boolean} True if `value` is a `Function`.
  533. */
  534. function isFunction(value) {return typeof value === 'function';}
  535. /**
  536. * Determines if a value is a regular expression object.
  537. *
  538. * @private
  539. * @param {*} value Reference to check.
  540. * @returns {boolean} True if `value` is a `RegExp`.
  541. */
  542. function isRegExp(value) {
  543. return toString.call(value) === '[object RegExp]';
  544. }
  545. /**
  546. * Checks if `obj` is a window object.
  547. *
  548. * @private
  549. * @param {*} obj Object to check
  550. * @returns {boolean} True if `obj` is a window obj.
  551. */
  552. function isWindow(obj) {
  553. return obj && obj.window === obj;
  554. }
  555. function isScope(obj) {
  556. return obj && obj.$evalAsync && obj.$watch;
  557. }
  558. function isFile(obj) {
  559. return toString.call(obj) === '[object File]';
  560. }
  561. function isBlob(obj) {
  562. return toString.call(obj) === '[object Blob]';
  563. }
  564. function isBoolean(value) {
  565. return typeof value === 'boolean';
  566. }
  567. function isPromiseLike(obj) {
  568. return obj && isFunction(obj.then);
  569. }
  570. var trim = function(value) {
  571. return isString(value) ? value.trim() : value;
  572. };
  573. // Copied from:
  574. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  575. // Prereq: s is a string.
  576. var escapeForRegexp = function(s) {
  577. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  578. replace(/\x08/g, '\\x08');
  579. };
  580. /**
  581. * @ngdoc function
  582. * @name angular.isElement
  583. * @module ng
  584. * @kind function
  585. *
  586. * @description
  587. * Determines if a reference is a DOM element (or wrapped jQuery element).
  588. *
  589. * @param {*} value Reference to check.
  590. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  591. */
  592. function isElement(node) {
  593. return !!(node &&
  594. (node.nodeName // we are a direct element
  595. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  596. }
  597. /**
  598. * @param str 'key1,key2,...'
  599. * @returns {object} in the form of {key1:true, key2:true, ...}
  600. */
  601. function makeMap(str) {
  602. var obj = {}, items = str.split(","), i;
  603. for (i = 0; i < items.length; i++)
  604. obj[ items[i] ] = true;
  605. return obj;
  606. }
  607. function nodeName_(element) {
  608. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  609. }
  610. function includes(array, obj) {
  611. return Array.prototype.indexOf.call(array, obj) != -1;
  612. }
  613. function arrayRemove(array, value) {
  614. var index = array.indexOf(value);
  615. if (index >= 0)
  616. array.splice(index, 1);
  617. return value;
  618. }
  619. /**
  620. * @ngdoc function
  621. * @name angular.copy
  622. * @module ng
  623. * @kind function
  624. *
  625. * @description
  626. * Creates a deep copy of `source`, which should be an object or an array.
  627. *
  628. * * If no destination is supplied, a copy of the object or array is created.
  629. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  630. * are deleted and then all elements/properties from the source are copied to it.
  631. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  632. * * If `source` is identical to 'destination' an exception will be thrown.
  633. *
  634. * @param {*} source The source that will be used to make a copy.
  635. * Can be any type, including primitives, `null`, and `undefined`.
  636. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  637. * provided, must be of the same type as `source`.
  638. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  639. *
  640. * @example
  641. <example module="copyExample">
  642. <file name="index.html">
  643. <div ng-controller="ExampleController">
  644. <form novalidate class="simple-form">
  645. Name: <input type="text" ng-model="user.name" /><br />
  646. E-mail: <input type="email" ng-model="user.email" /><br />
  647. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  648. <input type="radio" ng-model="user.gender" value="female" />female<br />
  649. <button ng-click="reset()">RESET</button>
  650. <button ng-click="update(user)">SAVE</button>
  651. </form>
  652. <pre>form = {{user | json}}</pre>
  653. <pre>master = {{master | json}}</pre>
  654. </div>
  655. <script>
  656. angular.module('copyExample', [])
  657. .controller('ExampleController', ['$scope', function($scope) {
  658. $scope.master= {};
  659. $scope.update = function(user) {
  660. // Example with 1 argument
  661. $scope.master= angular.copy(user);
  662. };
  663. $scope.reset = function() {
  664. // Example with 2 arguments
  665. angular.copy($scope.master, $scope.user);
  666. };
  667. $scope.reset();
  668. }]);
  669. </script>
  670. </file>
  671. </example>
  672. */
  673. function copy(source, destination, stackSource, stackDest) {
  674. if (isWindow(source) || isScope(source)) {
  675. throw ngMinErr('cpws',
  676. "Can't copy! Making copies of Window or Scope instances is not supported.");
  677. }
  678. if (!destination) {
  679. destination = source;
  680. if (source) {
  681. if (isArray(source)) {
  682. destination = copy(source, [], stackSource, stackDest);
  683. } else if (isDate(source)) {
  684. destination = new Date(source.getTime());
  685. } else if (isRegExp(source)) {
  686. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  687. destination.lastIndex = source.lastIndex;
  688. } else if (isObject(source)) {
  689. var emptyObject = Object.create(Object.getPrototypeOf(source));
  690. destination = copy(source, emptyObject, stackSource, stackDest);
  691. }
  692. }
  693. } else {
  694. if (source === destination) throw ngMinErr('cpi',
  695. "Can't copy! Source and destination are identical.");
  696. stackSource = stackSource || [];
  697. stackDest = stackDest || [];
  698. if (isObject(source)) {
  699. var index = stackSource.indexOf(source);
  700. if (index !== -1) return stackDest[index];
  701. stackSource.push(source);
  702. stackDest.push(destination);
  703. }
  704. var result;
  705. if (isArray(source)) {
  706. destination.length = 0;
  707. for (var i = 0; i < source.length; i++) {
  708. result = copy(source[i], null, stackSource, stackDest);
  709. if (isObject(source[i])) {
  710. stackSource.push(source[i]);
  711. stackDest.push(result);
  712. }
  713. destination.push(result);
  714. }
  715. } else {
  716. var h = destination.$$hashKey;
  717. if (isArray(destination)) {
  718. destination.length = 0;
  719. } else {
  720. forEach(destination, function(value, key) {
  721. delete destination[key];
  722. });
  723. }
  724. for (var key in source) {
  725. if (source.hasOwnProperty(key)) {
  726. result = copy(source[key], null, stackSource, stackDest);
  727. if (isObject(source[key])) {
  728. stackSource.push(source[key]);
  729. stackDest.push(result);
  730. }
  731. destination[key] = result;
  732. }
  733. }
  734. setHashKey(destination,h);
  735. }
  736. }
  737. return destination;
  738. }
  739. /**
  740. * Creates a shallow copy of an object, an array or a primitive.
  741. *
  742. * Assumes that there are no proto properties for objects.
  743. */
  744. function shallowCopy(src, dst) {
  745. if (isArray(src)) {
  746. dst = dst || [];
  747. for (var i = 0, ii = src.length; i < ii; i++) {
  748. dst[i] = src[i];
  749. }
  750. } else if (isObject(src)) {
  751. dst = dst || {};
  752. for (var key in src) {
  753. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  754. dst[key] = src[key];
  755. }
  756. }
  757. }
  758. return dst || src;
  759. }
  760. /**
  761. * @ngdoc function
  762. * @name angular.equals
  763. * @module ng
  764. * @kind function
  765. *
  766. * @description
  767. * Determines if two objects or two values are equivalent. Supports value types, regular
  768. * expressions, arrays and objects.
  769. *
  770. * Two objects or values are considered equivalent if at least one of the following is true:
  771. *
  772. * * Both objects or values pass `===` comparison.
  773. * * Both objects or values are of the same type and all of their properties are equal by
  774. * comparing them with `angular.equals`.
  775. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  776. * * Both values represent the same regular expression (In JavaScript,
  777. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  778. * representation matches).
  779. *
  780. * During a property comparison, properties of `function` type and properties with names
  781. * that begin with `$` are ignored.
  782. *
  783. * Scope and DOMWindow objects are being compared only by identify (`===`).
  784. *
  785. * @param {*} o1 Object or value to compare.
  786. * @param {*} o2 Object or value to compare.
  787. * @returns {boolean} True if arguments are equal.
  788. */
  789. function equals(o1, o2) {
  790. if (o1 === o2) return true;
  791. if (o1 === null || o2 === null) return false;
  792. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  793. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  794. if (t1 == t2) {
  795. if (t1 == 'object') {
  796. if (isArray(o1)) {
  797. if (!isArray(o2)) return false;
  798. if ((length = o1.length) == o2.length) {
  799. for (key = 0; key < length; key++) {
  800. if (!equals(o1[key], o2[key])) return false;
  801. }
  802. return true;
  803. }
  804. } else if (isDate(o1)) {
  805. if (!isDate(o2)) return false;
  806. return equals(o1.getTime(), o2.getTime());
  807. } else if (isRegExp(o1) && isRegExp(o2)) {
  808. return o1.toString() == o2.toString();
  809. } else {
  810. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  811. keySet = {};
  812. for (key in o1) {
  813. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  814. if (!equals(o1[key], o2[key])) return false;
  815. keySet[key] = true;
  816. }
  817. for (key in o2) {
  818. if (!keySet.hasOwnProperty(key) &&
  819. key.charAt(0) !== '$' &&
  820. o2[key] !== undefined &&
  821. !isFunction(o2[key])) return false;
  822. }
  823. return true;
  824. }
  825. }
  826. }
  827. return false;
  828. }
  829. var csp = function() {
  830. if (isDefined(csp.isActive_)) return csp.isActive_;
  831. var active = !!(document.querySelector('[ng-csp]') ||
  832. document.querySelector('[data-ng-csp]'));
  833. if (!active) {
  834. try {
  835. /* jshint -W031, -W054 */
  836. new Function('');
  837. /* jshint +W031, +W054 */
  838. } catch (e) {
  839. active = true;
  840. }
  841. }
  842. return (csp.isActive_ = active);
  843. };
  844. function concat(array1, array2, index) {
  845. return array1.concat(slice.call(array2, index));
  846. }
  847. function sliceArgs(args, startIndex) {
  848. return slice.call(args, startIndex || 0);
  849. }
  850. /* jshint -W101 */
  851. /**
  852. * @ngdoc function
  853. * @name angular.bind
  854. * @module ng
  855. * @kind function
  856. *
  857. * @description
  858. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  859. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  860. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  861. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  862. *
  863. * @param {Object} self Context which `fn` should be evaluated in.
  864. * @param {function()} fn Function to be bound.
  865. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  866. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  867. */
  868. /* jshint +W101 */
  869. function bind(self, fn) {
  870. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  871. if (isFunction(fn) && !(fn instanceof RegExp)) {
  872. return curryArgs.length
  873. ? function() {
  874. return arguments.length
  875. ? fn.apply(self, concat(curryArgs, arguments, 0))
  876. : fn.apply(self, curryArgs);
  877. }
  878. : function() {
  879. return arguments.length
  880. ? fn.apply(self, arguments)
  881. : fn.call(self);
  882. };
  883. } else {
  884. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  885. return fn;
  886. }
  887. }
  888. function toJsonReplacer(key, value) {
  889. var val = value;
  890. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  891. val = undefined;
  892. } else if (isWindow(value)) {
  893. val = '$WINDOW';
  894. } else if (value && document === value) {
  895. val = '$DOCUMENT';
  896. } else if (isScope(value)) {
  897. val = '$SCOPE';
  898. }
  899. return val;
  900. }
  901. /**
  902. * @ngdoc function
  903. * @name angular.toJson
  904. * @module ng
  905. * @kind function
  906. *
  907. * @description
  908. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  909. * stripped since angular uses this notation internally.
  910. *
  911. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  912. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  913. * @returns {string|undefined} JSON-ified string representing `obj`.
  914. */
  915. function toJson(obj, pretty) {
  916. if (typeof obj === 'undefined') return undefined;
  917. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  918. }
  919. /**
  920. * @ngdoc function
  921. * @name angular.fromJson
  922. * @module ng
  923. * @kind function
  924. *
  925. * @description
  926. * Deserializes a JSON string.
  927. *
  928. * @param {string} json JSON string to deserialize.
  929. * @returns {Object|Array|string|number} Deserialized thingy.
  930. */
  931. function fromJson(json) {
  932. return isString(json)
  933. ? JSON.parse(json)
  934. : json;
  935. }
  936. /**
  937. * @returns {string} Returns the string representation of the element.
  938. */
  939. function startingTag(element) {
  940. element = jqLite(element).clone();
  941. try {
  942. // turns out IE does not let you set .html() on elements which
  943. // are not allowed to have children. So we just ignore it.
  944. element.empty();
  945. } catch (e) {}
  946. var elemHtml = jqLite('<div>').append(element).html();
  947. try {
  948. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  949. elemHtml.
  950. match(/^(<[^>]+>)/)[1].
  951. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  952. } catch (e) {
  953. return lowercase(elemHtml);
  954. }
  955. }
  956. /////////////////////////////////////////////////
  957. /**
  958. * Tries to decode the URI component without throwing an exception.
  959. *
  960. * @private
  961. * @param str value potential URI component to check.
  962. * @returns {boolean} True if `value` can be decoded
  963. * with the decodeURIComponent function.
  964. */
  965. function tryDecodeURIComponent(value) {
  966. try {
  967. return decodeURIComponent(value);
  968. } catch (e) {
  969. // Ignore any invalid uri component
  970. }
  971. }
  972. /**
  973. * Parses an escaped url query string into key-value pairs.
  974. * @returns {Object.<string,boolean|Array>}
  975. */
  976. function parseKeyValue(/**string*/keyValue) {
  977. var obj = {}, key_value, key;
  978. forEach((keyValue || "").split('&'), function(keyValue) {
  979. if (keyValue) {
  980. key_value = keyValue.replace(/\+/g,'%20').split('=');
  981. key = tryDecodeURIComponent(key_value[0]);
  982. if (isDefined(key)) {
  983. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  984. if (!hasOwnProperty.call(obj, key)) {
  985. obj[key] = val;
  986. } else if (isArray(obj[key])) {
  987. obj[key].push(val);
  988. } else {
  989. obj[key] = [obj[key],val];
  990. }
  991. }
  992. }
  993. });
  994. return obj;
  995. }
  996. function toKeyValue(obj) {
  997. var parts = [];
  998. forEach(obj, function(value, key) {
  999. if (isArray(value)) {
  1000. forEach(value, function(arrayValue) {
  1001. parts.push(encodeUriQuery(key, true) +
  1002. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1003. });
  1004. } else {
  1005. parts.push(encodeUriQuery(key, true) +
  1006. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1007. }
  1008. });
  1009. return parts.length ? parts.join('&') : '';
  1010. }
  1011. /**
  1012. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1013. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1014. * segments:
  1015. * segment = *pchar
  1016. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1017. * pct-encoded = "%" HEXDIG HEXDIG
  1018. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1019. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1020. * / "*" / "+" / "," / ";" / "="
  1021. */
  1022. function encodeUriSegment(val) {
  1023. return encodeUriQuery(val, true).
  1024. replace(/%26/gi, '&').
  1025. replace(/%3D/gi, '=').
  1026. replace(/%2B/gi, '+');
  1027. }
  1028. /**
  1029. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1030. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1031. * encoded per http://tools.ietf.org/html/rfc3986:
  1032. * query = *( pchar / "/" / "?" )
  1033. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1034. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1035. * pct-encoded = "%" HEXDIG HEXDIG
  1036. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1037. * / "*" / "+" / "," / ";" / "="
  1038. */
  1039. function encodeUriQuery(val, pctEncodeSpaces) {
  1040. return encodeURIComponent(val).
  1041. replace(/%40/gi, '@').
  1042. replace(/%3A/gi, ':').
  1043. replace(/%24/g, '$').
  1044. replace(/%2C/gi, ',').
  1045. replace(/%3B/gi, ';').
  1046. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1047. }
  1048. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1049. function getNgAttribute(element, ngAttr) {
  1050. var attr, i, ii = ngAttrPrefixes.length;
  1051. element = jqLite(element);
  1052. for (i = 0; i < ii; ++i) {
  1053. attr = ngAttrPrefixes[i] + ngAttr;
  1054. if (isString(attr = element.attr(attr))) {
  1055. return attr;
  1056. }
  1057. }
  1058. return null;
  1059. }
  1060. /**
  1061. * @ngdoc directive
  1062. * @name ngApp
  1063. * @module ng
  1064. *
  1065. * @element ANY
  1066. * @param {angular.Module} ngApp an optional application
  1067. * {@link angular.module module} name to load.
  1068. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1069. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1070. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1071. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1072. * tracking down the root of these bugs.
  1073. *
  1074. * @description
  1075. *
  1076. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1077. * designates the **root element** of the application and is typically placed near the root element
  1078. * of the page - e.g. on the `<body>` or `<html>` tags.
  1079. *
  1080. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1081. * found in the document will be used to define the root element to auto-bootstrap as an
  1082. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1083. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1084. *
  1085. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1086. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1087. * should contain the application code needed or have dependencies on other modules that will
  1088. * contain the code. See {@link angular.module} for more information.
  1089. *
  1090. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1091. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1092. * would not be resolved to `3`.
  1093. *
  1094. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1095. *
  1096. <example module="ngAppDemo">
  1097. <file name="index.html">
  1098. <div ng-controller="ngAppDemoController">
  1099. I can add: {{a}} + {{b}} = {{ a+b }}
  1100. </div>
  1101. </file>
  1102. <file name="script.js">
  1103. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1104. $scope.a = 1;
  1105. $scope.b = 2;
  1106. });
  1107. </file>
  1108. </example>
  1109. *
  1110. * Using `ngStrictDi`, you would see something like this:
  1111. *
  1112. <example ng-app-included="true">
  1113. <file name="index.html">
  1114. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1115. <div ng-controller="GoodController1">
  1116. I can add: {{a}} + {{b}} = {{ a+b }}
  1117. <p>This renders because the controller does not fail to
  1118. instantiate, by using explicit annotation style (see
  1119. script.js for details)
  1120. </p>
  1121. </div>
  1122. <div ng-controller="GoodController2">
  1123. Name: <input ng-model="name"><br />
  1124. Hello, {{name}}!
  1125. <p>This renders because the controller does not fail to
  1126. instantiate, by using explicit annotation style
  1127. (see script.js for details)
  1128. </p>
  1129. </div>
  1130. <div ng-controller="BadController">
  1131. I can add: {{a}} + {{b}} = {{ a+b }}
  1132. <p>The controller could not be instantiated, due to relying
  1133. on automatic function annotations (which are disabled in
  1134. strict mode). As such, the content of this section is not
  1135. interpolated, and there should be an error in your web console.
  1136. </p>
  1137. </div>
  1138. </div>
  1139. </file>
  1140. <file name="script.js">
  1141. angular.module('ngAppStrictDemo', [])
  1142. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1143. // rather than an explicit annotation
  1144. .controller('BadController', function($scope) {
  1145. $scope.a = 1;
  1146. $scope.b = 2;
  1147. })
  1148. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1149. // due to using explicit annotations using the array style and $inject property, respectively.
  1150. .controller('GoodController1', ['$scope', function($scope) {
  1151. $scope.a = 1;
  1152. $scope.b = 2;
  1153. }])
  1154. .controller('GoodController2', GoodController2);
  1155. function GoodController2($scope) {
  1156. $scope.name = "World";
  1157. }
  1158. GoodController2.$inject = ['$scope'];
  1159. </file>
  1160. <file name="style.css">
  1161. div[ng-controller] {
  1162. margin-bottom: 1em;
  1163. -webkit-border-radius: 4px;
  1164. border-radius: 4px;
  1165. border: 1px solid;
  1166. padding: .5em;
  1167. }
  1168. div[ng-controller^=Good] {
  1169. border-color: #d6e9c6;
  1170. background-color: #dff0d8;
  1171. color: #3c763d;
  1172. }
  1173. div[ng-controller^=Bad] {
  1174. border-color: #ebccd1;
  1175. background-color: #f2dede;
  1176. color: #a94442;
  1177. margin-bottom: 0;
  1178. }
  1179. </file>
  1180. </example>
  1181. */
  1182. function angularInit(element, bootstrap) {
  1183. var appElement,
  1184. module,
  1185. config = {};
  1186. // The element `element` has priority over any other element
  1187. forEach(ngAttrPrefixes, function(prefix) {
  1188. var name = prefix + 'app';
  1189. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1190. appElement = element;
  1191. module = element.getAttribute(name);
  1192. }
  1193. });
  1194. forEach(ngAttrPrefixes, function(prefix) {
  1195. var name = prefix + 'app';
  1196. var candidate;
  1197. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1198. appElement = candidate;
  1199. module = candidate.getAttribute(name);
  1200. }
  1201. });
  1202. if (appElement) {
  1203. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1204. bootstrap(appElement, module ? [module] : [], config);
  1205. }
  1206. }
  1207. /**
  1208. * @ngdoc function
  1209. * @name angular.bootstrap
  1210. * @module ng
  1211. * @description
  1212. * Use this function to manually start up angular application.
  1213. *
  1214. * See: {@link guide/bootstrap Bootstrap}
  1215. *
  1216. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1217. * They must use {@link ng.directive:ngApp ngApp}.
  1218. *
  1219. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1220. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1221. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1222. * multiple instances of Angular try to work on the DOM.
  1223. *
  1224. * ```html
  1225. * <!doctype html>
  1226. * <html>
  1227. * <body>
  1228. * <div ng-controller="WelcomeController">
  1229. * {{greeting}}
  1230. * </div>
  1231. *
  1232. * <script src="angular.js"></script>
  1233. * <script>
  1234. * var app = angular.module('demo', [])
  1235. * .controller('WelcomeController', function($scope) {
  1236. * $scope.greeting = 'Welcome!';
  1237. * });
  1238. * angular.bootstrap(document, ['demo']);
  1239. * </script>
  1240. * </body>
  1241. * </html>
  1242. * ```
  1243. *
  1244. * @param {DOMElement} element DOM element which is the root of angular application.
  1245. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1246. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1247. * function that will be invoked by the injector as a run block.
  1248. * See: {@link angular.module modules}
  1249. * @param {Object=} config an object for defining configuration options for the application. The
  1250. * following keys are supported:
  1251. *
  1252. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1253. * assist in finding bugs which break minified code. Defaults to `false`.
  1254. *
  1255. * @returns {auto.$injector} Returns the newly created injector for this app.
  1256. */
  1257. function bootstrap(element, modules, config) {
  1258. if (!isObject(config)) config = {};
  1259. var defaultConfig = {
  1260. strictDi: false
  1261. };
  1262. config = extend(defaultConfig, config);
  1263. var doBootstrap = function() {
  1264. element = jqLite(element);
  1265. if (element.injector()) {
  1266. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1267. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1268. throw ngMinErr(
  1269. 'btstrpd',
  1270. "App Already Bootstrapped with this Element '{0}'",
  1271. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1272. }
  1273. modules = modules || [];
  1274. modules.unshift(['$provide', function($provide) {
  1275. $provide.value('$rootElement', element);
  1276. }]);
  1277. if (config.debugInfoEnabled) {
  1278. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1279. modules.push(['$compileProvider', function($compileProvider) {
  1280. $compileProvider.debugInfoEnabled(true);
  1281. }]);
  1282. }
  1283. modules.unshift('ng');
  1284. var injector = createInjector(modules, config.strictDi);
  1285. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1286. function bootstrapApply(scope, element, compile, injector) {
  1287. scope.$apply(function() {
  1288. element.data('$injector', injector);
  1289. compile(element)(scope);
  1290. });
  1291. }]
  1292. );
  1293. return injector;
  1294. };
  1295. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1296. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1297. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1298. config.debugInfoEnabled = true;
  1299. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1300. }
  1301. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1302. return doBootstrap();
  1303. }
  1304. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1305. angular.resumeBootstrap = function(extraModules) {
  1306. forEach(extraModules, function(module) {
  1307. modules.push(module);
  1308. });
  1309. doBootstrap();
  1310. };
  1311. }
  1312. /**
  1313. * @ngdoc function
  1314. * @name angular.reloadWithDebugInfo
  1315. * @module ng
  1316. * @description
  1317. * Use this function to reload the current application with debug information turned on.
  1318. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1319. *
  1320. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1321. */
  1322. function reloadWithDebugInfo() {
  1323. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1324. window.location.reload();
  1325. }
  1326. /**
  1327. * @name angular.getTestability
  1328. * @module ng
  1329. * @description
  1330. * Get the testability service for the instance of Angular on the given
  1331. * element.
  1332. * @param {DOMElement} element DOM element which is the root of angular application.
  1333. */
  1334. function getTestability(rootElement) {
  1335. return angular.element(rootElement).injector().get('$$testability');
  1336. }
  1337. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1338. function snake_case(name, separator) {
  1339. separator = separator || '_';
  1340. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1341. return (pos ? separator : '') + letter.toLowerCase();
  1342. });
  1343. }
  1344. var bindJQueryFired = false;
  1345. var skipDestroyOnNextJQueryCleanData;
  1346. function bindJQuery() {
  1347. var originalCleanData;
  1348. if (bindJQueryFired) {
  1349. return;
  1350. }
  1351. // bind to jQuery if present;
  1352. jQuery = window.jQuery;
  1353. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1354. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1355. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1356. // versions. It will not work for sure with jQuery <1.7, though.
  1357. if (jQuery && jQuery.fn.on) {
  1358. jqLite = jQuery;
  1359. extend(jQuery.fn, {
  1360. scope: JQLitePrototype.scope,
  1361. isolateScope: JQLitePrototype.isolateScope,
  1362. controller: JQLitePrototype.controller,
  1363. injector: JQLitePrototype.injector,
  1364. inheritedData: JQLitePrototype.inheritedData
  1365. });
  1366. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1367. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1368. // the $destroy event on all removed nodes.
  1369. originalCleanData = jQuery.cleanData;
  1370. jQuery.cleanData = function(elems) {
  1371. var events;
  1372. if (!skipDestroyOnNextJQueryCleanData) {
  1373. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1374. events = jQuery._data(elem, "events");
  1375. if (events && events.$destroy) {
  1376. jQuery(elem).triggerHandler('$destroy');
  1377. }
  1378. }
  1379. } else {
  1380. skipDestroyOnNextJQueryCleanData = false;
  1381. }
  1382. originalCleanData(elems);
  1383. };
  1384. } else {
  1385. jqLite = JQLite;
  1386. }
  1387. angular.element = jqLite;
  1388. // Prevent double-proxying.
  1389. bindJQueryFired = true;
  1390. }
  1391. /**
  1392. * throw error if the argument is falsy.
  1393. */
  1394. function assertArg(arg, name, reason) {
  1395. if (!arg) {
  1396. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1397. }
  1398. return arg;
  1399. }
  1400. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1401. if (acceptArrayAnnotation && isArray(arg)) {
  1402. arg = arg[arg.length - 1];
  1403. }
  1404. assertArg(isFunction(arg), name, 'not a function, got ' +
  1405. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1406. return arg;
  1407. }
  1408. /**
  1409. * throw error if the name given is hasOwnProperty
  1410. * @param {String} name the name to test
  1411. * @param {String} context the context in which the name is used, such as module or directive
  1412. */
  1413. function assertNotHasOwnProperty(name, context) {
  1414. if (name === 'hasOwnProperty') {
  1415. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1416. }
  1417. }
  1418. /**
  1419. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1420. * @param {Object} obj starting object
  1421. * @param {String} path path to traverse
  1422. * @param {boolean} [bindFnToScope=true]
  1423. * @returns {Object} value as accessible by path
  1424. */
  1425. //TODO(misko): this function needs to be removed
  1426. function getter(obj, path, bindFnToScope) {
  1427. if (!path) return obj;
  1428. var keys = path.split('.');
  1429. var key;
  1430. var lastInstance = obj;
  1431. var len = keys.length;
  1432. for (var i = 0; i < len; i++) {
  1433. key = keys[i];
  1434. if (obj) {
  1435. obj = (lastInstance = obj)[key];
  1436. }
  1437. }
  1438. if (!bindFnToScope && isFunction(obj)) {
  1439. return bind(lastInstance, obj);
  1440. }
  1441. return obj;
  1442. }
  1443. /**
  1444. * Return the DOM siblings between the first and last node in the given array.
  1445. * @param {Array} array like object
  1446. * @returns {jqLite} jqLite collection containing the nodes
  1447. */
  1448. function getBlockNodes(nodes) {
  1449. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1450. // collection, otherwise update the original collection.
  1451. var node = nodes[0];
  1452. var endNode = nodes[nodes.length - 1];
  1453. var blockNodes = [node];
  1454. do {
  1455. node = node.nextSibling;
  1456. if (!node) break;
  1457. blockNodes.push(node);
  1458. } while (node !== endNode);
  1459. return jqLite(blockNodes);
  1460. }
  1461. /**
  1462. * Creates a new object without a prototype. This object is useful for lookup without having to
  1463. * guard against prototypically inherited properties via hasOwnProperty.
  1464. *
  1465. * Related micro-benchmarks:
  1466. * - http://jsperf.com/object-create2
  1467. * - http://jsperf.com/proto-map-lookup/2
  1468. * - http://jsperf.com/for-in-vs-object-keys2
  1469. *
  1470. * @returns {Object}
  1471. */
  1472. function createMap() {
  1473. return Object.create(null);
  1474. }
  1475. var NODE_TYPE_ELEMENT = 1;
  1476. var NODE_TYPE_TEXT = 3;
  1477. var NODE_TYPE_COMMENT = 8;
  1478. var NODE_TYPE_DOCUMENT = 9;
  1479. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1480. /**
  1481. * @ngdoc type
  1482. * @name angular.Module
  1483. * @module ng
  1484. * @description
  1485. *
  1486. * Interface for configuring angular {@link angular.module modules}.
  1487. */
  1488. function setupModuleLoader(window) {
  1489. var $injectorMinErr = minErr('$injector');
  1490. var ngMinErr = minErr('ng');
  1491. function ensure(obj, name, factory) {
  1492. return obj[name] || (obj[name] = factory());
  1493. }
  1494. var angular = ensure(window, 'angular', Object);
  1495. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1496. angular.$$minErr = angular.$$minErr || minErr;
  1497. return ensure(angular, 'module', function() {
  1498. /** @type {Object.<string, angular.Module>} */
  1499. var modules = {};
  1500. /**
  1501. * @ngdoc function
  1502. * @name angular.module
  1503. * @module ng
  1504. * @description
  1505. *
  1506. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1507. * modules.
  1508. * All modules (angular core or 3rd party) that should be available to an application must be
  1509. * registered using this mechanism.
  1510. *
  1511. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1512. * existing module (the name passed as the first argument to `module`) is retrieved.
  1513. *
  1514. *
  1515. * # Module
  1516. *
  1517. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1518. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1519. *
  1520. * ```js
  1521. * // Create a new module
  1522. * var myModule = angular.module('myModule', []);
  1523. *
  1524. * // register a new service
  1525. * myModule.value('appName', 'MyCoolApp');
  1526. *
  1527. * // configure existing services inside initialization blocks.
  1528. * myModule.config(['$locationProvider', function($locationProvider) {
  1529. * // Configure existing providers
  1530. * $locationProvider.hashPrefix('!');
  1531. * }]);
  1532. * ```
  1533. *
  1534. * Then you can create an injector and load your modules like this:
  1535. *
  1536. * ```js
  1537. * var injector = angular.injector(['ng', 'myModule'])
  1538. * ```
  1539. *
  1540. * However it's more likely that you'll just use
  1541. * {@link ng.directive:ngApp ngApp} or
  1542. * {@link angular.bootstrap} to simplify this process for you.
  1543. *
  1544. * @param {!string} name The name of the module to create or retrieve.
  1545. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1546. * unspecified then the module is being retrieved for further configuration.
  1547. * @param {Function=} configFn Optional configuration function for the module. Same as
  1548. * {@link angular.Module#config Module#config()}.
  1549. * @returns {module} new module with the {@link angular.Module} api.
  1550. */
  1551. return function module(name, requires, configFn) {
  1552. var assertNotHasOwnProperty = function(name, context) {
  1553. if (name === 'hasOwnProperty') {
  1554. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1555. }
  1556. };
  1557. assertNotHasOwnProperty(name, 'module');
  1558. if (requires && modules.hasOwnProperty(name)) {
  1559. modules[name] = null;
  1560. }
  1561. return ensure(modules, name, function() {
  1562. if (!requires) {
  1563. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1564. "the module name or forgot to load it. If registering a module ensure that you " +
  1565. "specify the dependencies as the second argument.", name);
  1566. }
  1567. /** @type {!Array.<Array.<*>>} */
  1568. var invokeQueue = [];
  1569. /** @type {!Array.<Function>} */
  1570. var configBlocks = [];
  1571. /** @type {!Array.<Function>} */
  1572. var runBlocks = [];
  1573. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1574. /** @type {angular.Module} */
  1575. var moduleInstance = {
  1576. // Private state
  1577. _invokeQueue: invokeQueue,
  1578. _configBlocks: configBlocks,
  1579. _runBlocks: runBlocks,
  1580. /**
  1581. * @ngdoc property
  1582. * @name angular.Module#requires
  1583. * @module ng
  1584. *
  1585. * @description
  1586. * Holds the list of modules which the injector will load before the current module is
  1587. * loaded.
  1588. */
  1589. requires: requires,
  1590. /**
  1591. * @ngdoc property
  1592. * @name angular.Module#name
  1593. * @module ng
  1594. *
  1595. * @description
  1596. * Name of the module.
  1597. */
  1598. name: name,
  1599. /**
  1600. * @ngdoc method
  1601. * @name angular.Module#provider
  1602. * @module ng
  1603. * @param {string} name service name
  1604. * @param {Function} providerType Construction function for creating new instance of the
  1605. * service.
  1606. * @description
  1607. * See {@link auto.$provide#provider $provide.provider()}.
  1608. */
  1609. provider: invokeLater('$provide', 'provider'),
  1610. /**
  1611. * @ngdoc method
  1612. * @name angular.Module#factory
  1613. * @module ng
  1614. * @param {string} name service name
  1615. * @param {Function} providerFunction Function for creating new instance of the service.
  1616. * @description
  1617. * See {@link auto.$provide#factory $provide.factory()}.
  1618. */
  1619. factory: invokeLater('$provide', 'factory'),
  1620. /**
  1621. * @ngdoc method
  1622. * @name angular.Module#service
  1623. * @module ng
  1624. * @param {string} name service name
  1625. * @param {Function} constructor A constructor function that will be instantiated.
  1626. * @description
  1627. * See {@link auto.$provide#service $provide.service()}.
  1628. */
  1629. service: invokeLater('$provide', 'service'),
  1630. /**
  1631. * @ngdoc method
  1632. * @name angular.Module#value
  1633. * @module ng
  1634. * @param {string} name service name
  1635. * @param {*} object Service instance object.
  1636. * @description
  1637. * See {@link auto.$provide#value $provide.value()}.
  1638. */
  1639. value: invokeLater('$provide', 'value'),
  1640. /**
  1641. * @ngdoc method
  1642. * @name angular.Module#constant
  1643. * @module ng
  1644. * @param {string} name constant name
  1645. * @param {*} object Constant value.
  1646. * @description
  1647. * Because the constant are fixed, they get applied before other provide methods.
  1648. * See {@link auto.$provide#constant $provide.constant()}.
  1649. */
  1650. constant: invokeLater('$provide', 'constant', 'unshift'),
  1651. /**
  1652. * @ngdoc method
  1653. * @name angular.Module#animation
  1654. * @module ng
  1655. * @param {string} name animation name
  1656. * @param {Function} animationFactory Factory function for creating new instance of an
  1657. * animation.
  1658. * @description
  1659. *
  1660. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1661. *
  1662. *
  1663. * Defines an animation hook that can be later used with
  1664. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1665. *
  1666. * ```js
  1667. * module.animation('.animation-name', function($inject1, $inject2) {
  1668. * return {
  1669. * eventName : function(element, done) {
  1670. * //code to run the animation
  1671. * //once complete, then run done()
  1672. * return function cancellationFunction(element) {
  1673. * //code to cancel the animation
  1674. * }
  1675. * }
  1676. * }
  1677. * })
  1678. * ```
  1679. *
  1680. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1681. * {@link ngAnimate ngAnimate module} for more information.
  1682. */
  1683. animation: invokeLater('$animateProvider', 'register'),
  1684. /**
  1685. * @ngdoc method
  1686. * @name angular.Module#filter
  1687. * @module ng
  1688. * @param {string} name Filter name.
  1689. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1690. * @description
  1691. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1692. */
  1693. filter: invokeLater('$filterProvider', 'register'),
  1694. /**
  1695. * @ngdoc method
  1696. * @name angular.Module#controller
  1697. * @module ng
  1698. * @param {string|Object} name Controller name, or an object map of controllers where the
  1699. * keys are the names and the values are the constructors.
  1700. * @param {Function} constructor Controller constructor function.
  1701. * @description
  1702. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1703. */
  1704. controller: invokeLater('$controllerProvider', 'register'),
  1705. /**
  1706. * @ngdoc method
  1707. * @name angular.Module#directive
  1708. * @module ng
  1709. * @param {string|Object} name Directive name, or an object map of directives where the
  1710. * keys are the names and the values are the factories.
  1711. * @param {Function} directiveFactory Factory function for creating new instance of
  1712. * directives.
  1713. * @description
  1714. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1715. */
  1716. directive: invokeLater('$compileProvider', 'directive'),
  1717. /**
  1718. * @ngdoc method
  1719. * @name angular.Module#config
  1720. * @module ng
  1721. * @param {Function} configFn Execute this function on module load. Useful for service
  1722. * configuration.
  1723. * @description
  1724. * Use this method to register work which needs to be performed on module loading.
  1725. * For more about how to configure services, see
  1726. * {@link providers#provider-recipe Provider Recipe}.
  1727. */
  1728. config: config,
  1729. /**
  1730. * @ngdoc method
  1731. * @name angular.Module#run
  1732. * @module ng
  1733. * @param {Function} initializationFn Execute this function after injector creation.
  1734. * Useful for application initialization.
  1735. * @description
  1736. * Use this method to register work which should be performed when the injector is done
  1737. * loading all modules.
  1738. */
  1739. run: function(block) {
  1740. runBlocks.push(block);
  1741. return this;
  1742. }
  1743. };
  1744. if (configFn) {
  1745. config(configFn);
  1746. }
  1747. return moduleInstance;
  1748. /**
  1749. * @param {string} provider
  1750. * @param {string} method
  1751. * @param {String=} insertMethod
  1752. * @returns {angular.Module}
  1753. */
  1754. function invokeLater(provider, method, insertMethod, queue) {
  1755. if (!queue) queue = invokeQueue;
  1756. return function() {
  1757. queue[insertMethod || 'push']([provider, method, arguments]);
  1758. return moduleInstance;
  1759. };
  1760. }
  1761. });
  1762. };
  1763. });
  1764. }
  1765. /* global: toDebugString: true */
  1766. function serializeObject(obj) {
  1767. var seen = [];
  1768. return JSON.stringify(obj, function(key, val) {
  1769. val = toJsonReplacer(key, val);
  1770. if (isObject(val)) {
  1771. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1772. seen.push(val);
  1773. }
  1774. return val;
  1775. });
  1776. }
  1777. function toDebugString(obj) {
  1778. if (typeof obj === 'function') {
  1779. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1780. } else if (typeof obj === 'undefined') {
  1781. return 'undefined';
  1782. } else if (typeof obj !== 'string') {
  1783. return serializeObject(obj);
  1784. }
  1785. return obj;
  1786. }
  1787. /* global angularModule: true,
  1788. version: true,
  1789. $LocaleProvider,
  1790. $CompileProvider,
  1791. htmlAnchorDirective,
  1792. inputDirective,
  1793. inputDirective,
  1794. formDirective,
  1795. scriptDirective,
  1796. selectDirective,
  1797. styleDirective,
  1798. optionDirective,
  1799. ngBindDirective,
  1800. ngBindHtmlDirective,
  1801. ngBindTemplateDirective,
  1802. ngClassDirective,
  1803. ngClassEvenDirective,
  1804. ngClassOddDirective,
  1805. ngCspDirective,
  1806. ngCloakDirective,
  1807. ngControllerDirective,
  1808. ngFormDirective,
  1809. ngHideDirective,
  1810. ngIfDirective,
  1811. ngIncludeDirective,
  1812. ngIncludeFillContentDirective,
  1813. ngInitDirective,
  1814. ngNonBindableDirective,
  1815. ngPluralizeDirective,
  1816. ngRepeatDirective,
  1817. ngShowDirective,
  1818. ngStyleDirective,
  1819. ngSwitchDirective,
  1820. ngSwitchWhenDirective,
  1821. ngSwitchDefaultDirective,
  1822. ngOptionsDirective,
  1823. ngTranscludeDirective,
  1824. ngModelDirective,
  1825. ngListDirective,
  1826. ngChangeDirective,
  1827. patternDirective,
  1828. patternDirective,
  1829. requiredDirective,
  1830. requiredDirective,
  1831. minlengthDirective,
  1832. minlengthDirective,
  1833. maxlengthDirective,
  1834. maxlengthDirective,
  1835. ngValueDirective,
  1836. ngModelOptionsDirective,
  1837. ngAttributeAliasDirectives,
  1838. ngEventDirectives,
  1839. $AnchorScrollProvider,
  1840. $AnimateProvider,
  1841. $BrowserProvider,
  1842. $CacheFactoryProvider,
  1843. $ControllerProvider,
  1844. $DocumentProvider,
  1845. $ExceptionHandlerProvider,
  1846. $FilterProvider,
  1847. $InterpolateProvider,
  1848. $IntervalProvider,
  1849. $HttpProvider,
  1850. $HttpBackendProvider,
  1851. $LocationProvider,
  1852. $LogProvider,
  1853. $ParseProvider,
  1854. $RootScopeProvider,
  1855. $QProvider,
  1856. $$QProvider,
  1857. $$SanitizeUriProvider,
  1858. $SceProvider,
  1859. $SceDelegateProvider,
  1860. $SnifferProvider,
  1861. $TemplateCacheProvider,
  1862. $TemplateRequestProvider,
  1863. $$TestabilityProvider,
  1864. $TimeoutProvider,
  1865. $$RAFProvider,
  1866. $$AsyncCallbackProvider,
  1867. $WindowProvider
  1868. */
  1869. /**
  1870. * @ngdoc object
  1871. * @name angular.version
  1872. * @module ng
  1873. * @description
  1874. * An object that contains information about the current AngularJS version. This object has the
  1875. * following properties:
  1876. *
  1877. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1878. * - `major` – `{number}` – Major version number, such as "0".
  1879. * - `minor` – `{number}` – Minor version number, such as "9".
  1880. * - `dot` – `{number}` – Dot version number, such as "18".
  1881. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1882. */
  1883. var version = {
  1884. full: '1.3.4', // all of these placeholder strings will be replaced by grunt's
  1885. major: 1, // package task
  1886. minor: 3,
  1887. dot: 4,
  1888. codeName: 'highfalutin-petroglyph'
  1889. };
  1890. function publishExternalAPI(angular) {
  1891. extend(angular, {
  1892. 'bootstrap': bootstrap,
  1893. 'copy': copy,
  1894. 'extend': extend,
  1895. 'equals': equals,
  1896. 'element': jqLite,
  1897. 'forEach': forEach,
  1898. 'injector': createInjector,
  1899. 'noop': noop,
  1900. 'bind': bind,
  1901. 'toJson': toJson,
  1902. 'fromJson': fromJson,
  1903. 'identity': identity,
  1904. 'isUndefined': isUndefined,
  1905. 'isDefined': isDefined,
  1906. 'isString': isString,
  1907. 'isFunction': isFunction,
  1908. 'isObject': isObject,
  1909. 'isNumber': isNumber,
  1910. 'isElement': isElement,
  1911. 'isArray': isArray,
  1912. 'version': version,
  1913. 'isDate': isDate,
  1914. 'lowercase': lowercase,
  1915. 'uppercase': uppercase,
  1916. 'callbacks': {counter: 0},
  1917. 'getTestability': getTestability,
  1918. '$$minErr': minErr,
  1919. '$$csp': csp,
  1920. 'reloadWithDebugInfo': reloadWithDebugInfo
  1921. });
  1922. angularModule = setupModuleLoader(window);
  1923. try {
  1924. angularModule('ngLocale');
  1925. } catch (e) {
  1926. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1927. }
  1928. angularModule('ng', ['ngLocale'], ['$provide',
  1929. function ngModule($provide) {
  1930. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1931. $provide.provider({
  1932. $$sanitizeUri: $$SanitizeUriProvider
  1933. });
  1934. $provide.provider('$compile', $CompileProvider).
  1935. directive({
  1936. a: htmlAnchorDirective,
  1937. input: inputDirective,
  1938. textarea: inputDirective,
  1939. form: formDirective,
  1940. script: scriptDirective,
  1941. select: selectDirective,
  1942. style: styleDirective,
  1943. option: optionDirective,
  1944. ngBind: ngBindDirective,
  1945. ngBindHtml: ngBindHtmlDirective,
  1946. ngBindTemplate: ngBindTemplateDirective,
  1947. ngClass: ngClassDirective,
  1948. ngClassEven: ngClassEvenDirective,
  1949. ngClassOdd: ngClassOddDirective,
  1950. ngCloak: ngCloakDirective,
  1951. ngController: ngControllerDirective,
  1952. ngForm: ngFormDirective,
  1953. ngHide: ngHideDirective,
  1954. ngIf: ngIfDirective,
  1955. ngInclude: ngIncludeDirective,
  1956. ngInit: ngInitDirective,
  1957. ngNonBindable: ngNonBindableDirective,
  1958. ngPluralize: ngPluralizeDirective,
  1959. ngRepeat: ngRepeatDirective,
  1960. ngShow: ngShowDirective,
  1961. ngStyle: ngStyleDirective,
  1962. ngSwitch: ngSwitchDirective,
  1963. ngSwitchWhen: ngSwitchWhenDirective,
  1964. ngSwitchDefault: ngSwitchDefaultDirective,
  1965. ngOptions: ngOptionsDirective,
  1966. ngTransclude: ngTranscludeDirective,
  1967. ngModel: ngModelDirective,
  1968. ngList: ngListDirective,
  1969. ngChange: ngChangeDirective,
  1970. pattern: patternDirective,
  1971. ngPattern: patternDirective,
  1972. required: requiredDirective,
  1973. ngRequired: requiredDirective,
  1974. minlength: minlengthDirective,
  1975. ngMinlength: minlengthDirective,
  1976. maxlength: maxlengthDirective,
  1977. ngMaxlength: maxlengthDirective,
  1978. ngValue: ngValueDirective,
  1979. ngModelOptions: ngModelOptionsDirective
  1980. }).
  1981. directive({
  1982. ngInclude: ngIncludeFillContentDirective
  1983. }).
  1984. directive(ngAttributeAliasDirectives).
  1985. directive(ngEventDirectives);
  1986. $provide.provider({
  1987. $anchorScroll: $AnchorScrollProvider,
  1988. $animate: $AnimateProvider,
  1989. $browser: $BrowserProvider,
  1990. $cacheFactory: $CacheFactoryProvider,
  1991. $controller: $ControllerProvider,
  1992. $document: $DocumentProvider,
  1993. $exceptionHandler: $ExceptionHandlerProvider,
  1994. $filter: $FilterProvider,
  1995. $interpolate: $InterpolateProvider,
  1996. $interval: $IntervalProvider,
  1997. $http: $HttpProvider,
  1998. $httpBackend: $HttpBackendProvider,
  1999. $location: $LocationProvider,
  2000. $log: $LogProvider,
  2001. $parse: $ParseProvider,
  2002. $rootScope: $RootScopeProvider,
  2003. $q: $QProvider,
  2004. $$q: $$QProvider,
  2005. $sce: $SceProvider,
  2006. $sceDelegate: $SceDelegateProvider,
  2007. $sniffer: $SnifferProvider,
  2008. $templateCache: $TemplateCacheProvider,
  2009. $templateRequest: $TemplateRequestProvider,
  2010. $$testability: $$TestabilityProvider,
  2011. $timeout: $TimeoutProvider,
  2012. $window: $WindowProvider,
  2013. $$rAF: $$RAFProvider,
  2014. $$asyncCallback: $$AsyncCallbackProvider
  2015. });
  2016. }
  2017. ]);
  2018. }
  2019. /* global JQLitePrototype: true,
  2020. addEventListenerFn: true,
  2021. removeEventListenerFn: true,
  2022. BOOLEAN_ATTR: true,
  2023. ALIASED_ATTR: true,
  2024. */
  2025. //////////////////////////////////
  2026. //JQLite
  2027. //////////////////////////////////
  2028. /**
  2029. * @ngdoc function
  2030. * @name angular.element
  2031. * @module ng
  2032. * @kind function
  2033. *
  2034. * @description
  2035. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2036. *
  2037. * If jQuery is available, `angular.element` is an alias for the
  2038. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2039. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2040. *
  2041. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2042. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2043. * commonly needed functionality with the goal of having a very small footprint.</div>
  2044. *
  2045. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2046. *
  2047. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2048. * jqLite; they are never raw DOM references.</div>
  2049. *
  2050. * ## Angular's jqLite
  2051. * jqLite provides only the following jQuery methods:
  2052. *
  2053. * - [`addClass()`](http://api.jquery.com/addClass/)
  2054. * - [`after()`](http://api.jquery.com/after/)
  2055. * - [`append()`](http://api.jquery.com/append/)
  2056. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2057. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2058. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2059. * - [`clone()`](http://api.jquery.com/clone/)
  2060. * - [`contents()`](http://api.jquery.com/contents/)
  2061. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
  2062. * - [`data()`](http://api.jquery.com/data/)
  2063. * - [`detach()`](http://api.jquery.com/detach/)
  2064. * - [`empty()`](http://api.jquery.com/empty/)
  2065. * - [`eq()`](http://api.jquery.com/eq/)
  2066. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2067. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2068. * - [`html()`](http://api.jquery.com/html/)
  2069. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2070. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2071. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2072. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2073. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2074. * - [`prepend()`](http://api.jquery.com/prepend/)
  2075. * - [`prop()`](http://api.jquery.com/prop/)
  2076. * - [`ready()`](http://api.jquery.com/ready/)
  2077. * - [`remove()`](http://api.jquery.com/remove/)
  2078. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2079. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2080. * - [`removeData()`](http://api.jquery.com/removeData/)
  2081. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2082. * - [`text()`](http://api.jquery.com/text/)
  2083. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2084. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2085. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2086. * - [`val()`](http://api.jquery.com/val/)
  2087. * - [`wrap()`](http://api.jquery.com/wrap/)
  2088. *
  2089. * ## jQuery/jqLite Extras
  2090. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2091. *
  2092. * ### Events
  2093. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2094. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2095. * element before it is removed.
  2096. *
  2097. * ### Methods
  2098. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2099. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2100. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2101. * `'ngModel'`).
  2102. * - `injector()` - retrieves the injector of the current element or its parent.
  2103. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2104. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2105. * be enabled.
  2106. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2107. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2108. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2109. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2110. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2111. * parent element is reached.
  2112. *
  2113. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2114. * @returns {Object} jQuery object.
  2115. */
  2116. JQLite.expando = 'ng339';
  2117. var jqCache = JQLite.cache = {},
  2118. jqId = 1,
  2119. addEventListenerFn = function(element, type, fn) {
  2120. element.addEventListener(type, fn, false);
  2121. },
  2122. removeEventListenerFn = function(element, type, fn) {
  2123. element.removeEventListener(type, fn, false);
  2124. };
  2125. /*
  2126. * !!! This is an undocumented "private" function !!!
  2127. */
  2128. JQLite._data = function(node) {
  2129. //jQuery always returns an object on cache miss
  2130. return this.cache[node[this.expando]] || {};
  2131. };
  2132. function jqNextId() { return ++jqId; }
  2133. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2134. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2135. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2136. var jqLiteMinErr = minErr('jqLite');
  2137. /**
  2138. * Converts snake_case to camelCase.
  2139. * Also there is special case for Moz prefix starting with upper case letter.
  2140. * @param name Name to normalize
  2141. */
  2142. function camelCase(name) {
  2143. return name.
  2144. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2145. return offset ? letter.toUpperCase() : letter;
  2146. }).
  2147. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2148. }
  2149. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2150. var HTML_REGEXP = /<|&#?\w+;/;
  2151. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2152. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2153. var wrapMap = {
  2154. 'option': [1, '<select multiple="multiple">', '</select>'],
  2155. 'thead': [1, '<table>', '</table>'],
  2156. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2157. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2158. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2159. '_default': [0, "", ""]
  2160. };
  2161. wrapMap.optgroup = wrapMap.option;
  2162. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2163. wrapMap.th = wrapMap.td;
  2164. function jqLiteIsTextNode(html) {
  2165. return !HTML_REGEXP.test(html);
  2166. }
  2167. function jqLiteAcceptsData(node) {
  2168. // The window object can accept data but has no nodeType
  2169. // Otherwise we are only interested in elements (1) and documents (9)
  2170. var nodeType = node.nodeType;
  2171. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2172. }
  2173. function jqLiteBuildFragment(html, context) {
  2174. var tmp, tag, wrap,
  2175. fragment = context.createDocumentFragment(),
  2176. nodes = [], i;
  2177. if (jqLiteIsTextNode(html)) {
  2178. // Convert non-html into a text node
  2179. nodes.push(context.createTextNode(html));
  2180. } else {
  2181. // Convert html into DOM nodes
  2182. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2183. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2184. wrap = wrapMap[tag] || wrapMap._default;
  2185. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2186. // Descend through wrappers to the right content
  2187. i = wrap[0];
  2188. while (i--) {
  2189. tmp = tmp.lastChild;
  2190. }
  2191. nodes = concat(nodes, tmp.childNodes);
  2192. tmp = fragment.firstChild;
  2193. tmp.textContent = "";
  2194. }
  2195. // Remove wrapper from fragment
  2196. fragment.textContent = "";
  2197. fragment.innerHTML = ""; // Clear inner HTML
  2198. forEach(nodes, function(node) {
  2199. fragment.appendChild(node);
  2200. });
  2201. return fragment;
  2202. }
  2203. function jqLiteParseHTML(html, context) {
  2204. context = context || document;
  2205. var parsed;
  2206. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2207. return [context.createElement(parsed[1])];
  2208. }
  2209. if ((parsed = jqLiteBuildFragment(html, context))) {
  2210. return parsed.childNodes;
  2211. }
  2212. return [];
  2213. }
  2214. /////////////////////////////////////////////
  2215. function JQLite(element) {
  2216. if (element instanceof JQLite) {
  2217. return element;
  2218. }
  2219. var argIsString;
  2220. if (isString(element)) {
  2221. element = trim(element);
  2222. argIsString = true;
  2223. }
  2224. if (!(this instanceof JQLite)) {
  2225. if (argIsString && element.charAt(0) != '<') {
  2226. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2227. }
  2228. return new JQLite(element);
  2229. }
  2230. if (argIsString) {
  2231. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2232. } else {
  2233. jqLiteAddNodes(this, element);
  2234. }
  2235. }
  2236. function jqLiteClone(element) {
  2237. return element.cloneNode(true);
  2238. }
  2239. function jqLiteDealoc(element, onlyDescendants) {
  2240. if (!onlyDescendants) jqLiteRemoveData(element);
  2241. if (element.querySelectorAll) {
  2242. var descendants = element.querySelectorAll('*');
  2243. for (var i = 0, l = descendants.length; i < l; i++) {
  2244. jqLiteRemoveData(descendants[i]);
  2245. }
  2246. }
  2247. }
  2248. function jqLiteOff(element, type, fn, unsupported) {
  2249. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2250. var expandoStore = jqLiteExpandoStore(element);
  2251. var events = expandoStore && expandoStore.events;
  2252. var handle = expandoStore && expandoStore.handle;
  2253. if (!handle) return; //no listeners registered
  2254. if (!type) {
  2255. for (type in events) {
  2256. if (type !== '$destroy') {
  2257. removeEventListenerFn(element, type, handle);
  2258. }
  2259. delete events[type];
  2260. }
  2261. } else {
  2262. forEach(type.split(' '), function(type) {
  2263. if (isDefined(fn)) {
  2264. var listenerFns = events[type];
  2265. arrayRemove(listenerFns || [], fn);
  2266. if (listenerFns && listenerFns.length > 0) {
  2267. return;
  2268. }
  2269. }
  2270. removeEventListenerFn(element, type, handle);
  2271. delete events[type];
  2272. });
  2273. }
  2274. }
  2275. function jqLiteRemoveData(element, name) {
  2276. var expandoId = element.ng339;
  2277. var expandoStore = expandoId && jqCache[expandoId];
  2278. if (expandoStore) {
  2279. if (name) {
  2280. delete expandoStore.data[name];
  2281. return;
  2282. }
  2283. if (expandoStore.handle) {
  2284. if (expandoStore.events.$destroy) {
  2285. expandoStore.handle({}, '$destroy');
  2286. }
  2287. jqLiteOff(element);
  2288. }
  2289. delete jqCache[expandoId];
  2290. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2291. }
  2292. }
  2293. function jqLiteExpandoStore(element, createIfNecessary) {
  2294. var expandoId = element.ng339,
  2295. expandoStore = expandoId && jqCache[expandoId];
  2296. if (createIfNecessary && !expandoStore) {
  2297. element.ng339 = expandoId = jqNextId();
  2298. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2299. }
  2300. return expandoStore;
  2301. }
  2302. function jqLiteData(element, key, value) {
  2303. if (jqLiteAcceptsData(element)) {
  2304. var isSimpleSetter = isDefined(value);
  2305. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2306. var massGetter = !key;
  2307. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2308. var data = expandoStore && expandoStore.data;
  2309. if (isSimpleSetter) { // data('key', value)
  2310. data[key] = value;
  2311. } else {
  2312. if (massGetter) { // data()
  2313. return data;
  2314. } else {
  2315. if (isSimpleGetter) { // data('key')
  2316. // don't force creation of expandoStore if it doesn't exist yet
  2317. return data && data[key];
  2318. } else { // mass-setter: data({key1: val1, key2: val2})
  2319. extend(data, key);
  2320. }
  2321. }
  2322. }
  2323. }
  2324. }
  2325. function jqLiteHasClass(element, selector) {
  2326. if (!element.getAttribute) return false;
  2327. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2328. indexOf(" " + selector + " ") > -1);
  2329. }
  2330. function jqLiteRemoveClass(element, cssClasses) {
  2331. if (cssClasses && element.setAttribute) {
  2332. forEach(cssClasses.split(' '), function(cssClass) {
  2333. element.setAttribute('class', trim(
  2334. (" " + (element.getAttribute('class') || '') + " ")
  2335. .replace(/[\n\t]/g, " ")
  2336. .replace(" " + trim(cssClass) + " ", " "))
  2337. );
  2338. });
  2339. }
  2340. }
  2341. function jqLiteAddClass(element, cssClasses) {
  2342. if (cssClasses && element.setAttribute) {
  2343. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2344. .replace(/[\n\t]/g, " ");
  2345. forEach(cssClasses.split(' '), function(cssClass) {
  2346. cssClass = trim(cssClass);
  2347. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2348. existingClasses += cssClass + ' ';
  2349. }
  2350. });
  2351. element.setAttribute('class', trim(existingClasses));
  2352. }
  2353. }
  2354. function jqLiteAddNodes(root, elements) {
  2355. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2356. if (elements) {
  2357. // if a Node (the most common case)
  2358. if (elements.nodeType) {
  2359. root[root.length++] = elements;
  2360. } else {
  2361. var length = elements.length;
  2362. // if an Array or NodeList and not a Window
  2363. if (typeof length === 'number' && elements.window !== elements) {
  2364. if (length) {
  2365. for (var i = 0; i < length; i++) {
  2366. root[root.length++] = elements[i];
  2367. }
  2368. }
  2369. } else {
  2370. root[root.length++] = elements;
  2371. }
  2372. }
  2373. }
  2374. }
  2375. function jqLiteController(element, name) {
  2376. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2377. }
  2378. function jqLiteInheritedData(element, name, value) {
  2379. // if element is the document object work with the html element instead
  2380. // this makes $(document).scope() possible
  2381. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2382. element = element.documentElement;
  2383. }
  2384. var names = isArray(name) ? name : [name];
  2385. while (element) {
  2386. for (var i = 0, ii = names.length; i < ii; i++) {
  2387. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2388. }
  2389. // If dealing with a document fragment node with a host element, and no parent, use the host
  2390. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2391. // to lookup parent controllers.
  2392. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2393. }
  2394. }
  2395. function jqLiteEmpty(element) {
  2396. jqLiteDealoc(element, true);
  2397. while (element.firstChild) {
  2398. element.removeChild(element.firstChild);
  2399. }
  2400. }
  2401. function jqLiteRemove(element, keepData) {
  2402. if (!keepData) jqLiteDealoc(element);
  2403. var parent = element.parentNode;
  2404. if (parent) parent.removeChild(element);
  2405. }
  2406. function jqLiteDocumentLoaded(action, win) {
  2407. win = win || window;
  2408. if (win.document.readyState === 'complete') {
  2409. // Force the action to be run async for consistent behaviour
  2410. // from the action's point of view
  2411. // i.e. it will definitely not be in a $apply
  2412. win.setTimeout(action);
  2413. } else {
  2414. // No need to unbind this handler as load is only ever called once
  2415. jqLite(win).on('load', action);
  2416. }
  2417. }
  2418. //////////////////////////////////////////
  2419. // Functions which are declared directly.
  2420. //////////////////////////////////////////
  2421. var JQLitePrototype = JQLite.prototype = {
  2422. ready: function(fn) {
  2423. var fired = false;
  2424. function trigger() {
  2425. if (fired) return;
  2426. fired = true;
  2427. fn();
  2428. }
  2429. // check if document is already loaded
  2430. if (document.readyState === 'complete') {
  2431. setTimeout(trigger);
  2432. } else {
  2433. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2434. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2435. // jshint -W064
  2436. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2437. // jshint +W064
  2438. }
  2439. },
  2440. toString: function() {
  2441. var value = [];
  2442. forEach(this, function(e) { value.push('' + e);});
  2443. return '[' + value.join(', ') + ']';
  2444. },
  2445. eq: function(index) {
  2446. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2447. },
  2448. length: 0,
  2449. push: push,
  2450. sort: [].sort,
  2451. splice: [].splice
  2452. };
  2453. //////////////////////////////////////////
  2454. // Functions iterating getter/setters.
  2455. // these functions return self on setter and
  2456. // value on get.
  2457. //////////////////////////////////////////
  2458. var BOOLEAN_ATTR = {};
  2459. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2460. BOOLEAN_ATTR[lowercase(value)] = value;
  2461. });
  2462. var BOOLEAN_ELEMENTS = {};
  2463. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2464. BOOLEAN_ELEMENTS[value] = true;
  2465. });
  2466. var ALIASED_ATTR = {
  2467. 'ngMinlength': 'minlength',
  2468. 'ngMaxlength': 'maxlength',
  2469. 'ngMin': 'min',
  2470. 'ngMax': 'max',
  2471. 'ngPattern': 'pattern'
  2472. };
  2473. function getBooleanAttrName(element, name) {
  2474. // check dom last since we will most likely fail on name
  2475. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2476. // booleanAttr is here twice to minimize DOM access
  2477. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2478. }
  2479. function getAliasedAttrName(element, name) {
  2480. var nodeName = element.nodeName;
  2481. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2482. }
  2483. forEach({
  2484. data: jqLiteData,
  2485. removeData: jqLiteRemoveData
  2486. }, function(fn, name) {
  2487. JQLite[name] = fn;
  2488. });
  2489. forEach({
  2490. data: jqLiteData,
  2491. inheritedData: jqLiteInheritedData,
  2492. scope: function(element) {
  2493. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2494. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2495. },
  2496. isolateScope: function(element) {
  2497. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2498. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2499. },
  2500. controller: jqLiteController,
  2501. injector: function(element) {
  2502. return jqLiteInheritedData(element, '$injector');
  2503. },
  2504. removeAttr: function(element, name) {
  2505. element.removeAttribute(name);
  2506. },
  2507. hasClass: jqLiteHasClass,
  2508. css: function(element, name, value) {
  2509. name = camelCase(name);
  2510. if (isDefined(value)) {
  2511. element.style[name] = value;
  2512. } else {
  2513. return element.style[name];
  2514. }
  2515. },
  2516. attr: function(element, name, value) {
  2517. var lowercasedName = lowercase(name);
  2518. if (BOOLEAN_ATTR[lowercasedName]) {
  2519. if (isDefined(value)) {
  2520. if (!!value) {
  2521. element[name] = true;
  2522. element.setAttribute(name, lowercasedName);
  2523. } else {
  2524. element[name] = false;
  2525. element.removeAttribute(lowercasedName);
  2526. }
  2527. } else {
  2528. return (element[name] ||
  2529. (element.attributes.getNamedItem(name) || noop).specified)
  2530. ? lowercasedName
  2531. : undefined;
  2532. }
  2533. } else if (isDefined(value)) {
  2534. element.setAttribute(name, value);
  2535. } else if (element.getAttribute) {
  2536. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2537. // some elements (e.g. Document) don't have get attribute, so return undefined
  2538. var ret = element.getAttribute(name, 2);
  2539. // normalize non-existing attributes to undefined (as jQuery)
  2540. return ret === null ? undefined : ret;
  2541. }
  2542. },
  2543. prop: function(element, name, value) {
  2544. if (isDefined(value)) {
  2545. element[name] = value;
  2546. } else {
  2547. return element[name];
  2548. }
  2549. },
  2550. text: (function() {
  2551. getText.$dv = '';
  2552. return getText;
  2553. function getText(element, value) {
  2554. if (isUndefined(value)) {
  2555. var nodeType = element.nodeType;
  2556. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2557. }
  2558. element.textContent = value;
  2559. }
  2560. })(),
  2561. val: function(element, value) {
  2562. if (isUndefined(value)) {
  2563. if (element.multiple && nodeName_(element) === 'select') {
  2564. var result = [];
  2565. forEach(element.options, function(option) {
  2566. if (option.selected) {
  2567. result.push(option.value || option.text);
  2568. }
  2569. });
  2570. return result.length === 0 ? null : result;
  2571. }
  2572. return element.value;
  2573. }
  2574. element.value = value;
  2575. },
  2576. html: function(element, value) {
  2577. if (isUndefined(value)) {
  2578. return element.innerHTML;
  2579. }
  2580. jqLiteDealoc(element, true);
  2581. element.innerHTML = value;
  2582. },
  2583. empty: jqLiteEmpty
  2584. }, function(fn, name) {
  2585. /**
  2586. * Properties: writes return selection, reads return first value
  2587. */
  2588. JQLite.prototype[name] = function(arg1, arg2) {
  2589. var i, key;
  2590. var nodeCount = this.length;
  2591. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2592. // in a way that survives minification.
  2593. // jqLiteEmpty takes no arguments but is a setter.
  2594. if (fn !== jqLiteEmpty &&
  2595. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2596. if (isObject(arg1)) {
  2597. // we are a write, but the object properties are the key/values
  2598. for (i = 0; i < nodeCount; i++) {
  2599. if (fn === jqLiteData) {
  2600. // data() takes the whole object in jQuery
  2601. fn(this[i], arg1);
  2602. } else {
  2603. for (key in arg1) {
  2604. fn(this[i], key, arg1[key]);
  2605. }
  2606. }
  2607. }
  2608. // return self for chaining
  2609. return this;
  2610. } else {
  2611. // we are a read, so read the first child.
  2612. // TODO: do we still need this?
  2613. var value = fn.$dv;
  2614. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2615. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2616. for (var j = 0; j < jj; j++) {
  2617. var nodeValue = fn(this[j], arg1, arg2);
  2618. value = value ? value + nodeValue : nodeValue;
  2619. }
  2620. return value;
  2621. }
  2622. } else {
  2623. // we are a write, so apply to all children
  2624. for (i = 0; i < nodeCount; i++) {
  2625. fn(this[i], arg1, arg2);
  2626. }
  2627. // return self for chaining
  2628. return this;
  2629. }
  2630. };
  2631. });
  2632. function createEventHandler(element, events) {
  2633. var eventHandler = function(event, type) {
  2634. // jQuery specific api
  2635. event.isDefaultPrevented = function() {
  2636. return event.defaultPrevented;
  2637. };
  2638. var eventFns = events[type || event.type];
  2639. var eventFnsLength = eventFns ? eventFns.length : 0;
  2640. if (!eventFnsLength) return;
  2641. if (isUndefined(event.immediatePropagationStopped)) {
  2642. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2643. event.stopImmediatePropagation = function() {
  2644. event.immediatePropagationStopped = true;
  2645. if (event.stopPropagation) {
  2646. event.stopPropagation();
  2647. }
  2648. if (originalStopImmediatePropagation) {
  2649. originalStopImmediatePropagation.call(event);
  2650. }
  2651. };
  2652. }
  2653. event.isImmediatePropagationStopped = function() {
  2654. return event.immediatePropagationStopped === true;
  2655. };
  2656. // Copy event handlers in case event handlers array is modified during execution.
  2657. if ((eventFnsLength > 1)) {
  2658. eventFns = shallowCopy(eventFns);
  2659. }
  2660. for (var i = 0; i < eventFnsLength; i++) {
  2661. if (!event.isImmediatePropagationStopped()) {
  2662. eventFns[i].call(element, event);
  2663. }
  2664. }
  2665. };
  2666. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2667. // events on `element`
  2668. eventHandler.elem = element;
  2669. return eventHandler;
  2670. }
  2671. //////////////////////////////////////////
  2672. // Functions iterating traversal.
  2673. // These functions chain results into a single
  2674. // selector.
  2675. //////////////////////////////////////////
  2676. forEach({
  2677. removeData: jqLiteRemoveData,
  2678. on: function jqLiteOn(element, type, fn, unsupported) {
  2679. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2680. // Do not add event handlers to non-elements because they will not be cleaned up.
  2681. if (!jqLiteAcceptsData(element)) {
  2682. return;
  2683. }
  2684. var expandoStore = jqLiteExpandoStore(element, true);
  2685. var events = expandoStore.events;
  2686. var handle = expandoStore.handle;
  2687. if (!handle) {
  2688. handle = expandoStore.handle = createEventHandler(element, events);
  2689. }
  2690. // http://jsperf.com/string-indexof-vs-split
  2691. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2692. var i = types.length;
  2693. while (i--) {
  2694. type = types[i];
  2695. var eventFns = events[type];
  2696. if (!eventFns) {
  2697. events[type] = [];
  2698. if (type === 'mouseenter' || type === 'mouseleave') {
  2699. // Refer to jQuery's implementation of mouseenter & mouseleave
  2700. // Read about mouseenter and mouseleave:
  2701. // http://www.quirksmode.org/js/events_mouse.html#link8
  2702. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2703. var target = this, related = event.relatedTarget;
  2704. // For mousenter/leave call the handler if related is outside the target.
  2705. // NB: No relatedTarget if the mouse left/entered the browser window
  2706. if (!related || (related !== target && !target.contains(related))) {
  2707. handle(event, type);
  2708. }
  2709. });
  2710. } else {
  2711. if (type !== '$destroy') {
  2712. addEventListenerFn(element, type, handle);
  2713. }
  2714. }
  2715. eventFns = events[type];
  2716. }
  2717. eventFns.push(fn);
  2718. }
  2719. },
  2720. off: jqLiteOff,
  2721. one: function(element, type, fn) {
  2722. element = jqLite(element);
  2723. //add the listener twice so that when it is called
  2724. //you can remove the original function and still be
  2725. //able to call element.off(ev, fn) normally
  2726. element.on(type, function onFn() {
  2727. element.off(type, fn);
  2728. element.off(type, onFn);
  2729. });
  2730. element.on(type, fn);
  2731. },
  2732. replaceWith: function(element, replaceNode) {
  2733. var index, parent = element.parentNode;
  2734. jqLiteDealoc(element);
  2735. forEach(new JQLite(replaceNode), function(node) {
  2736. if (index) {
  2737. parent.insertBefore(node, index.nextSibling);
  2738. } else {
  2739. parent.replaceChild(node, element);
  2740. }
  2741. index = node;
  2742. });
  2743. },
  2744. children: function(element) {
  2745. var children = [];
  2746. forEach(element.childNodes, function(element) {
  2747. if (element.nodeType === NODE_TYPE_ELEMENT)
  2748. children.push(element);
  2749. });
  2750. return children;
  2751. },
  2752. contents: function(element) {
  2753. return element.contentDocument || element.childNodes || [];
  2754. },
  2755. append: function(element, node) {
  2756. var nodeType = element.nodeType;
  2757. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2758. node = new JQLite(node);
  2759. for (var i = 0, ii = node.length; i < ii; i++) {
  2760. var child = node[i];
  2761. element.appendChild(child);
  2762. }
  2763. },
  2764. prepend: function(element, node) {
  2765. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2766. var index = element.firstChild;
  2767. forEach(new JQLite(node), function(child) {
  2768. element.insertBefore(child, index);
  2769. });
  2770. }
  2771. },
  2772. wrap: function(element, wrapNode) {
  2773. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2774. var parent = element.parentNode;
  2775. if (parent) {
  2776. parent.replaceChild(wrapNode, element);
  2777. }
  2778. wrapNode.appendChild(element);
  2779. },
  2780. remove: jqLiteRemove,
  2781. detach: function(element) {
  2782. jqLiteRemove(element, true);
  2783. },
  2784. after: function(element, newElement) {
  2785. var index = element, parent = element.parentNode;
  2786. newElement = new JQLite(newElement);
  2787. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2788. var node = newElement[i];
  2789. parent.insertBefore(node, index.nextSibling);
  2790. index = node;
  2791. }
  2792. },
  2793. addClass: jqLiteAddClass,
  2794. removeClass: jqLiteRemoveClass,
  2795. toggleClass: function(element, selector, condition) {
  2796. if (selector) {
  2797. forEach(selector.split(' '), function(className) {
  2798. var classCondition = condition;
  2799. if (isUndefined(classCondition)) {
  2800. classCondition = !jqLiteHasClass(element, className);
  2801. }
  2802. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2803. });
  2804. }
  2805. },
  2806. parent: function(element) {
  2807. var parent = element.parentNode;
  2808. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2809. },
  2810. next: function(element) {
  2811. return element.nextElementSibling;
  2812. },
  2813. find: function(element, selector) {
  2814. if (element.getElementsByTagName) {
  2815. return element.getElementsByTagName(selector);
  2816. } else {
  2817. return [];
  2818. }
  2819. },
  2820. clone: jqLiteClone,
  2821. triggerHandler: function(element, event, extraParameters) {
  2822. var dummyEvent, eventFnsCopy, handlerArgs;
  2823. var eventName = event.type || event;
  2824. var expandoStore = jqLiteExpandoStore(element);
  2825. var events = expandoStore && expandoStore.events;
  2826. var eventFns = events && events[eventName];
  2827. if (eventFns) {
  2828. // Create a dummy event to pass to the handlers
  2829. dummyEvent = {
  2830. preventDefault: function() { this.defaultPrevented = true; },
  2831. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2832. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2833. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2834. stopPropagation: noop,
  2835. type: eventName,
  2836. target: element
  2837. };
  2838. // If a custom event was provided then extend our dummy event with it
  2839. if (event.type) {
  2840. dummyEvent = extend(dummyEvent, event);
  2841. }
  2842. // Copy event handlers in case event handlers array is modified during execution.
  2843. eventFnsCopy = shallowCopy(eventFns);
  2844. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2845. forEach(eventFnsCopy, function(fn) {
  2846. if (!dummyEvent.isImmediatePropagationStopped()) {
  2847. fn.apply(element, handlerArgs);
  2848. }
  2849. });
  2850. }
  2851. }
  2852. }, function(fn, name) {
  2853. /**
  2854. * chaining functions
  2855. */
  2856. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2857. var value;
  2858. for (var i = 0, ii = this.length; i < ii; i++) {
  2859. if (isUndefined(value)) {
  2860. value = fn(this[i], arg1, arg2, arg3);
  2861. if (isDefined(value)) {
  2862. // any function which returns a value needs to be wrapped
  2863. value = jqLite(value);
  2864. }
  2865. } else {
  2866. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2867. }
  2868. }
  2869. return isDefined(value) ? value : this;
  2870. };
  2871. // bind legacy bind/unbind to on/off
  2872. JQLite.prototype.bind = JQLite.prototype.on;
  2873. JQLite.prototype.unbind = JQLite.prototype.off;
  2874. });
  2875. /**
  2876. * Computes a hash of an 'obj'.
  2877. * Hash of a:
  2878. * string is string
  2879. * number is number as string
  2880. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2881. * that is also assigned to the $$hashKey property of the object.
  2882. *
  2883. * @param obj
  2884. * @returns {string} hash string such that the same input will have the same hash string.
  2885. * The resulting string key is in 'type:hashKey' format.
  2886. */
  2887. function hashKey(obj, nextUidFn) {
  2888. var key = obj && obj.$$hashKey;
  2889. if (key) {
  2890. if (typeof key === 'function') {
  2891. key = obj.$$hashKey();
  2892. }
  2893. return key;
  2894. }
  2895. var objType = typeof obj;
  2896. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2897. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2898. } else {
  2899. key = objType + ':' + obj;
  2900. }
  2901. return key;
  2902. }
  2903. /**
  2904. * HashMap which can use objects as keys
  2905. */
  2906. function HashMap(array, isolatedUid) {
  2907. if (isolatedUid) {
  2908. var uid = 0;
  2909. this.nextUid = function() {
  2910. return ++uid;
  2911. };
  2912. }
  2913. forEach(array, this.put, this);
  2914. }
  2915. HashMap.prototype = {
  2916. /**
  2917. * Store key value pair
  2918. * @param key key to store can be any type
  2919. * @param value value to store can be any type
  2920. */
  2921. put: function(key, value) {
  2922. this[hashKey(key, this.nextUid)] = value;
  2923. },
  2924. /**
  2925. * @param key
  2926. * @returns {Object} the value for the key
  2927. */
  2928. get: function(key) {
  2929. return this[hashKey(key, this.nextUid)];
  2930. },
  2931. /**
  2932. * Remove the key/value pair
  2933. * @param key
  2934. */
  2935. remove: function(key) {
  2936. var value = this[key = hashKey(key, this.nextUid)];
  2937. delete this[key];
  2938. return value;
  2939. }
  2940. };
  2941. /**
  2942. * @ngdoc function
  2943. * @module ng
  2944. * @name angular.injector
  2945. * @kind function
  2946. *
  2947. * @description
  2948. * Creates an injector object that can be used for retrieving services as well as for
  2949. * dependency injection (see {@link guide/di dependency injection}).
  2950. *
  2951. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2952. * {@link angular.module}. The `ng` module must be explicitly added.
  2953. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  2954. * disallows argument name annotation inference.
  2955. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2956. *
  2957. * @example
  2958. * Typical usage
  2959. * ```js
  2960. * // create an injector
  2961. * var $injector = angular.injector(['ng']);
  2962. *
  2963. * // use the injector to kick off your application
  2964. * // use the type inference to auto inject arguments, or use implicit injection
  2965. * $injector.invoke(function($rootScope, $compile, $document) {
  2966. * $compile($document)($rootScope);
  2967. * $rootScope.$digest();
  2968. * });
  2969. * ```
  2970. *
  2971. * Sometimes you want to get access to the injector of a currently running Angular app
  2972. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2973. * application has been bootstrapped. You can do this using the extra `injector()` added
  2974. * to JQuery/jqLite elements. See {@link angular.element}.
  2975. *
  2976. * *This is fairly rare but could be the case if a third party library is injecting the
  2977. * markup.*
  2978. *
  2979. * In the following example a new block of HTML containing a `ng-controller`
  2980. * directive is added to the end of the document body by JQuery. We then compile and link
  2981. * it into the current AngularJS scope.
  2982. *
  2983. * ```js
  2984. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2985. * $(document.body).append($div);
  2986. *
  2987. * angular.element(document).injector().invoke(function($compile) {
  2988. * var scope = angular.element($div).scope();
  2989. * $compile($div)(scope);
  2990. * });
  2991. * ```
  2992. */
  2993. /**
  2994. * @ngdoc module
  2995. * @name auto
  2996. * @description
  2997. *
  2998. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2999. */
  3000. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3001. var FN_ARG_SPLIT = /,/;
  3002. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3003. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3004. var $injectorMinErr = minErr('$injector');
  3005. function anonFn(fn) {
  3006. // For anonymous functions, showing at the very least the function signature can help in
  3007. // debugging.
  3008. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3009. args = fnText.match(FN_ARGS);
  3010. if (args) {
  3011. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3012. }
  3013. return 'fn';
  3014. }
  3015. function annotate(fn, strictDi, name) {
  3016. var $inject,
  3017. fnText,
  3018. argDecl,
  3019. last;
  3020. if (typeof fn === 'function') {
  3021. if (!($inject = fn.$inject)) {
  3022. $inject = [];
  3023. if (fn.length) {
  3024. if (strictDi) {
  3025. if (!isString(name) || !name) {
  3026. name = fn.name || anonFn(fn);
  3027. }
  3028. throw $injectorMinErr('strictdi',
  3029. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3030. }
  3031. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3032. argDecl = fnText.match(FN_ARGS);
  3033. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3034. arg.replace(FN_ARG, function(all, underscore, name) {
  3035. $inject.push(name);
  3036. });
  3037. });
  3038. }
  3039. fn.$inject = $inject;
  3040. }
  3041. } else if (isArray(fn)) {
  3042. last = fn.length - 1;
  3043. assertArgFn(fn[last], 'fn');
  3044. $inject = fn.slice(0, last);
  3045. } else {
  3046. assertArgFn(fn, 'fn', true);
  3047. }
  3048. return $inject;
  3049. }
  3050. ///////////////////////////////////////
  3051. /**
  3052. * @ngdoc service
  3053. * @name $injector
  3054. *
  3055. * @description
  3056. *
  3057. * `$injector` is used to retrieve object instances as defined by
  3058. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3059. * and load modules.
  3060. *
  3061. * The following always holds true:
  3062. *
  3063. * ```js
  3064. * var $injector = angular.injector();
  3065. * expect($injector.get('$injector')).toBe($injector);
  3066. * expect($injector.invoke(function($injector) {
  3067. * return $injector;
  3068. * })).toBe($injector);
  3069. * ```
  3070. *
  3071. * # Injection Function Annotation
  3072. *
  3073. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3074. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3075. *
  3076. * ```js
  3077. * // inferred (only works if code not minified/obfuscated)
  3078. * $injector.invoke(function(serviceA){});
  3079. *
  3080. * // annotated
  3081. * function explicit(serviceA) {};
  3082. * explicit.$inject = ['serviceA'];
  3083. * $injector.invoke(explicit);
  3084. *
  3085. * // inline
  3086. * $injector.invoke(['serviceA', function(serviceA){}]);
  3087. * ```
  3088. *
  3089. * ## Inference
  3090. *
  3091. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3092. * can then be parsed and the function arguments can be extracted. This method of discovering
  3093. * annotations is disallowed when the injector is in strict mode.
  3094. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3095. * argument names.
  3096. *
  3097. * ## `$inject` Annotation
  3098. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3099. *
  3100. * ## Inline
  3101. * As an array of injection names, where the last item in the array is the function to call.
  3102. */
  3103. /**
  3104. * @ngdoc method
  3105. * @name $injector#get
  3106. *
  3107. * @description
  3108. * Return an instance of the service.
  3109. *
  3110. * @param {string} name The name of the instance to retrieve.
  3111. * @return {*} The instance.
  3112. */
  3113. /**
  3114. * @ngdoc method
  3115. * @name $injector#invoke
  3116. *
  3117. * @description
  3118. * Invoke the method and supply the method arguments from the `$injector`.
  3119. *
  3120. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3121. * {@link guide/di $inject Annotation} rules.
  3122. * @param {Object=} self The `this` for the invoked method.
  3123. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3124. * object first, before the `$injector` is consulted.
  3125. * @returns {*} the value returned by the invoked `fn` function.
  3126. */
  3127. /**
  3128. * @ngdoc method
  3129. * @name $injector#has
  3130. *
  3131. * @description
  3132. * Allows the user to query if the particular service exists.
  3133. *
  3134. * @param {string} name Name of the service to query.
  3135. * @returns {boolean} `true` if injector has given service.
  3136. */
  3137. /**
  3138. * @ngdoc method
  3139. * @name $injector#instantiate
  3140. * @description
  3141. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3142. * operator, and supplies all of the arguments to the constructor function as specified by the
  3143. * constructor annotation.
  3144. *
  3145. * @param {Function} Type Annotated constructor function.
  3146. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3147. * object first, before the `$injector` is consulted.
  3148. * @returns {Object} new instance of `Type`.
  3149. */
  3150. /**
  3151. * @ngdoc method
  3152. * @name $injector#annotate
  3153. *
  3154. * @description
  3155. * Returns an array of service names which the function is requesting for injection. This API is
  3156. * used by the injector to determine which services need to be injected into the function when the
  3157. * function is invoked. There are three ways in which the function can be annotated with the needed
  3158. * dependencies.
  3159. *
  3160. * # Argument names
  3161. *
  3162. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3163. * by converting the function into a string using `toString()` method and extracting the argument
  3164. * names.
  3165. * ```js
  3166. * // Given
  3167. * function MyController($scope, $route) {
  3168. * // ...
  3169. * }
  3170. *
  3171. * // Then
  3172. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3173. * ```
  3174. *
  3175. * You can disallow this method by using strict injection mode.
  3176. *
  3177. * This method does not work with code minification / obfuscation. For this reason the following
  3178. * annotation strategies are supported.
  3179. *
  3180. * # The `$inject` property
  3181. *
  3182. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3183. * represent names of services to be injected into the function.
  3184. * ```js
  3185. * // Given
  3186. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3187. * // ...
  3188. * }
  3189. * // Define function dependencies
  3190. * MyController['$inject'] = ['$scope', '$route'];
  3191. *
  3192. * // Then
  3193. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3194. * ```
  3195. *
  3196. * # The array notation
  3197. *
  3198. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3199. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3200. * a way that survives minification is a better choice:
  3201. *
  3202. * ```js
  3203. * // We wish to write this (not minification / obfuscation safe)
  3204. * injector.invoke(function($compile, $rootScope) {
  3205. * // ...
  3206. * });
  3207. *
  3208. * // We are forced to write break inlining
  3209. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3210. * // ...
  3211. * };
  3212. * tmpFn.$inject = ['$compile', '$rootScope'];
  3213. * injector.invoke(tmpFn);
  3214. *
  3215. * // To better support inline function the inline annotation is supported
  3216. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3217. * // ...
  3218. * }]);
  3219. *
  3220. * // Therefore
  3221. * expect(injector.annotate(
  3222. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3223. * ).toEqual(['$compile', '$rootScope']);
  3224. * ```
  3225. *
  3226. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3227. * be retrieved as described above.
  3228. *
  3229. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3230. *
  3231. * @returns {Array.<string>} The names of the services which the function requires.
  3232. */
  3233. /**
  3234. * @ngdoc service
  3235. * @name $provide
  3236. *
  3237. * @description
  3238. *
  3239. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3240. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3241. * {@link angular.Module}.
  3242. *
  3243. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3244. * factories** are functions which, in turn, are created by a **service provider**.
  3245. * The **service providers** are constructor functions. When instantiated they must contain a
  3246. * property called `$get`, which holds the **service factory** function.
  3247. *
  3248. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3249. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3250. * function to get the instance of the **service**.
  3251. *
  3252. * Often services have no configuration options and there is no need to add methods to the service
  3253. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3254. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3255. * services without specifying a provider.
  3256. *
  3257. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3258. * {@link auto.$injector $injector}
  3259. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3260. * providers and services.
  3261. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3262. * services, not providers.
  3263. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3264. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3265. * given factory function.
  3266. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3267. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3268. * a new object using the given constructor function.
  3269. *
  3270. * See the individual methods for more information and examples.
  3271. */
  3272. /**
  3273. * @ngdoc method
  3274. * @name $provide#provider
  3275. * @description
  3276. *
  3277. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3278. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3279. * service.
  3280. *
  3281. * Service provider names start with the name of the service they provide followed by `Provider`.
  3282. * For example, the {@link ng.$log $log} service has a provider called
  3283. * {@link ng.$logProvider $logProvider}.
  3284. *
  3285. * Service provider objects can have additional methods which allow configuration of the provider
  3286. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3287. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3288. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3289. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3290. * console or not.
  3291. *
  3292. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3293. 'Provider'` key.
  3294. * @param {(Object|function())} provider If the provider is:
  3295. *
  3296. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3297. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3298. * - `Constructor`: a new instance of the provider will be created using
  3299. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3300. *
  3301. * @returns {Object} registered provider instance
  3302. * @example
  3303. *
  3304. * The following example shows how to create a simple event tracking service and register it using
  3305. * {@link auto.$provide#provider $provide.provider()}.
  3306. *
  3307. * ```js
  3308. * // Define the eventTracker provider
  3309. * function EventTrackerProvider() {
  3310. * var trackingUrl = '/track';
  3311. *
  3312. * // A provider method for configuring where the tracked events should been saved
  3313. * this.setTrackingUrl = function(url) {
  3314. * trackingUrl = url;
  3315. * };
  3316. *
  3317. * // The service factory function
  3318. * this.$get = ['$http', function($http) {
  3319. * var trackedEvents = {};
  3320. * return {
  3321. * // Call this to track an event
  3322. * event: function(event) {
  3323. * var count = trackedEvents[event] || 0;
  3324. * count += 1;
  3325. * trackedEvents[event] = count;
  3326. * return count;
  3327. * },
  3328. * // Call this to save the tracked events to the trackingUrl
  3329. * save: function() {
  3330. * $http.post(trackingUrl, trackedEvents);
  3331. * }
  3332. * };
  3333. * }];
  3334. * }
  3335. *
  3336. * describe('eventTracker', function() {
  3337. * var postSpy;
  3338. *
  3339. * beforeEach(module(function($provide) {
  3340. * // Register the eventTracker provider
  3341. * $provide.provider('eventTracker', EventTrackerProvider);
  3342. * }));
  3343. *
  3344. * beforeEach(module(function(eventTrackerProvider) {
  3345. * // Configure eventTracker provider
  3346. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3347. * }));
  3348. *
  3349. * it('tracks events', inject(function(eventTracker) {
  3350. * expect(eventTracker.event('login')).toEqual(1);
  3351. * expect(eventTracker.event('login')).toEqual(2);
  3352. * }));
  3353. *
  3354. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3355. * postSpy = spyOn($http, 'post');
  3356. * eventTracker.event('login');
  3357. * eventTracker.save();
  3358. * expect(postSpy).toHaveBeenCalled();
  3359. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3360. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3361. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3362. * }));
  3363. * });
  3364. * ```
  3365. */
  3366. /**
  3367. * @ngdoc method
  3368. * @name $provide#factory
  3369. * @description
  3370. *
  3371. * Register a **service factory**, which will be called to return the service instance.
  3372. * This is short for registering a service where its provider consists of only a `$get` property,
  3373. * which is the given service factory function.
  3374. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3375. * configure your service in a provider.
  3376. *
  3377. * @param {string} name The name of the instance.
  3378. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3379. * for `$provide.provider(name, {$get: $getFn})`.
  3380. * @returns {Object} registered provider instance
  3381. *
  3382. * @example
  3383. * Here is an example of registering a service
  3384. * ```js
  3385. * $provide.factory('ping', ['$http', function($http) {
  3386. * return function ping() {
  3387. * return $http.send('/ping');
  3388. * };
  3389. * }]);
  3390. * ```
  3391. * You would then inject and use this service like this:
  3392. * ```js
  3393. * someModule.controller('Ctrl', ['ping', function(ping) {
  3394. * ping();
  3395. * }]);
  3396. * ```
  3397. */
  3398. /**
  3399. * @ngdoc method
  3400. * @name $provide#service
  3401. * @description
  3402. *
  3403. * Register a **service constructor**, which will be invoked with `new` to create the service
  3404. * instance.
  3405. * This is short for registering a service where its provider's `$get` property is the service
  3406. * constructor function that will be used to instantiate the service instance.
  3407. *
  3408. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3409. * as a type/class.
  3410. *
  3411. * @param {string} name The name of the instance.
  3412. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3413. * @returns {Object} registered provider instance
  3414. *
  3415. * @example
  3416. * Here is an example of registering a service using
  3417. * {@link auto.$provide#service $provide.service(class)}.
  3418. * ```js
  3419. * var Ping = function($http) {
  3420. * this.$http = $http;
  3421. * };
  3422. *
  3423. * Ping.$inject = ['$http'];
  3424. *
  3425. * Ping.prototype.send = function() {
  3426. * return this.$http.get('/ping');
  3427. * };
  3428. * $provide.service('ping', Ping);
  3429. * ```
  3430. * You would then inject and use this service like this:
  3431. * ```js
  3432. * someModule.controller('Ctrl', ['ping', function(ping) {
  3433. * ping.send();
  3434. * }]);
  3435. * ```
  3436. */
  3437. /**
  3438. * @ngdoc method
  3439. * @name $provide#value
  3440. * @description
  3441. *
  3442. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3443. * number, an array, an object or a function. This is short for registering a service where its
  3444. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3445. * service**.
  3446. *
  3447. * Value services are similar to constant services, except that they cannot be injected into a
  3448. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3449. * an Angular
  3450. * {@link auto.$provide#decorator decorator}.
  3451. *
  3452. * @param {string} name The name of the instance.
  3453. * @param {*} value The value.
  3454. * @returns {Object} registered provider instance
  3455. *
  3456. * @example
  3457. * Here are some examples of creating value services.
  3458. * ```js
  3459. * $provide.value('ADMIN_USER', 'admin');
  3460. *
  3461. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3462. *
  3463. * $provide.value('halfOf', function(value) {
  3464. * return value / 2;
  3465. * });
  3466. * ```
  3467. */
  3468. /**
  3469. * @ngdoc method
  3470. * @name $provide#constant
  3471. * @description
  3472. *
  3473. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3474. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3475. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3476. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3477. *
  3478. * @param {string} name The name of the constant.
  3479. * @param {*} value The constant value.
  3480. * @returns {Object} registered instance
  3481. *
  3482. * @example
  3483. * Here a some examples of creating constants:
  3484. * ```js
  3485. * $provide.constant('SHARD_HEIGHT', 306);
  3486. *
  3487. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3488. *
  3489. * $provide.constant('double', function(value) {
  3490. * return value * 2;
  3491. * });
  3492. * ```
  3493. */
  3494. /**
  3495. * @ngdoc method
  3496. * @name $provide#decorator
  3497. * @description
  3498. *
  3499. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3500. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3501. * service. The object returned by the decorator may be the original service, or a new service
  3502. * object which replaces or wraps and delegates to the original service.
  3503. *
  3504. * @param {string} name The name of the service to decorate.
  3505. * @param {function()} decorator This function will be invoked when the service needs to be
  3506. * instantiated and should return the decorated service instance. The function is called using
  3507. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3508. * Local injection arguments:
  3509. *
  3510. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3511. * decorated or delegated to.
  3512. *
  3513. * @example
  3514. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3515. * calls to {@link ng.$log#error $log.warn()}.
  3516. * ```js
  3517. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3518. * $delegate.warn = $delegate.error;
  3519. * return $delegate;
  3520. * }]);
  3521. * ```
  3522. */
  3523. function createInjector(modulesToLoad, strictDi) {
  3524. strictDi = (strictDi === true);
  3525. var INSTANTIATING = {},
  3526. providerSuffix = 'Provider',
  3527. path = [],
  3528. loadedModules = new HashMap([], true),
  3529. providerCache = {
  3530. $provide: {
  3531. provider: supportObject(provider),
  3532. factory: supportObject(factory),
  3533. service: supportObject(service),
  3534. value: supportObject(value),
  3535. constant: supportObject(constant),
  3536. decorator: decorator
  3537. }
  3538. },
  3539. providerInjector = (providerCache.$injector =
  3540. createInternalInjector(providerCache, function() {
  3541. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3542. })),
  3543. instanceCache = {},
  3544. instanceInjector = (instanceCache.$injector =
  3545. createInternalInjector(instanceCache, function(servicename) {
  3546. var provider = providerInjector.get(servicename + providerSuffix);
  3547. return instanceInjector.invoke(provider.$get, provider, undefined, servicename);
  3548. }));
  3549. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3550. return instanceInjector;
  3551. ////////////////////////////////////
  3552. // $provider
  3553. ////////////////////////////////////
  3554. function supportObject(delegate) {
  3555. return function(key, value) {
  3556. if (isObject(key)) {
  3557. forEach(key, reverseParams(delegate));
  3558. } else {
  3559. return delegate(key, value);
  3560. }
  3561. };
  3562. }
  3563. function provider(name, provider_) {
  3564. assertNotHasOwnProperty(name, 'service');
  3565. if (isFunction(provider_) || isArray(provider_)) {
  3566. provider_ = providerInjector.instantiate(provider_);
  3567. }
  3568. if (!provider_.$get) {
  3569. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3570. }
  3571. return providerCache[name + providerSuffix] = provider_;
  3572. }
  3573. function enforceReturnValue(name, factory) {
  3574. return function enforcedReturnValue() {
  3575. var result = instanceInjector.invoke(factory, this, undefined, name);
  3576. if (isUndefined(result)) {
  3577. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3578. }
  3579. return result;
  3580. };
  3581. }
  3582. function factory(name, factoryFn, enforce) {
  3583. return provider(name, {
  3584. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3585. });
  3586. }
  3587. function service(name, constructor) {
  3588. return factory(name, ['$injector', function($injector) {
  3589. return $injector.instantiate(constructor);
  3590. }]);
  3591. }
  3592. function value(name, val) { return factory(name, valueFn(val), false); }
  3593. function constant(name, value) {
  3594. assertNotHasOwnProperty(name, 'constant');
  3595. providerCache[name] = value;
  3596. instanceCache[name] = value;
  3597. }
  3598. function decorator(serviceName, decorFn) {
  3599. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3600. orig$get = origProvider.$get;
  3601. origProvider.$get = function() {
  3602. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3603. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3604. };
  3605. }
  3606. ////////////////////////////////////
  3607. // Module Loading
  3608. ////////////////////////////////////
  3609. function loadModules(modulesToLoad) {
  3610. var runBlocks = [], moduleFn;
  3611. forEach(modulesToLoad, function(module) {
  3612. if (loadedModules.get(module)) return;
  3613. loadedModules.put(module, true);
  3614. function runInvokeQueue(queue) {
  3615. var i, ii;
  3616. for (i = 0, ii = queue.length; i < ii; i++) {
  3617. var invokeArgs = queue[i],
  3618. provider = providerInjector.get(invokeArgs[0]);
  3619. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3620. }
  3621. }
  3622. try {
  3623. if (isString(module)) {
  3624. moduleFn = angularModule(module);
  3625. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3626. runInvokeQueue(moduleFn._invokeQueue);
  3627. runInvokeQueue(moduleFn._configBlocks);
  3628. } else if (isFunction(module)) {
  3629. runBlocks.push(providerInjector.invoke(module));
  3630. } else if (isArray(module)) {
  3631. runBlocks.push(providerInjector.invoke(module));
  3632. } else {
  3633. assertArgFn(module, 'module');
  3634. }
  3635. } catch (e) {
  3636. if (isArray(module)) {
  3637. module = module[module.length - 1];
  3638. }
  3639. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3640. // Safari & FF's stack traces don't contain error.message content
  3641. // unlike those of Chrome and IE
  3642. // So if stack doesn't contain message, we create a new string that contains both.
  3643. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3644. /* jshint -W022 */
  3645. e = e.message + '\n' + e.stack;
  3646. }
  3647. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3648. module, e.stack || e.message || e);
  3649. }
  3650. });
  3651. return runBlocks;
  3652. }
  3653. ////////////////////////////////////
  3654. // internal Injector
  3655. ////////////////////////////////////
  3656. function createInternalInjector(cache, factory) {
  3657. function getService(serviceName) {
  3658. if (cache.hasOwnProperty(serviceName)) {
  3659. if (cache[serviceName] === INSTANTIATING) {
  3660. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3661. serviceName + ' <- ' + path.join(' <- '));
  3662. }
  3663. return cache[serviceName];
  3664. } else {
  3665. try {
  3666. path.unshift(serviceName);
  3667. cache[serviceName] = INSTANTIATING;
  3668. return cache[serviceName] = factory(serviceName);
  3669. } catch (err) {
  3670. if (cache[serviceName] === INSTANTIATING) {
  3671. delete cache[serviceName];
  3672. }
  3673. throw err;
  3674. } finally {
  3675. path.shift();
  3676. }
  3677. }
  3678. }
  3679. function invoke(fn, self, locals, serviceName) {
  3680. if (typeof locals === 'string') {
  3681. serviceName = locals;
  3682. locals = null;
  3683. }
  3684. var args = [],
  3685. $inject = annotate(fn, strictDi, serviceName),
  3686. length, i,
  3687. key;
  3688. for (i = 0, length = $inject.length; i < length; i++) {
  3689. key = $inject[i];
  3690. if (typeof key !== 'string') {
  3691. throw $injectorMinErr('itkn',
  3692. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3693. }
  3694. args.push(
  3695. locals && locals.hasOwnProperty(key)
  3696. ? locals[key]
  3697. : getService(key)
  3698. );
  3699. }
  3700. if (isArray(fn)) {
  3701. fn = fn[length];
  3702. }
  3703. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3704. // #5388
  3705. return fn.apply(self, args);
  3706. }
  3707. function instantiate(Type, locals, serviceName) {
  3708. // Check if Type is annotated and use just the given function at n-1 as parameter
  3709. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3710. // Object creation: http://jsperf.com/create-constructor/2
  3711. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype);
  3712. var returnedValue = invoke(Type, instance, locals, serviceName);
  3713. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3714. }
  3715. return {
  3716. invoke: invoke,
  3717. instantiate: instantiate,
  3718. get: getService,
  3719. annotate: annotate,
  3720. has: function(name) {
  3721. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3722. }
  3723. };
  3724. }
  3725. }
  3726. createInjector.$$annotate = annotate;
  3727. /**
  3728. * @ngdoc provider
  3729. * @name $anchorScrollProvider
  3730. *
  3731. * @description
  3732. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3733. * {@link ng.$location#hash $location.hash()} changes.
  3734. */
  3735. function $AnchorScrollProvider() {
  3736. var autoScrollingEnabled = true;
  3737. /**
  3738. * @ngdoc method
  3739. * @name $anchorScrollProvider#disableAutoScrolling
  3740. *
  3741. * @description
  3742. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3743. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3744. * Use this method to disable automatic scrolling.
  3745. *
  3746. * If automatic scrolling is disabled, one must explicitly call
  3747. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3748. * current hash.
  3749. */
  3750. this.disableAutoScrolling = function() {
  3751. autoScrollingEnabled = false;
  3752. };
  3753. /**
  3754. * @ngdoc service
  3755. * @name $anchorScroll
  3756. * @kind function
  3757. * @requires $window
  3758. * @requires $location
  3759. * @requires $rootScope
  3760. *
  3761. * @description
  3762. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3763. * scrolls to the related element, according to the rules specified in the
  3764. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3765. *
  3766. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3767. * match any anchor whenever it changes. This can be disabled by calling
  3768. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3769. *
  3770. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3771. * vertical scroll-offset (either fixed or dynamic).
  3772. *
  3773. * @property {(number|function|jqLite)} yOffset
  3774. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3775. * positioned elements at the top of the page, such as navbars, headers etc.
  3776. *
  3777. * `yOffset` can be specified in various ways:
  3778. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3779. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3780. * a number representing the offset (in pixels).<br /><br />
  3781. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3782. * the top of the page to the element's bottom will be used as offset.<br />
  3783. * **Note**: The element will be taken into account only as long as its `position` is set to
  3784. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3785. * their height and/or positioning according to the viewport's size.
  3786. *
  3787. * <br />
  3788. * <div class="alert alert-warning">
  3789. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3790. * not some child element.
  3791. * </div>
  3792. *
  3793. * @example
  3794. <example module="anchorScrollExample">
  3795. <file name="index.html">
  3796. <div id="scrollArea" ng-controller="ScrollController">
  3797. <a ng-click="gotoBottom()">Go to bottom</a>
  3798. <a id="bottom"></a> You're at the bottom!
  3799. </div>
  3800. </file>
  3801. <file name="script.js">
  3802. angular.module('anchorScrollExample', [])
  3803. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3804. function ($scope, $location, $anchorScroll) {
  3805. $scope.gotoBottom = function() {
  3806. // set the location.hash to the id of
  3807. // the element you wish to scroll to.
  3808. $location.hash('bottom');
  3809. // call $anchorScroll()
  3810. $anchorScroll();
  3811. };
  3812. }]);
  3813. </file>
  3814. <file name="style.css">
  3815. #scrollArea {
  3816. height: 280px;
  3817. overflow: auto;
  3818. }
  3819. #bottom {
  3820. display: block;
  3821. margin-top: 2000px;
  3822. }
  3823. </file>
  3824. </example>
  3825. *
  3826. * <hr />
  3827. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3828. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3829. *
  3830. * @example
  3831. <example module="anchorScrollOffsetExample">
  3832. <file name="index.html">
  3833. <div class="fixed-header" ng-controller="headerCtrl">
  3834. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3835. Go to anchor {{x}}
  3836. </a>
  3837. </div>
  3838. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3839. Anchor {{x}} of 5
  3840. </div>
  3841. </file>
  3842. <file name="script.js">
  3843. angular.module('anchorScrollOffsetExample', [])
  3844. .run(['$anchorScroll', function($anchorScroll) {
  3845. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3846. }])
  3847. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3848. function ($anchorScroll, $location, $scope) {
  3849. $scope.gotoAnchor = function(x) {
  3850. var newHash = 'anchor' + x;
  3851. if ($location.hash() !== newHash) {
  3852. // set the $location.hash to `newHash` and
  3853. // $anchorScroll will automatically scroll to it
  3854. $location.hash('anchor' + x);
  3855. } else {
  3856. // call $anchorScroll() explicitly,
  3857. // since $location.hash hasn't changed
  3858. $anchorScroll();
  3859. }
  3860. };
  3861. }
  3862. ]);
  3863. </file>
  3864. <file name="style.css">
  3865. body {
  3866. padding-top: 50px;
  3867. }
  3868. .anchor {
  3869. border: 2px dashed DarkOrchid;
  3870. padding: 10px 10px 200px 10px;
  3871. }
  3872. .fixed-header {
  3873. background-color: rgba(0, 0, 0, 0.2);
  3874. height: 50px;
  3875. position: fixed;
  3876. top: 0; left: 0; right: 0;
  3877. }
  3878. .fixed-header > a {
  3879. display: inline-block;
  3880. margin: 5px 15px;
  3881. }
  3882. </file>
  3883. </example>
  3884. */
  3885. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3886. var document = $window.document;
  3887. // Helper function to get first anchor from a NodeList
  3888. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3889. // and working in all supported browsers.)
  3890. function getFirstAnchor(list) {
  3891. var result = null;
  3892. Array.prototype.some.call(list, function(element) {
  3893. if (nodeName_(element) === 'a') {
  3894. result = element;
  3895. return true;
  3896. }
  3897. });
  3898. return result;
  3899. }
  3900. function getYOffset() {
  3901. var offset = scroll.yOffset;
  3902. if (isFunction(offset)) {
  3903. offset = offset();
  3904. } else if (isElement(offset)) {
  3905. var elem = offset[0];
  3906. var style = $window.getComputedStyle(elem);
  3907. if (style.position !== 'fixed') {
  3908. offset = 0;
  3909. } else {
  3910. offset = elem.getBoundingClientRect().bottom;
  3911. }
  3912. } else if (!isNumber(offset)) {
  3913. offset = 0;
  3914. }
  3915. return offset;
  3916. }
  3917. function scrollTo(elem) {
  3918. if (elem) {
  3919. elem.scrollIntoView();
  3920. var offset = getYOffset();
  3921. if (offset) {
  3922. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3923. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3924. // top of the viewport.
  3925. //
  3926. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3927. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3928. // way down the page.
  3929. //
  3930. // This is often the case for elements near the bottom of the page.
  3931. //
  3932. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3933. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3934. // desired position.
  3935. var elemTop = elem.getBoundingClientRect().top;
  3936. $window.scrollBy(0, elemTop - offset);
  3937. }
  3938. } else {
  3939. $window.scrollTo(0, 0);
  3940. }
  3941. }
  3942. function scroll() {
  3943. var hash = $location.hash(), elm;
  3944. // empty hash, scroll to the top of the page
  3945. if (!hash) scrollTo(null);
  3946. // element with given id
  3947. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  3948. // first anchor with given name :-D
  3949. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  3950. // no element and hash == 'top', scroll to the top of the page
  3951. else if (hash === 'top') scrollTo(null);
  3952. }
  3953. // does not scroll when user clicks on anchor link that is currently on
  3954. // (no url change, no $location.hash() change), browser native does scroll
  3955. if (autoScrollingEnabled) {
  3956. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3957. function autoScrollWatchAction(newVal, oldVal) {
  3958. // skip the initial scroll if $location.hash is empty
  3959. if (newVal === oldVal && newVal === '') return;
  3960. jqLiteDocumentLoaded(function() {
  3961. $rootScope.$evalAsync(scroll);
  3962. });
  3963. });
  3964. }
  3965. return scroll;
  3966. }];
  3967. }
  3968. var $animateMinErr = minErr('$animate');
  3969. /**
  3970. * @ngdoc provider
  3971. * @name $animateProvider
  3972. *
  3973. * @description
  3974. * Default implementation of $animate that doesn't perform any animations, instead just
  3975. * synchronously performs DOM
  3976. * updates and calls done() callbacks.
  3977. *
  3978. * In order to enable animations the ngAnimate module has to be loaded.
  3979. *
  3980. * To see the functional implementation check out src/ngAnimate/animate.js
  3981. */
  3982. var $AnimateProvider = ['$provide', function($provide) {
  3983. this.$$selectors = {};
  3984. /**
  3985. * @ngdoc method
  3986. * @name $animateProvider#register
  3987. *
  3988. * @description
  3989. * Registers a new injectable animation factory function. The factory function produces the
  3990. * animation object which contains callback functions for each event that is expected to be
  3991. * animated.
  3992. *
  3993. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3994. * must be called once the element animation is complete. If a function is returned then the
  3995. * animation service will use this function to cancel the animation whenever a cancel event is
  3996. * triggered.
  3997. *
  3998. *
  3999. * ```js
  4000. * return {
  4001. * eventFn : function(element, done) {
  4002. * //code to run the animation
  4003. * //once complete, then run done()
  4004. * return function cancellationFunction() {
  4005. * //code to cancel the animation
  4006. * }
  4007. * }
  4008. * }
  4009. * ```
  4010. *
  4011. * @param {string} name The name of the animation.
  4012. * @param {Function} factory The factory function that will be executed to return the animation
  4013. * object.
  4014. */
  4015. this.register = function(name, factory) {
  4016. var key = name + '-animation';
  4017. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4018. "Expecting class selector starting with '.' got '{0}'.", name);
  4019. this.$$selectors[name.substr(1)] = key;
  4020. $provide.factory(key, factory);
  4021. };
  4022. /**
  4023. * @ngdoc method
  4024. * @name $animateProvider#classNameFilter
  4025. *
  4026. * @description
  4027. * Sets and/or returns the CSS class regular expression that is checked when performing
  4028. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4029. * therefore enable $animate to attempt to perform an animation on any element.
  4030. * When setting the classNameFilter value, animations will only be performed on elements
  4031. * that successfully match the filter expression. This in turn can boost performance
  4032. * for low-powered devices as well as applications containing a lot of structural operations.
  4033. * @param {RegExp=} expression The className expression which will be checked against all animations
  4034. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4035. */
  4036. this.classNameFilter = function(expression) {
  4037. if (arguments.length === 1) {
  4038. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4039. }
  4040. return this.$$classNameFilter;
  4041. };
  4042. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4043. var currentDefer;
  4044. function runAnimationPostDigest(fn) {
  4045. var cancelFn, defer = $$q.defer();
  4046. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4047. cancelFn && cancelFn();
  4048. };
  4049. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4050. cancelFn = fn(function ngAnimateNotifyComplete() {
  4051. defer.resolve();
  4052. });
  4053. });
  4054. return defer.promise;
  4055. }
  4056. function resolveElementClasses(element, classes) {
  4057. var toAdd = [], toRemove = [];
  4058. var hasClasses = createMap();
  4059. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4060. hasClasses[className] = true;
  4061. });
  4062. forEach(classes, function(status, className) {
  4063. var hasClass = hasClasses[className];
  4064. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4065. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4066. // the most recent class manipulation (via $animate) was to add the class, and the
  4067. // element does not currently have the class, the class is scheduled to be added.
  4068. if (status === false && hasClass) {
  4069. toRemove.push(className);
  4070. } else if (status === true && !hasClass) {
  4071. toAdd.push(className);
  4072. }
  4073. });
  4074. return (toAdd.length + toRemove.length) > 0 &&
  4075. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4076. }
  4077. function cachedClassManipulation(cache, classes, op) {
  4078. for (var i=0, ii = classes.length; i < ii; ++i) {
  4079. var className = classes[i];
  4080. cache[className] = op;
  4081. }
  4082. }
  4083. function asyncPromise() {
  4084. // only serve one instance of a promise in order to save CPU cycles
  4085. if (!currentDefer) {
  4086. currentDefer = $$q.defer();
  4087. $$asyncCallback(function() {
  4088. currentDefer.resolve();
  4089. currentDefer = null;
  4090. });
  4091. }
  4092. return currentDefer.promise;
  4093. }
  4094. function applyStyles(element, options) {
  4095. if (angular.isObject(options)) {
  4096. var styles = extend(options.from || {}, options.to || {});
  4097. element.css(styles);
  4098. }
  4099. }
  4100. /**
  4101. *
  4102. * @ngdoc service
  4103. * @name $animate
  4104. * @description The $animate service provides rudimentary DOM manipulation functions to
  4105. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4106. * This service is the core service used by the ngAnimate $animator service which provides
  4107. * high-level animation hooks for CSS and JavaScript.
  4108. *
  4109. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4110. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4111. * manipulation operations.
  4112. *
  4113. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4114. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4115. * page}.
  4116. */
  4117. return {
  4118. animate: function(element, from, to) {
  4119. applyStyles(element, { from: from, to: to });
  4120. return asyncPromise();
  4121. },
  4122. /**
  4123. *
  4124. * @ngdoc method
  4125. * @name $animate#enter
  4126. * @kind function
  4127. * @description Inserts the element into the DOM either after the `after` element or
  4128. * as the first child within the `parent` element. When the function is called a promise
  4129. * is returned that will be resolved at a later time.
  4130. * @param {DOMElement} element the element which will be inserted into the DOM
  4131. * @param {DOMElement} parent the parent element which will append the element as
  4132. * a child (if the after element is not present)
  4133. * @param {DOMElement} after the sibling element which will append the element
  4134. * after itself
  4135. * @param {object=} options an optional collection of styles that will be applied to the element.
  4136. * @return {Promise} the animation callback promise
  4137. */
  4138. enter: function(element, parent, after, options) {
  4139. applyStyles(element, options);
  4140. after ? after.after(element)
  4141. : parent.prepend(element);
  4142. return asyncPromise();
  4143. },
  4144. /**
  4145. *
  4146. * @ngdoc method
  4147. * @name $animate#leave
  4148. * @kind function
  4149. * @description Removes the element from the DOM. When the function is called a promise
  4150. * is returned that will be resolved at a later time.
  4151. * @param {DOMElement} element the element which will be removed from the DOM
  4152. * @param {object=} options an optional collection of options that will be applied to the element.
  4153. * @return {Promise} the animation callback promise
  4154. */
  4155. leave: function(element, options) {
  4156. element.remove();
  4157. return asyncPromise();
  4158. },
  4159. /**
  4160. *
  4161. * @ngdoc method
  4162. * @name $animate#move
  4163. * @kind function
  4164. * @description Moves the position of the provided element within the DOM to be placed
  4165. * either after the `after` element or inside of the `parent` element. When the function
  4166. * is called a promise is returned that will be resolved at a later time.
  4167. *
  4168. * @param {DOMElement} element the element which will be moved around within the
  4169. * DOM
  4170. * @param {DOMElement} parent the parent element where the element will be
  4171. * inserted into (if the after element is not present)
  4172. * @param {DOMElement} after the sibling element where the element will be
  4173. * positioned next to
  4174. * @param {object=} options an optional collection of options that will be applied to the element.
  4175. * @return {Promise} the animation callback promise
  4176. */
  4177. move: function(element, parent, after, options) {
  4178. // Do not remove element before insert. Removing will cause data associated with the
  4179. // element to be dropped. Insert will implicitly do the remove.
  4180. return this.enter(element, parent, after, options);
  4181. },
  4182. /**
  4183. *
  4184. * @ngdoc method
  4185. * @name $animate#addClass
  4186. * @kind function
  4187. * @description Adds the provided className CSS class value to the provided element.
  4188. * When the function is called a promise is returned that will be resolved at a later time.
  4189. * @param {DOMElement} element the element which will have the className value
  4190. * added to it
  4191. * @param {string} className the CSS class which will be added to the element
  4192. * @param {object=} options an optional collection of options that will be applied to the element.
  4193. * @return {Promise} the animation callback promise
  4194. */
  4195. addClass: function(element, className, options) {
  4196. return this.setClass(element, className, [], options);
  4197. },
  4198. $$addClassImmediately: function(element, className, options) {
  4199. element = jqLite(element);
  4200. className = !isString(className)
  4201. ? (isArray(className) ? className.join(' ') : '')
  4202. : className;
  4203. forEach(element, function(element) {
  4204. jqLiteAddClass(element, className);
  4205. });
  4206. applyStyles(element, options);
  4207. return asyncPromise();
  4208. },
  4209. /**
  4210. *
  4211. * @ngdoc method
  4212. * @name $animate#removeClass
  4213. * @kind function
  4214. * @description Removes the provided className CSS class value from the provided element.
  4215. * When the function is called a promise is returned that will be resolved at a later time.
  4216. * @param {DOMElement} element the element which will have the className value
  4217. * removed from it
  4218. * @param {string} className the CSS class which will be removed from the element
  4219. * @param {object=} options an optional collection of options that will be applied to the element.
  4220. * @return {Promise} the animation callback promise
  4221. */
  4222. removeClass: function(element, className, options) {
  4223. return this.setClass(element, [], className, options);
  4224. },
  4225. $$removeClassImmediately: function(element, className, options) {
  4226. element = jqLite(element);
  4227. className = !isString(className)
  4228. ? (isArray(className) ? className.join(' ') : '')
  4229. : className;
  4230. forEach(element, function(element) {
  4231. jqLiteRemoveClass(element, className);
  4232. });
  4233. applyStyles(element, options);
  4234. return asyncPromise();
  4235. },
  4236. /**
  4237. *
  4238. * @ngdoc method
  4239. * @name $animate#setClass
  4240. * @kind function
  4241. * @description Adds and/or removes the given CSS classes to and from the element.
  4242. * When the function is called a promise is returned that will be resolved at a later time.
  4243. * @param {DOMElement} element the element which will have its CSS classes changed
  4244. * removed from it
  4245. * @param {string} add the CSS classes which will be added to the element
  4246. * @param {string} remove the CSS class which will be removed from the element
  4247. * @param {object=} options an optional collection of options that will be applied to the element.
  4248. * @return {Promise} the animation callback promise
  4249. */
  4250. setClass: function(element, add, remove, options) {
  4251. var self = this;
  4252. var STORAGE_KEY = '$$animateClasses';
  4253. var createdCache = false;
  4254. element = jqLite(element);
  4255. var cache = element.data(STORAGE_KEY);
  4256. if (!cache) {
  4257. cache = {
  4258. classes: {},
  4259. options: options
  4260. };
  4261. createdCache = true;
  4262. } else if (options && cache.options) {
  4263. cache.options = angular.extend(cache.options || {}, options);
  4264. }
  4265. var classes = cache.classes;
  4266. add = isArray(add) ? add : add.split(' ');
  4267. remove = isArray(remove) ? remove : remove.split(' ');
  4268. cachedClassManipulation(classes, add, true);
  4269. cachedClassManipulation(classes, remove, false);
  4270. if (createdCache) {
  4271. cache.promise = runAnimationPostDigest(function(done) {
  4272. var cache = element.data(STORAGE_KEY);
  4273. element.removeData(STORAGE_KEY);
  4274. // in the event that the element is removed before postDigest
  4275. // is run then the cache will be undefined and there will be
  4276. // no need anymore to add or remove and of the element classes
  4277. if (cache) {
  4278. var classes = resolveElementClasses(element, cache.classes);
  4279. if (classes) {
  4280. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4281. }
  4282. }
  4283. done();
  4284. });
  4285. element.data(STORAGE_KEY, cache);
  4286. }
  4287. return cache.promise;
  4288. },
  4289. $$setClassImmediately: function(element, add, remove, options) {
  4290. add && this.$$addClassImmediately(element, add);
  4291. remove && this.$$removeClassImmediately(element, remove);
  4292. applyStyles(element, options);
  4293. return asyncPromise();
  4294. },
  4295. enabled: noop,
  4296. cancel: noop
  4297. };
  4298. }];
  4299. }];
  4300. function $$AsyncCallbackProvider() {
  4301. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4302. return $$rAF.supported
  4303. ? function(fn) { return $$rAF(fn); }
  4304. : function(fn) {
  4305. return $timeout(fn, 0, false);
  4306. };
  4307. }];
  4308. }
  4309. /* global stripHash: true */
  4310. /**
  4311. * ! This is a private undocumented service !
  4312. *
  4313. * @name $browser
  4314. * @requires $log
  4315. * @description
  4316. * This object has two goals:
  4317. *
  4318. * - hide all the global state in the browser caused by the window object
  4319. * - abstract away all the browser specific features and inconsistencies
  4320. *
  4321. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4322. * service, which can be used for convenient testing of the application without the interaction with
  4323. * the real browser apis.
  4324. */
  4325. /**
  4326. * @param {object} window The global window object.
  4327. * @param {object} document jQuery wrapped document.
  4328. * @param {object} $log window.console or an object with the same interface.
  4329. * @param {object} $sniffer $sniffer service
  4330. */
  4331. function Browser(window, document, $log, $sniffer) {
  4332. var self = this,
  4333. rawDocument = document[0],
  4334. location = window.location,
  4335. history = window.history,
  4336. setTimeout = window.setTimeout,
  4337. clearTimeout = window.clearTimeout,
  4338. pendingDeferIds = {};
  4339. self.isMock = false;
  4340. var outstandingRequestCount = 0;
  4341. var outstandingRequestCallbacks = [];
  4342. // TODO(vojta): remove this temporary api
  4343. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4344. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4345. /**
  4346. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4347. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4348. */
  4349. function completeOutstandingRequest(fn) {
  4350. try {
  4351. fn.apply(null, sliceArgs(arguments, 1));
  4352. } finally {
  4353. outstandingRequestCount--;
  4354. if (outstandingRequestCount === 0) {
  4355. while (outstandingRequestCallbacks.length) {
  4356. try {
  4357. outstandingRequestCallbacks.pop()();
  4358. } catch (e) {
  4359. $log.error(e);
  4360. }
  4361. }
  4362. }
  4363. }
  4364. }
  4365. /**
  4366. * @private
  4367. * Note: this method is used only by scenario runner
  4368. * TODO(vojta): prefix this method with $$ ?
  4369. * @param {function()} callback Function that will be called when no outstanding request
  4370. */
  4371. self.notifyWhenNoOutstandingRequests = function(callback) {
  4372. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4373. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4374. // regular poller would result in flaky tests.
  4375. forEach(pollFns, function(pollFn) { pollFn(); });
  4376. if (outstandingRequestCount === 0) {
  4377. callback();
  4378. } else {
  4379. outstandingRequestCallbacks.push(callback);
  4380. }
  4381. };
  4382. //////////////////////////////////////////////////////////////
  4383. // Poll Watcher API
  4384. //////////////////////////////////////////////////////////////
  4385. var pollFns = [],
  4386. pollTimeout;
  4387. /**
  4388. * @name $browser#addPollFn
  4389. *
  4390. * @param {function()} fn Poll function to add
  4391. *
  4392. * @description
  4393. * Adds a function to the list of functions that poller periodically executes,
  4394. * and starts polling if not started yet.
  4395. *
  4396. * @returns {function()} the added function
  4397. */
  4398. self.addPollFn = function(fn) {
  4399. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4400. pollFns.push(fn);
  4401. return fn;
  4402. };
  4403. /**
  4404. * @param {number} interval How often should browser call poll functions (ms)
  4405. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4406. *
  4407. * @description
  4408. * Configures the poller to run in the specified intervals, using the specified
  4409. * setTimeout fn and kicks it off.
  4410. */
  4411. function startPoller(interval, setTimeout) {
  4412. (function check() {
  4413. forEach(pollFns, function(pollFn) { pollFn(); });
  4414. pollTimeout = setTimeout(check, interval);
  4415. })();
  4416. }
  4417. //////////////////////////////////////////////////////////////
  4418. // URL API
  4419. //////////////////////////////////////////////////////////////
  4420. var cachedState, lastHistoryState,
  4421. lastBrowserUrl = location.href,
  4422. baseElement = document.find('base'),
  4423. reloadLocation = null;
  4424. cacheState();
  4425. lastHistoryState = cachedState;
  4426. /**
  4427. * @name $browser#url
  4428. *
  4429. * @description
  4430. * GETTER:
  4431. * Without any argument, this method just returns current value of location.href.
  4432. *
  4433. * SETTER:
  4434. * With at least one argument, this method sets url to new value.
  4435. * If html5 history api supported, pushState/replaceState is used, otherwise
  4436. * location.href/location.replace is used.
  4437. * Returns its own instance to allow chaining
  4438. *
  4439. * NOTE: this api is intended for use only by the $location service. Please use the
  4440. * {@link ng.$location $location service} to change url.
  4441. *
  4442. * @param {string} url New url (when used as setter)
  4443. * @param {boolean=} replace Should new url replace current history record?
  4444. * @param {object=} state object to use with pushState/replaceState
  4445. */
  4446. self.url = function(url, replace, state) {
  4447. // In modern browsers `history.state` is `null` by default; treating it separately
  4448. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4449. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4450. if (isUndefined(state)) {
  4451. state = null;
  4452. }
  4453. // Android Browser BFCache causes location, history reference to become stale.
  4454. if (location !== window.location) location = window.location;
  4455. if (history !== window.history) history = window.history;
  4456. // setter
  4457. if (url) {
  4458. var sameState = lastHistoryState === state;
  4459. // Don't change anything if previous and current URLs and states match. This also prevents
  4460. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4461. // See https://github.com/angular/angular.js/commit/ffb2701
  4462. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4463. return self;
  4464. }
  4465. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4466. lastBrowserUrl = url;
  4467. lastHistoryState = state;
  4468. // Don't use history API if only the hash changed
  4469. // due to a bug in IE10/IE11 which leads
  4470. // to not firing a `hashchange` nor `popstate` event
  4471. // in some cases (see #9143).
  4472. if ($sniffer.history && (!sameBase || !sameState)) {
  4473. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4474. cacheState();
  4475. // Do the assignment again so that those two variables are referentially identical.
  4476. lastHistoryState = cachedState;
  4477. } else {
  4478. if (!sameBase) {
  4479. reloadLocation = url;
  4480. }
  4481. if (replace) {
  4482. location.replace(url);
  4483. } else {
  4484. location.href = url;
  4485. }
  4486. }
  4487. return self;
  4488. // getter
  4489. } else {
  4490. // - reloadLocation is needed as browsers don't allow to read out
  4491. // the new location.href if a reload happened.
  4492. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4493. return reloadLocation || location.href.replace(/%27/g,"'");
  4494. }
  4495. };
  4496. /**
  4497. * @name $browser#state
  4498. *
  4499. * @description
  4500. * This method is a getter.
  4501. *
  4502. * Return history.state or null if history.state is undefined.
  4503. *
  4504. * @returns {object} state
  4505. */
  4506. self.state = function() {
  4507. return cachedState;
  4508. };
  4509. var urlChangeListeners = [],
  4510. urlChangeInit = false;
  4511. function cacheStateAndFireUrlChange() {
  4512. cacheState();
  4513. fireUrlChange();
  4514. }
  4515. // This variable should be used *only* inside the cacheState function.
  4516. var lastCachedState = null;
  4517. function cacheState() {
  4518. // This should be the only place in $browser where `history.state` is read.
  4519. cachedState = window.history.state;
  4520. cachedState = isUndefined(cachedState) ? null : cachedState;
  4521. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4522. if (equals(cachedState, lastCachedState)) {
  4523. cachedState = lastCachedState;
  4524. }
  4525. lastCachedState = cachedState;
  4526. }
  4527. function fireUrlChange() {
  4528. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4529. return;
  4530. }
  4531. lastBrowserUrl = self.url();
  4532. lastHistoryState = cachedState;
  4533. forEach(urlChangeListeners, function(listener) {
  4534. listener(self.url(), cachedState);
  4535. });
  4536. }
  4537. /**
  4538. * @name $browser#onUrlChange
  4539. *
  4540. * @description
  4541. * Register callback function that will be called, when url changes.
  4542. *
  4543. * It's only called when the url is changed from outside of angular:
  4544. * - user types different url into address bar
  4545. * - user clicks on history (forward/back) button
  4546. * - user clicks on a link
  4547. *
  4548. * It's not called when url is changed by $browser.url() method
  4549. *
  4550. * The listener gets called with new url as parameter.
  4551. *
  4552. * NOTE: this api is intended for use only by the $location service. Please use the
  4553. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4554. *
  4555. * @param {function(string)} listener Listener function to be called when url changes.
  4556. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4557. */
  4558. self.onUrlChange = function(callback) {
  4559. // TODO(vojta): refactor to use node's syntax for events
  4560. if (!urlChangeInit) {
  4561. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4562. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4563. // changed by push/replaceState
  4564. // html5 history api - popstate event
  4565. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4566. // hashchange event
  4567. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4568. urlChangeInit = true;
  4569. }
  4570. urlChangeListeners.push(callback);
  4571. return callback;
  4572. };
  4573. /**
  4574. * Checks whether the url has changed outside of Angular.
  4575. * Needs to be exported to be able to check for changes that have been done in sync,
  4576. * as hashchange/popstate events fire in async.
  4577. */
  4578. self.$$checkUrlChange = fireUrlChange;
  4579. //////////////////////////////////////////////////////////////
  4580. // Misc API
  4581. //////////////////////////////////////////////////////////////
  4582. /**
  4583. * @name $browser#baseHref
  4584. *
  4585. * @description
  4586. * Returns current <base href>
  4587. * (always relative - without domain)
  4588. *
  4589. * @returns {string} The current base href
  4590. */
  4591. self.baseHref = function() {
  4592. var href = baseElement.attr('href');
  4593. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4594. };
  4595. //////////////////////////////////////////////////////////////
  4596. // Cookies API
  4597. //////////////////////////////////////////////////////////////
  4598. var lastCookies = {};
  4599. var lastCookieString = '';
  4600. var cookiePath = self.baseHref();
  4601. function safeDecodeURIComponent(str) {
  4602. try {
  4603. return decodeURIComponent(str);
  4604. } catch (e) {
  4605. return str;
  4606. }
  4607. }
  4608. /**
  4609. * @name $browser#cookies
  4610. *
  4611. * @param {string=} name Cookie name
  4612. * @param {string=} value Cookie value
  4613. *
  4614. * @description
  4615. * The cookies method provides a 'private' low level access to browser cookies.
  4616. * It is not meant to be used directly, use the $cookie service instead.
  4617. *
  4618. * The return values vary depending on the arguments that the method was called with as follows:
  4619. *
  4620. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4621. * it
  4622. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4623. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4624. * way)
  4625. *
  4626. * @returns {Object} Hash of all cookies (if called without any parameter)
  4627. */
  4628. self.cookies = function(name, value) {
  4629. var cookieLength, cookieArray, cookie, i, index;
  4630. if (name) {
  4631. if (value === undefined) {
  4632. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4633. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4634. } else {
  4635. if (isString(value)) {
  4636. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4637. ';path=' + cookiePath).length + 1;
  4638. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4639. // - 300 cookies
  4640. // - 20 cookies per unique domain
  4641. // - 4096 bytes per cookie
  4642. if (cookieLength > 4096) {
  4643. $log.warn("Cookie '" + name +
  4644. "' possibly not set or overflowed because it was too large (" +
  4645. cookieLength + " > 4096 bytes)!");
  4646. }
  4647. }
  4648. }
  4649. } else {
  4650. if (rawDocument.cookie !== lastCookieString) {
  4651. lastCookieString = rawDocument.cookie;
  4652. cookieArray = lastCookieString.split("; ");
  4653. lastCookies = {};
  4654. for (i = 0; i < cookieArray.length; i++) {
  4655. cookie = cookieArray[i];
  4656. index = cookie.indexOf('=');
  4657. if (index > 0) { //ignore nameless cookies
  4658. name = safeDecodeURIComponent(cookie.substring(0, index));
  4659. // the first value that is seen for a cookie is the most
  4660. // specific one. values for the same cookie name that
  4661. // follow are for less specific paths.
  4662. if (lastCookies[name] === undefined) {
  4663. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4664. }
  4665. }
  4666. }
  4667. }
  4668. return lastCookies;
  4669. }
  4670. };
  4671. /**
  4672. * @name $browser#defer
  4673. * @param {function()} fn A function, who's execution should be deferred.
  4674. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4675. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4676. *
  4677. * @description
  4678. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4679. *
  4680. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4681. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4682. * via `$browser.defer.flush()`.
  4683. *
  4684. */
  4685. self.defer = function(fn, delay) {
  4686. var timeoutId;
  4687. outstandingRequestCount++;
  4688. timeoutId = setTimeout(function() {
  4689. delete pendingDeferIds[timeoutId];
  4690. completeOutstandingRequest(fn);
  4691. }, delay || 0);
  4692. pendingDeferIds[timeoutId] = true;
  4693. return timeoutId;
  4694. };
  4695. /**
  4696. * @name $browser#defer.cancel
  4697. *
  4698. * @description
  4699. * Cancels a deferred task identified with `deferId`.
  4700. *
  4701. * @param {*} deferId Token returned by the `$browser.defer` function.
  4702. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4703. * canceled.
  4704. */
  4705. self.defer.cancel = function(deferId) {
  4706. if (pendingDeferIds[deferId]) {
  4707. delete pendingDeferIds[deferId];
  4708. clearTimeout(deferId);
  4709. completeOutstandingRequest(noop);
  4710. return true;
  4711. }
  4712. return false;
  4713. };
  4714. }
  4715. function $BrowserProvider() {
  4716. this.$get = ['$window', '$log', '$sniffer', '$document',
  4717. function($window, $log, $sniffer, $document) {
  4718. return new Browser($window, $document, $log, $sniffer);
  4719. }];
  4720. }
  4721. /**
  4722. * @ngdoc service
  4723. * @name $cacheFactory
  4724. *
  4725. * @description
  4726. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4727. * them.
  4728. *
  4729. * ```js
  4730. *
  4731. * var cache = $cacheFactory('cacheId');
  4732. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4733. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4734. *
  4735. * cache.put("key", "value");
  4736. * cache.put("another key", "another value");
  4737. *
  4738. * // We've specified no options on creation
  4739. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4740. *
  4741. * ```
  4742. *
  4743. *
  4744. * @param {string} cacheId Name or id of the newly created cache.
  4745. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4746. *
  4747. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4748. *
  4749. * @returns {object} Newly created cache object with the following set of methods:
  4750. *
  4751. * - `{object}` `info()` — Returns id, size, and options of cache.
  4752. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4753. * it.
  4754. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4755. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4756. * - `{void}` `removeAll()` — Removes all cached values.
  4757. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4758. *
  4759. * @example
  4760. <example module="cacheExampleApp">
  4761. <file name="index.html">
  4762. <div ng-controller="CacheController">
  4763. <input ng-model="newCacheKey" placeholder="Key">
  4764. <input ng-model="newCacheValue" placeholder="Value">
  4765. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4766. <p ng-if="keys.length">Cached Values</p>
  4767. <div ng-repeat="key in keys">
  4768. <span ng-bind="key"></span>
  4769. <span>: </span>
  4770. <b ng-bind="cache.get(key)"></b>
  4771. </div>
  4772. <p>Cache Info</p>
  4773. <div ng-repeat="(key, value) in cache.info()">
  4774. <span ng-bind="key"></span>
  4775. <span>: </span>
  4776. <b ng-bind="value"></b>
  4777. </div>
  4778. </div>
  4779. </file>
  4780. <file name="script.js">
  4781. angular.module('cacheExampleApp', []).
  4782. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4783. $scope.keys = [];
  4784. $scope.cache = $cacheFactory('cacheId');
  4785. $scope.put = function(key, value) {
  4786. if ($scope.cache.get(key) === undefined) {
  4787. $scope.keys.push(key);
  4788. }
  4789. $scope.cache.put(key, value === undefined ? null : value);
  4790. };
  4791. }]);
  4792. </file>
  4793. <file name="style.css">
  4794. p {
  4795. margin: 10px 0 3px;
  4796. }
  4797. </file>
  4798. </example>
  4799. */
  4800. function $CacheFactoryProvider() {
  4801. this.$get = function() {
  4802. var caches = {};
  4803. function cacheFactory(cacheId, options) {
  4804. if (cacheId in caches) {
  4805. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4806. }
  4807. var size = 0,
  4808. stats = extend({}, options, {id: cacheId}),
  4809. data = {},
  4810. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4811. lruHash = {},
  4812. freshEnd = null,
  4813. staleEnd = null;
  4814. /**
  4815. * @ngdoc type
  4816. * @name $cacheFactory.Cache
  4817. *
  4818. * @description
  4819. * A cache object used to store and retrieve data, primarily used by
  4820. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4821. * templates and other data.
  4822. *
  4823. * ```js
  4824. * angular.module('superCache')
  4825. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4826. * return $cacheFactory('super-cache');
  4827. * }]);
  4828. * ```
  4829. *
  4830. * Example test:
  4831. *
  4832. * ```js
  4833. * it('should behave like a cache', inject(function(superCache) {
  4834. * superCache.put('key', 'value');
  4835. * superCache.put('another key', 'another value');
  4836. *
  4837. * expect(superCache.info()).toEqual({
  4838. * id: 'super-cache',
  4839. * size: 2
  4840. * });
  4841. *
  4842. * superCache.remove('another key');
  4843. * expect(superCache.get('another key')).toBeUndefined();
  4844. *
  4845. * superCache.removeAll();
  4846. * expect(superCache.info()).toEqual({
  4847. * id: 'super-cache',
  4848. * size: 0
  4849. * });
  4850. * }));
  4851. * ```
  4852. */
  4853. return caches[cacheId] = {
  4854. /**
  4855. * @ngdoc method
  4856. * @name $cacheFactory.Cache#put
  4857. * @kind function
  4858. *
  4859. * @description
  4860. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4861. * retrieved later, and incrementing the size of the cache if the key was not already
  4862. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4863. * entries from the set.
  4864. *
  4865. * It will not insert undefined values into the cache.
  4866. *
  4867. * @param {string} key the key under which the cached data is stored.
  4868. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4869. * will not be stored.
  4870. * @returns {*} the value stored.
  4871. */
  4872. put: function(key, value) {
  4873. if (capacity < Number.MAX_VALUE) {
  4874. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4875. refresh(lruEntry);
  4876. }
  4877. if (isUndefined(value)) return;
  4878. if (!(key in data)) size++;
  4879. data[key] = value;
  4880. if (size > capacity) {
  4881. this.remove(staleEnd.key);
  4882. }
  4883. return value;
  4884. },
  4885. /**
  4886. * @ngdoc method
  4887. * @name $cacheFactory.Cache#get
  4888. * @kind function
  4889. *
  4890. * @description
  4891. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4892. *
  4893. * @param {string} key the key of the data to be retrieved
  4894. * @returns {*} the value stored.
  4895. */
  4896. get: function(key) {
  4897. if (capacity < Number.MAX_VALUE) {
  4898. var lruEntry = lruHash[key];
  4899. if (!lruEntry) return;
  4900. refresh(lruEntry);
  4901. }
  4902. return data[key];
  4903. },
  4904. /**
  4905. * @ngdoc method
  4906. * @name $cacheFactory.Cache#remove
  4907. * @kind function
  4908. *
  4909. * @description
  4910. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4911. *
  4912. * @param {string} key the key of the entry to be removed
  4913. */
  4914. remove: function(key) {
  4915. if (capacity < Number.MAX_VALUE) {
  4916. var lruEntry = lruHash[key];
  4917. if (!lruEntry) return;
  4918. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4919. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4920. link(lruEntry.n,lruEntry.p);
  4921. delete lruHash[key];
  4922. }
  4923. delete data[key];
  4924. size--;
  4925. },
  4926. /**
  4927. * @ngdoc method
  4928. * @name $cacheFactory.Cache#removeAll
  4929. * @kind function
  4930. *
  4931. * @description
  4932. * Clears the cache object of any entries.
  4933. */
  4934. removeAll: function() {
  4935. data = {};
  4936. size = 0;
  4937. lruHash = {};
  4938. freshEnd = staleEnd = null;
  4939. },
  4940. /**
  4941. * @ngdoc method
  4942. * @name $cacheFactory.Cache#destroy
  4943. * @kind function
  4944. *
  4945. * @description
  4946. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4947. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4948. */
  4949. destroy: function() {
  4950. data = null;
  4951. stats = null;
  4952. lruHash = null;
  4953. delete caches[cacheId];
  4954. },
  4955. /**
  4956. * @ngdoc method
  4957. * @name $cacheFactory.Cache#info
  4958. * @kind function
  4959. *
  4960. * @description
  4961. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4962. *
  4963. * @returns {object} an object with the following properties:
  4964. * <ul>
  4965. * <li>**id**: the id of the cache instance</li>
  4966. * <li>**size**: the number of entries kept in the cache instance</li>
  4967. * <li>**...**: any additional properties from the options object when creating the
  4968. * cache.</li>
  4969. * </ul>
  4970. */
  4971. info: function() {
  4972. return extend({}, stats, {size: size});
  4973. }
  4974. };
  4975. /**
  4976. * makes the `entry` the freshEnd of the LRU linked list
  4977. */
  4978. function refresh(entry) {
  4979. if (entry != freshEnd) {
  4980. if (!staleEnd) {
  4981. staleEnd = entry;
  4982. } else if (staleEnd == entry) {
  4983. staleEnd = entry.n;
  4984. }
  4985. link(entry.n, entry.p);
  4986. link(entry, freshEnd);
  4987. freshEnd = entry;
  4988. freshEnd.n = null;
  4989. }
  4990. }
  4991. /**
  4992. * bidirectionally links two entries of the LRU linked list
  4993. */
  4994. function link(nextEntry, prevEntry) {
  4995. if (nextEntry != prevEntry) {
  4996. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4997. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4998. }
  4999. }
  5000. }
  5001. /**
  5002. * @ngdoc method
  5003. * @name $cacheFactory#info
  5004. *
  5005. * @description
  5006. * Get information about all the caches that have been created
  5007. *
  5008. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5009. */
  5010. cacheFactory.info = function() {
  5011. var info = {};
  5012. forEach(caches, function(cache, cacheId) {
  5013. info[cacheId] = cache.info();
  5014. });
  5015. return info;
  5016. };
  5017. /**
  5018. * @ngdoc method
  5019. * @name $cacheFactory#get
  5020. *
  5021. * @description
  5022. * Get access to a cache object by the `cacheId` used when it was created.
  5023. *
  5024. * @param {string} cacheId Name or id of a cache to access.
  5025. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5026. */
  5027. cacheFactory.get = function(cacheId) {
  5028. return caches[cacheId];
  5029. };
  5030. return cacheFactory;
  5031. };
  5032. }
  5033. /**
  5034. * @ngdoc service
  5035. * @name $templateCache
  5036. *
  5037. * @description
  5038. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5039. * can load templates directly into the cache in a `script` tag, or by consuming the
  5040. * `$templateCache` service directly.
  5041. *
  5042. * Adding via the `script` tag:
  5043. *
  5044. * ```html
  5045. * <script type="text/ng-template" id="templateId.html">
  5046. * <p>This is the content of the template</p>
  5047. * </script>
  5048. * ```
  5049. *
  5050. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5051. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5052. * element with ng-app attribute), otherwise the template will be ignored.
  5053. *
  5054. * Adding via the $templateCache service:
  5055. *
  5056. * ```js
  5057. * var myApp = angular.module('myApp', []);
  5058. * myApp.run(function($templateCache) {
  5059. * $templateCache.put('templateId.html', 'This is the content of the template');
  5060. * });
  5061. * ```
  5062. *
  5063. * To retrieve the template later, simply use it in your HTML:
  5064. * ```html
  5065. * <div ng-include=" 'templateId.html' "></div>
  5066. * ```
  5067. *
  5068. * or get it via Javascript:
  5069. * ```js
  5070. * $templateCache.get('templateId.html')
  5071. * ```
  5072. *
  5073. * See {@link ng.$cacheFactory $cacheFactory}.
  5074. *
  5075. */
  5076. function $TemplateCacheProvider() {
  5077. this.$get = ['$cacheFactory', function($cacheFactory) {
  5078. return $cacheFactory('templates');
  5079. }];
  5080. }
  5081. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5082. *
  5083. * DOM-related variables:
  5084. *
  5085. * - "node" - DOM Node
  5086. * - "element" - DOM Element or Node
  5087. * - "$node" or "$element" - jqLite-wrapped node or element
  5088. *
  5089. *
  5090. * Compiler related stuff:
  5091. *
  5092. * - "linkFn" - linking fn of a single directive
  5093. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5094. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5095. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5096. */
  5097. /**
  5098. * @ngdoc service
  5099. * @name $compile
  5100. * @kind function
  5101. *
  5102. * @description
  5103. * Compiles an HTML string or DOM into a template and produces a template function, which
  5104. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5105. *
  5106. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5107. * {@link ng.$compileProvider#directive directives}.
  5108. *
  5109. * <div class="alert alert-warning">
  5110. * **Note:** This document is an in-depth reference of all directive options.
  5111. * For a gentle introduction to directives with examples of common use cases,
  5112. * see the {@link guide/directive directive guide}.
  5113. * </div>
  5114. *
  5115. * ## Comprehensive Directive API
  5116. *
  5117. * There are many different options for a directive.
  5118. *
  5119. * The difference resides in the return value of the factory function.
  5120. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5121. * or just the `postLink` function (all other properties will have the default values).
  5122. *
  5123. * <div class="alert alert-success">
  5124. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5125. * </div>
  5126. *
  5127. * Here's an example directive declared with a Directive Definition Object:
  5128. *
  5129. * ```js
  5130. * var myModule = angular.module(...);
  5131. *
  5132. * myModule.directive('directiveName', function factory(injectables) {
  5133. * var directiveDefinitionObject = {
  5134. * priority: 0,
  5135. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5136. * // or
  5137. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5138. * transclude: false,
  5139. * restrict: 'A',
  5140. * templateNamespace: 'html',
  5141. * scope: false,
  5142. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5143. * controllerAs: 'stringAlias',
  5144. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5145. * compile: function compile(tElement, tAttrs, transclude) {
  5146. * return {
  5147. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5148. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5149. * }
  5150. * // or
  5151. * // return function postLink( ... ) { ... }
  5152. * },
  5153. * // or
  5154. * // link: {
  5155. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5156. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5157. * // }
  5158. * // or
  5159. * // link: function postLink( ... ) { ... }
  5160. * };
  5161. * return directiveDefinitionObject;
  5162. * });
  5163. * ```
  5164. *
  5165. * <div class="alert alert-warning">
  5166. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5167. * </div>
  5168. *
  5169. * Therefore the above can be simplified as:
  5170. *
  5171. * ```js
  5172. * var myModule = angular.module(...);
  5173. *
  5174. * myModule.directive('directiveName', function factory(injectables) {
  5175. * var directiveDefinitionObject = {
  5176. * link: function postLink(scope, iElement, iAttrs) { ... }
  5177. * };
  5178. * return directiveDefinitionObject;
  5179. * // or
  5180. * // return function postLink(scope, iElement, iAttrs) { ... }
  5181. * });
  5182. * ```
  5183. *
  5184. *
  5185. *
  5186. * ### Directive Definition Object
  5187. *
  5188. * The directive definition object provides instructions to the {@link ng.$compile
  5189. * compiler}. The attributes are:
  5190. *
  5191. * #### `multiElement`
  5192. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5193. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5194. * together as the directive elements. It is recomended that this feature be used on directives
  5195. * which are not strictly behavioural (such as {@link ngClick}), and which
  5196. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5197. *
  5198. * #### `priority`
  5199. * When there are multiple directives defined on a single DOM element, sometimes it
  5200. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5201. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5202. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5203. * are also run in priority order, but post-link functions are run in reverse order. The order
  5204. * of directives with the same priority is undefined. The default priority is `0`.
  5205. *
  5206. * #### `terminal`
  5207. * If set to true then the current `priority` will be the last set of directives
  5208. * which will execute (any directives at the current priority will still execute
  5209. * as the order of execution on same `priority` is undefined). Note that expressions
  5210. * and other directives used in the directive's template will also be excluded from execution.
  5211. *
  5212. * #### `scope`
  5213. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5214. * same element request a new scope, only one new scope is created. The new scope rule does not
  5215. * apply for the root of the template since the root of the template always gets a new scope.
  5216. *
  5217. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5218. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5219. * when creating reusable components, which should not accidentally read or modify data in the
  5220. * parent scope.
  5221. *
  5222. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5223. * derived from the parent scope. These local properties are useful for aliasing values for
  5224. * templates. Locals definition is a hash of local scope property to its source:
  5225. *
  5226. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5227. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5228. * attribute name is assumed to be the same as the local name.
  5229. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5230. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5231. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5232. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5233. * component scope).
  5234. *
  5235. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5236. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5237. * name is specified then the attribute name is assumed to be the same as the local name.
  5238. * Given `<widget my-attr="parentModel">` and widget definition of
  5239. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5240. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5241. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5242. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5243. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5244. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5245. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5246. *
  5247. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5248. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5249. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5250. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5251. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5252. * pass data from the isolated scope via an expression to the parent scope, this can be
  5253. * done by passing a map of local variable names and values into the expression wrapper fn.
  5254. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5255. * by calling the `localFn` as `localFn({amount: 22})`.
  5256. *
  5257. *
  5258. * #### `bindToController`
  5259. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5260. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5261. * is instantiated, the initial values of the isolate scope bindings are already available.
  5262. *
  5263. * #### `controller`
  5264. * Controller constructor function. The controller is instantiated before the
  5265. * pre-linking phase and it is shared with other directives (see
  5266. * `require` attribute). This allows the directives to communicate with each other and augment
  5267. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5268. *
  5269. * * `$scope` - Current scope associated with the element
  5270. * * `$element` - Current element
  5271. * * `$attrs` - Current attributes object for the element
  5272. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5273. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5274. * * `scope`: optional argument to override the scope.
  5275. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5276. * * `futureParentElement`:
  5277. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5278. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5279. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5280. * and when the `cloneLinkinFn` is passed,
  5281. * as those elements need to created and cloned in a special way when they are defined outside their
  5282. * usual containers (e.g. like `<svg>`).
  5283. * * See also the `directive.templateNamespace` property.
  5284. *
  5285. *
  5286. * #### `require`
  5287. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5288. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5289. * injected argument will be an array in corresponding order. If no such directive can be
  5290. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  5291. *
  5292. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5293. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5294. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5295. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5296. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5297. * `null` to the `link` fn if not found.
  5298. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5299. * `null` to the `link` fn if not found.
  5300. *
  5301. *
  5302. * #### `controllerAs`
  5303. * Controller alias at the directive scope. An alias for the controller so it
  5304. * can be referenced at the directive template. The directive needs to define a scope for this
  5305. * configuration to be used. Useful in the case when directive is used as component.
  5306. *
  5307. *
  5308. * #### `restrict`
  5309. * String of subset of `EACM` which restricts the directive to a specific directive
  5310. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5311. *
  5312. * * `E` - Element name (default): `<my-directive></my-directive>`
  5313. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5314. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5315. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5316. *
  5317. *
  5318. * #### `templateNamespace`
  5319. * String representing the document type used by the markup in the template.
  5320. * AngularJS needs this information as those elements need to be created and cloned
  5321. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5322. *
  5323. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5324. * top-level elements such as `<svg>` or `<math>`.
  5325. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5326. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5327. *
  5328. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5329. *
  5330. * #### `template`
  5331. * HTML markup that may:
  5332. * * Replace the contents of the directive's element (default).
  5333. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5334. * * Wrap the contents of the directive's element (if `transclude` is true).
  5335. *
  5336. * Value may be:
  5337. *
  5338. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5339. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5340. * function api below) and returns a string value.
  5341. *
  5342. *
  5343. * #### `templateUrl`
  5344. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5345. *
  5346. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5347. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5348. * sibling and parent elements as though this element had not contained any directives.
  5349. *
  5350. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5351. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5352. * case when only one deeply nested directive has `templateUrl`.
  5353. *
  5354. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5355. *
  5356. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5357. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5358. * a string value representing the url. In either case, the template URL is passed through {@link
  5359. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5360. *
  5361. *
  5362. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5363. * specify what the template should replace. Defaults to `false`.
  5364. *
  5365. * * `true` - the template will replace the directive's element.
  5366. * * `false` - the template will replace the contents of the directive's element.
  5367. *
  5368. * The replacement process migrates all of the attributes / classes from the old element to the new
  5369. * one. See the {@link guide/directive#template-expanding-directive
  5370. * Directives Guide} for an example.
  5371. *
  5372. * There are very few scenarios where element replacement is required for the application function,
  5373. * the main one being reusable custom components that are used within SVG contexts
  5374. * (because SVG doesn't work with custom elements in the DOM tree).
  5375. *
  5376. * #### `transclude`
  5377. * Extract the contents of the element where the directive appears and make it available to the directive.
  5378. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5379. * {@link $compile#transclusion Transclusion} section below.
  5380. *
  5381. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5382. * directive's element or the entire element:
  5383. *
  5384. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5385. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5386. * element that defined at a lower priority than this directive. When used, the `template`
  5387. * property is ignored.
  5388. *
  5389. *
  5390. * #### `compile`
  5391. *
  5392. * ```js
  5393. * function compile(tElement, tAttrs, transclude) { ... }
  5394. * ```
  5395. *
  5396. * The compile function deals with transforming the template DOM. Since most directives do not do
  5397. * template transformation, it is not used often. The compile function takes the following arguments:
  5398. *
  5399. * * `tElement` - template element - The element where the directive has been declared. It is
  5400. * safe to do template transformation on the element and child elements only.
  5401. *
  5402. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5403. * between all directive compile functions.
  5404. *
  5405. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5406. *
  5407. * <div class="alert alert-warning">
  5408. * **Note:** The template instance and the link instance may be different objects if the template has
  5409. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5410. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5411. * should be done in a linking function rather than in a compile function.
  5412. * </div>
  5413. * <div class="alert alert-warning">
  5414. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5415. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5416. * stack overflow errors.
  5417. *
  5418. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5419. * a directive's template instead of relying on automatic template compilation via `template` or
  5420. * `templateUrl` declaration or manual compilation inside the compile function.
  5421. * </div>
  5422. *
  5423. * <div class="alert alert-error">
  5424. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5425. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5426. * to the link function instead.
  5427. * </div>
  5428. * A compile function can have a return value which can be either a function or an object.
  5429. *
  5430. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5431. * `link` property of the config object when the compile function is empty.
  5432. *
  5433. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5434. * control when a linking function should be called during the linking phase. See info about
  5435. * pre-linking and post-linking functions below.
  5436. *
  5437. *
  5438. * #### `link`
  5439. * This property is used only if the `compile` property is not defined.
  5440. *
  5441. * ```js
  5442. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5443. * ```
  5444. *
  5445. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5446. * executed after the template has been cloned. This is where most of the directive logic will be
  5447. * put.
  5448. *
  5449. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5450. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5451. *
  5452. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5453. * manipulate the children of the element only in `postLink` function since the children have
  5454. * already been linked.
  5455. *
  5456. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5457. * between all directive linking functions.
  5458. *
  5459. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5460. * element defines a controller. The controller is shared among all the directives, which allows
  5461. * the directives to use the controllers as a communication channel.
  5462. *
  5463. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5464. * This is the same as the `$transclude`
  5465. * parameter of directive controllers, see there for details.
  5466. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5467. *
  5468. * #### Pre-linking function
  5469. *
  5470. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5471. * compiler linking function will fail to locate the correct elements for linking.
  5472. *
  5473. * #### Post-linking function
  5474. *
  5475. * Executed after the child elements are linked.
  5476. *
  5477. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5478. * and linked since they are waiting for their template to load asynchronously and their own
  5479. * compilation and linking has been suspended until that occurs.
  5480. *
  5481. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5482. * for their async templates to be resolved.
  5483. *
  5484. *
  5485. * ### Transclusion
  5486. *
  5487. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5488. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5489. * scope from where they were taken.
  5490. *
  5491. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5492. * original contents of a directive's element into a specified place in the template of the directive.
  5493. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5494. * content has access to the properties on the scope from which it was taken, even if the directive
  5495. * has isolated scope.
  5496. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5497. *
  5498. * This makes it possible for the widget to have private state for its template, while the transcluded
  5499. * content has access to its originating scope.
  5500. *
  5501. * <div class="alert alert-warning">
  5502. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5503. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5504. * Testing Transclusion Directives}.
  5505. * </div>
  5506. *
  5507. * #### Transclusion Functions
  5508. *
  5509. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5510. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5511. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5512. *
  5513. * <div class="alert alert-info">
  5514. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5515. * ngTransclude will deal with it for us.
  5516. * </div>
  5517. *
  5518. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5519. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5520. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5521. *
  5522. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5523. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5524. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5525. *
  5526. * <div class="alert alert-info">
  5527. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5528. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5529. * </div>
  5530. *
  5531. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5532. * attach function**:
  5533. *
  5534. * ```js
  5535. * var transcludedContent, transclusionScope;
  5536. *
  5537. * $transclude(function(clone, scope) {
  5538. * element.append(clone);
  5539. * transcludedContent = clone;
  5540. * transclusionScope = scope;
  5541. * });
  5542. * ```
  5543. *
  5544. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5545. * associated transclusion scope:
  5546. *
  5547. * ```js
  5548. * transcludedContent.remove();
  5549. * transclusionScope.$destroy();
  5550. * ```
  5551. *
  5552. * <div class="alert alert-info">
  5553. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5554. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5555. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5556. * </div>
  5557. *
  5558. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5559. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5560. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5561. *
  5562. *
  5563. * #### Transclusion Scopes
  5564. *
  5565. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5566. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5567. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5568. * was taken.
  5569. *
  5570. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5571. * like this:
  5572. *
  5573. * ```html
  5574. * <div ng-app>
  5575. * <div isolate>
  5576. * <div transclusion>
  5577. * </div>
  5578. * </div>
  5579. * </div>
  5580. * ```
  5581. *
  5582. * The `$parent` scope hierarchy will look like this:
  5583. *
  5584. * ```
  5585. * - $rootScope
  5586. * - isolate
  5587. * - transclusion
  5588. * ```
  5589. *
  5590. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5591. *
  5592. * ```
  5593. * - $rootScope
  5594. * - transclusion
  5595. * - isolate
  5596. * ```
  5597. *
  5598. *
  5599. * ### Attributes
  5600. *
  5601. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5602. * `link()` or `compile()` functions. It has a variety of uses.
  5603. *
  5604. * accessing *Normalized attribute names:*
  5605. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5606. * the attributes object allows for normalized access to
  5607. * the attributes.
  5608. *
  5609. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5610. * object which allows the directives to use the attributes object as inter directive
  5611. * communication.
  5612. *
  5613. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5614. * allowing other directives to read the interpolated value.
  5615. *
  5616. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5617. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5618. * the only way to easily get the actual value because during the linking phase the interpolation
  5619. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5620. *
  5621. * ```js
  5622. * function linkingFn(scope, elm, attrs, ctrl) {
  5623. * // get the attribute value
  5624. * console.log(attrs.ngModel);
  5625. *
  5626. * // change the attribute
  5627. * attrs.$set('ngModel', 'new value');
  5628. *
  5629. * // observe changes to interpolated attribute
  5630. * attrs.$observe('ngModel', function(value) {
  5631. * console.log('ngModel has changed value to ' + value);
  5632. * });
  5633. * }
  5634. * ```
  5635. *
  5636. * ## Example
  5637. *
  5638. * <div class="alert alert-warning">
  5639. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5640. * to illustrate how `$compile` works.
  5641. * </div>
  5642. *
  5643. <example module="compileExample">
  5644. <file name="index.html">
  5645. <script>
  5646. angular.module('compileExample', [], function($compileProvider) {
  5647. // configure new 'compile' directive by passing a directive
  5648. // factory function. The factory function injects the '$compile'
  5649. $compileProvider.directive('compile', function($compile) {
  5650. // directive factory creates a link function
  5651. return function(scope, element, attrs) {
  5652. scope.$watch(
  5653. function(scope) {
  5654. // watch the 'compile' expression for changes
  5655. return scope.$eval(attrs.compile);
  5656. },
  5657. function(value) {
  5658. // when the 'compile' expression changes
  5659. // assign it into the current DOM
  5660. element.html(value);
  5661. // compile the new DOM and link it to the current
  5662. // scope.
  5663. // NOTE: we only compile .childNodes so that
  5664. // we don't get into infinite loop compiling ourselves
  5665. $compile(element.contents())(scope);
  5666. }
  5667. );
  5668. };
  5669. });
  5670. })
  5671. .controller('GreeterController', ['$scope', function($scope) {
  5672. $scope.name = 'Angular';
  5673. $scope.html = 'Hello {{name}}';
  5674. }]);
  5675. </script>
  5676. <div ng-controller="GreeterController">
  5677. <input ng-model="name"> <br>
  5678. <textarea ng-model="html"></textarea> <br>
  5679. <div compile="html"></div>
  5680. </div>
  5681. </file>
  5682. <file name="protractor.js" type="protractor">
  5683. it('should auto compile', function() {
  5684. var textarea = $('textarea');
  5685. var output = $('div[compile]');
  5686. // The initial state reads 'Hello Angular'.
  5687. expect(output.getText()).toBe('Hello Angular');
  5688. textarea.clear();
  5689. textarea.sendKeys('{{name}}!');
  5690. expect(output.getText()).toBe('Angular!');
  5691. });
  5692. </file>
  5693. </example>
  5694. *
  5695. *
  5696. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5697. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5698. *
  5699. * <div class="alert alert-error">
  5700. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5701. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5702. * `parentBoundTranscludeFn` to the link function instead.
  5703. * </div>
  5704. *
  5705. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5706. * root element(s), not their children)
  5707. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5708. * (a DOM element/tree) to a scope. Where:
  5709. *
  5710. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5711. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5712. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5713. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5714. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5715. *
  5716. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5717. * * `scope` - is the current scope with which the linking function is working with.
  5718. *
  5719. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5720. * keys may be used to control linking behavior:
  5721. *
  5722. * * `parentBoundTranscludeFn` - the transclude function made available to
  5723. * directives; if given, it will be passed through to the link functions of
  5724. * directives found in `element` during compilation.
  5725. * * `transcludeControllers` - an object hash with keys that map controller names
  5726. * to controller instances; if given, it will make the controllers
  5727. * available to directives.
  5728. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5729. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5730. * elements (e.g. SVG elements). See also the directive.controller property.
  5731. *
  5732. * Calling the linking function returns the element of the template. It is either the original
  5733. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5734. *
  5735. * After linking the view is not updated until after a call to $digest which typically is done by
  5736. * Angular automatically.
  5737. *
  5738. * If you need access to the bound view, there are two ways to do it:
  5739. *
  5740. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5741. * before you send them to the compiler and keep this reference around.
  5742. * ```js
  5743. * var element = $compile('<p>{{total}}</p>')(scope);
  5744. * ```
  5745. *
  5746. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5747. * example would not point to the clone, but rather to the original template that was cloned. In
  5748. * this case, you can access the clone via the cloneAttachFn:
  5749. * ```js
  5750. * var templateElement = angular.element('<p>{{total}}</p>'),
  5751. * scope = ....;
  5752. *
  5753. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5754. * //attach the clone to DOM document at the right place
  5755. * });
  5756. *
  5757. * //now we have reference to the cloned DOM via `clonedElement`
  5758. * ```
  5759. *
  5760. *
  5761. * For information on how the compiler works, see the
  5762. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5763. */
  5764. var $compileMinErr = minErr('$compile');
  5765. /**
  5766. * @ngdoc provider
  5767. * @name $compileProvider
  5768. *
  5769. * @description
  5770. */
  5771. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5772. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5773. var hasDirectives = {},
  5774. Suffix = 'Directive',
  5775. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5776. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5777. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5778. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5779. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5780. // The assumption is that future DOM event attribute names will begin with
  5781. // 'on' and be composed of only English letters.
  5782. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5783. function parseIsolateBindings(scope, directiveName) {
  5784. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5785. var bindings = {};
  5786. forEach(scope, function(definition, scopeName) {
  5787. var match = definition.match(LOCAL_REGEXP);
  5788. if (!match) {
  5789. throw $compileMinErr('iscp',
  5790. "Invalid isolate scope definition for directive '{0}'." +
  5791. " Definition: {... {1}: '{2}' ...}",
  5792. directiveName, scopeName, definition);
  5793. }
  5794. bindings[scopeName] = {
  5795. mode: match[1][0],
  5796. collection: match[2] === '*',
  5797. optional: match[3] === '?',
  5798. attrName: match[4] || scopeName
  5799. };
  5800. });
  5801. return bindings;
  5802. }
  5803. /**
  5804. * @ngdoc method
  5805. * @name $compileProvider#directive
  5806. * @kind function
  5807. *
  5808. * @description
  5809. * Register a new directive with the compiler.
  5810. *
  5811. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5812. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5813. * names and the values are the factories.
  5814. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5815. * {@link guide/directive} for more info.
  5816. * @returns {ng.$compileProvider} Self for chaining.
  5817. */
  5818. this.directive = function registerDirective(name, directiveFactory) {
  5819. assertNotHasOwnProperty(name, 'directive');
  5820. if (isString(name)) {
  5821. assertArg(directiveFactory, 'directiveFactory');
  5822. if (!hasDirectives.hasOwnProperty(name)) {
  5823. hasDirectives[name] = [];
  5824. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5825. function($injector, $exceptionHandler) {
  5826. var directives = [];
  5827. forEach(hasDirectives[name], function(directiveFactory, index) {
  5828. try {
  5829. var directive = $injector.invoke(directiveFactory);
  5830. if (isFunction(directive)) {
  5831. directive = { compile: valueFn(directive) };
  5832. } else if (!directive.compile && directive.link) {
  5833. directive.compile = valueFn(directive.link);
  5834. }
  5835. directive.priority = directive.priority || 0;
  5836. directive.index = index;
  5837. directive.name = directive.name || name;
  5838. directive.require = directive.require || (directive.controller && directive.name);
  5839. directive.restrict = directive.restrict || 'EA';
  5840. if (isObject(directive.scope)) {
  5841. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5842. }
  5843. directives.push(directive);
  5844. } catch (e) {
  5845. $exceptionHandler(e);
  5846. }
  5847. });
  5848. return directives;
  5849. }]);
  5850. }
  5851. hasDirectives[name].push(directiveFactory);
  5852. } else {
  5853. forEach(name, reverseParams(registerDirective));
  5854. }
  5855. return this;
  5856. };
  5857. /**
  5858. * @ngdoc method
  5859. * @name $compileProvider#aHrefSanitizationWhitelist
  5860. * @kind function
  5861. *
  5862. * @description
  5863. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5864. * urls during a[href] sanitization.
  5865. *
  5866. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5867. *
  5868. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5869. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5870. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5871. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5872. *
  5873. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5874. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5875. * chaining otherwise.
  5876. */
  5877. this.aHrefSanitizationWhitelist = function(regexp) {
  5878. if (isDefined(regexp)) {
  5879. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5880. return this;
  5881. } else {
  5882. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5883. }
  5884. };
  5885. /**
  5886. * @ngdoc method
  5887. * @name $compileProvider#imgSrcSanitizationWhitelist
  5888. * @kind function
  5889. *
  5890. * @description
  5891. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5892. * urls during img[src] sanitization.
  5893. *
  5894. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5895. *
  5896. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5897. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5898. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5899. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5900. *
  5901. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5902. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5903. * chaining otherwise.
  5904. */
  5905. this.imgSrcSanitizationWhitelist = function(regexp) {
  5906. if (isDefined(regexp)) {
  5907. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5908. return this;
  5909. } else {
  5910. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5911. }
  5912. };
  5913. /**
  5914. * @ngdoc method
  5915. * @name $compileProvider#debugInfoEnabled
  5916. *
  5917. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  5918. * current debugInfoEnabled state
  5919. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  5920. *
  5921. * @kind function
  5922. *
  5923. * @description
  5924. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  5925. * binding information and a reference to the current scope on to DOM elements.
  5926. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  5927. * * `ng-binding` CSS class
  5928. * * `$binding` data property containing an array of the binding expressions
  5929. *
  5930. * You may want to use this in production for a significant performance boost. See
  5931. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  5932. *
  5933. * The default value is true.
  5934. */
  5935. var debugInfoEnabled = true;
  5936. this.debugInfoEnabled = function(enabled) {
  5937. if (isDefined(enabled)) {
  5938. debugInfoEnabled = enabled;
  5939. return this;
  5940. }
  5941. return debugInfoEnabled;
  5942. };
  5943. this.$get = [
  5944. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  5945. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5946. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  5947. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5948. var Attributes = function(element, attributesToCopy) {
  5949. if (attributesToCopy) {
  5950. var keys = Object.keys(attributesToCopy);
  5951. var i, l, key;
  5952. for (i = 0, l = keys.length; i < l; i++) {
  5953. key = keys[i];
  5954. this[key] = attributesToCopy[key];
  5955. }
  5956. } else {
  5957. this.$attr = {};
  5958. }
  5959. this.$$element = element;
  5960. };
  5961. Attributes.prototype = {
  5962. $normalize: directiveNormalize,
  5963. /**
  5964. * @ngdoc method
  5965. * @name $compile.directive.Attributes#$addClass
  5966. * @kind function
  5967. *
  5968. * @description
  5969. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5970. * are enabled then an animation will be triggered for the class addition.
  5971. *
  5972. * @param {string} classVal The className value that will be added to the element
  5973. */
  5974. $addClass: function(classVal) {
  5975. if (classVal && classVal.length > 0) {
  5976. $animate.addClass(this.$$element, classVal);
  5977. }
  5978. },
  5979. /**
  5980. * @ngdoc method
  5981. * @name $compile.directive.Attributes#$removeClass
  5982. * @kind function
  5983. *
  5984. * @description
  5985. * Removes the CSS class value specified by the classVal parameter from the element. If
  5986. * animations are enabled then an animation will be triggered for the class removal.
  5987. *
  5988. * @param {string} classVal The className value that will be removed from the element
  5989. */
  5990. $removeClass: function(classVal) {
  5991. if (classVal && classVal.length > 0) {
  5992. $animate.removeClass(this.$$element, classVal);
  5993. }
  5994. },
  5995. /**
  5996. * @ngdoc method
  5997. * @name $compile.directive.Attributes#$updateClass
  5998. * @kind function
  5999. *
  6000. * @description
  6001. * Adds and removes the appropriate CSS class values to the element based on the difference
  6002. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6003. *
  6004. * @param {string} newClasses The current CSS className value
  6005. * @param {string} oldClasses The former CSS className value
  6006. */
  6007. $updateClass: function(newClasses, oldClasses) {
  6008. var toAdd = tokenDifference(newClasses, oldClasses);
  6009. if (toAdd && toAdd.length) {
  6010. $animate.addClass(this.$$element, toAdd);
  6011. }
  6012. var toRemove = tokenDifference(oldClasses, newClasses);
  6013. if (toRemove && toRemove.length) {
  6014. $animate.removeClass(this.$$element, toRemove);
  6015. }
  6016. },
  6017. /**
  6018. * Set a normalized attribute on the element in a way such that all directives
  6019. * can share the attribute. This function properly handles boolean attributes.
  6020. * @param {string} key Normalized key. (ie ngAttribute)
  6021. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6022. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6023. * Defaults to true.
  6024. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6025. */
  6026. $set: function(key, value, writeAttr, attrName) {
  6027. // TODO: decide whether or not to throw an error if "class"
  6028. //is set through this function since it may cause $updateClass to
  6029. //become unstable.
  6030. var node = this.$$element[0],
  6031. booleanKey = getBooleanAttrName(node, key),
  6032. aliasedKey = getAliasedAttrName(node, key),
  6033. observer = key,
  6034. nodeName;
  6035. if (booleanKey) {
  6036. this.$$element.prop(key, value);
  6037. attrName = booleanKey;
  6038. } else if (aliasedKey) {
  6039. this[aliasedKey] = value;
  6040. observer = aliasedKey;
  6041. }
  6042. this[key] = value;
  6043. // translate normalized key to actual key
  6044. if (attrName) {
  6045. this.$attr[key] = attrName;
  6046. } else {
  6047. attrName = this.$attr[key];
  6048. if (!attrName) {
  6049. this.$attr[key] = attrName = snake_case(key, '-');
  6050. }
  6051. }
  6052. nodeName = nodeName_(this.$$element);
  6053. if ((nodeName === 'a' && key === 'href') ||
  6054. (nodeName === 'img' && key === 'src')) {
  6055. // sanitize a[href] and img[src] values
  6056. this[key] = value = $$sanitizeUri(value, key === 'src');
  6057. } else if (nodeName === 'img' && key === 'srcset') {
  6058. // sanitize img[srcset] values
  6059. var result = "";
  6060. // first check if there are spaces because it's not the same pattern
  6061. var trimmedSrcset = trim(value);
  6062. // ( 999x ,| 999w ,| ,|, )
  6063. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6064. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6065. // split srcset into tuple of uri and descriptor except for the last item
  6066. var rawUris = trimmedSrcset.split(pattern);
  6067. // for each tuples
  6068. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6069. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6070. var innerIdx = i * 2;
  6071. // sanitize the uri
  6072. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6073. // add the descriptor
  6074. result += (" " + trim(rawUris[innerIdx + 1]));
  6075. }
  6076. // split the last item into uri and descriptor
  6077. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6078. // sanitize the last uri
  6079. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6080. // and add the last descriptor if any
  6081. if (lastTuple.length === 2) {
  6082. result += (" " + trim(lastTuple[1]));
  6083. }
  6084. this[key] = value = result;
  6085. }
  6086. if (writeAttr !== false) {
  6087. if (value === null || value === undefined) {
  6088. this.$$element.removeAttr(attrName);
  6089. } else {
  6090. this.$$element.attr(attrName, value);
  6091. }
  6092. }
  6093. // fire observers
  6094. var $$observers = this.$$observers;
  6095. $$observers && forEach($$observers[observer], function(fn) {
  6096. try {
  6097. fn(value);
  6098. } catch (e) {
  6099. $exceptionHandler(e);
  6100. }
  6101. });
  6102. },
  6103. /**
  6104. * @ngdoc method
  6105. * @name $compile.directive.Attributes#$observe
  6106. * @kind function
  6107. *
  6108. * @description
  6109. * Observes an interpolated attribute.
  6110. *
  6111. * The observer function will be invoked once during the next `$digest` following
  6112. * compilation. The observer is then invoked whenever the interpolated value
  6113. * changes.
  6114. *
  6115. * @param {string} key Normalized key. (ie ngAttribute) .
  6116. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6117. the interpolated value of the attribute changes.
  6118. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6119. * @returns {function()} Returns a deregistration function for this observer.
  6120. */
  6121. $observe: function(key, fn) {
  6122. var attrs = this,
  6123. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6124. listeners = ($$observers[key] || ($$observers[key] = []));
  6125. listeners.push(fn);
  6126. $rootScope.$evalAsync(function() {
  6127. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6128. // no one registered attribute interpolation function, so lets call it manually
  6129. fn(attrs[key]);
  6130. }
  6131. });
  6132. return function() {
  6133. arrayRemove(listeners, fn);
  6134. };
  6135. }
  6136. };
  6137. function safeAddClass($element, className) {
  6138. try {
  6139. $element.addClass(className);
  6140. } catch (e) {
  6141. // ignore, since it means that we are trying to set class on
  6142. // SVG element, where class name is read-only.
  6143. }
  6144. }
  6145. var startSymbol = $interpolate.startSymbol(),
  6146. endSymbol = $interpolate.endSymbol(),
  6147. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6148. ? identity
  6149. : function denormalizeTemplate(template) {
  6150. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6151. },
  6152. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6153. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6154. var bindings = $element.data('$binding') || [];
  6155. if (isArray(binding)) {
  6156. bindings = bindings.concat(binding);
  6157. } else {
  6158. bindings.push(binding);
  6159. }
  6160. $element.data('$binding', bindings);
  6161. } : noop;
  6162. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6163. safeAddClass($element, 'ng-binding');
  6164. } : noop;
  6165. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6166. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6167. $element.data(dataName, scope);
  6168. } : noop;
  6169. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6170. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6171. } : noop;
  6172. return compile;
  6173. //================================
  6174. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6175. previousCompileContext) {
  6176. if (!($compileNodes instanceof jqLite)) {
  6177. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6178. // modify it.
  6179. $compileNodes = jqLite($compileNodes);
  6180. }
  6181. // We can not compile top level text elements since text nodes can be merged and we will
  6182. // not be able to attach scope data to them, so we will wrap them in <span>
  6183. forEach($compileNodes, function(node, index) {
  6184. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6185. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6186. }
  6187. });
  6188. var compositeLinkFn =
  6189. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6190. maxPriority, ignoreDirective, previousCompileContext);
  6191. compile.$$addScopeClass($compileNodes);
  6192. var namespace = null;
  6193. return function publicLinkFn(scope, cloneConnectFn, options) {
  6194. assertArg(scope, 'scope');
  6195. options = options || {};
  6196. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6197. transcludeControllers = options.transcludeControllers,
  6198. futureParentElement = options.futureParentElement;
  6199. // When `parentBoundTranscludeFn` is passed, it is a
  6200. // `controllersBoundTransclude` function (it was previously passed
  6201. // as `transclude` to directive.link) so we must unwrap it to get
  6202. // its `boundTranscludeFn`
  6203. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6204. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6205. }
  6206. if (!namespace) {
  6207. namespace = detectNamespaceForChildElements(futureParentElement);
  6208. }
  6209. var $linkNode;
  6210. if (namespace !== 'html') {
  6211. // When using a directive with replace:true and templateUrl the $compileNodes
  6212. // (or a child element inside of them)
  6213. // might change, so we need to recreate the namespace adapted compileNodes
  6214. // for call to the link function.
  6215. // Note: This will already clone the nodes...
  6216. $linkNode = jqLite(
  6217. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6218. );
  6219. } else if (cloneConnectFn) {
  6220. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6221. // and sometimes changes the structure of the DOM.
  6222. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6223. } else {
  6224. $linkNode = $compileNodes;
  6225. }
  6226. if (transcludeControllers) {
  6227. for (var controllerName in transcludeControllers) {
  6228. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6229. }
  6230. }
  6231. compile.$$addScopeInfo($linkNode, scope);
  6232. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6233. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6234. return $linkNode;
  6235. };
  6236. }
  6237. function detectNamespaceForChildElements(parentElement) {
  6238. // TODO: Make this detect MathML as well...
  6239. var node = parentElement && parentElement[0];
  6240. if (!node) {
  6241. return 'html';
  6242. } else {
  6243. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6244. }
  6245. }
  6246. /**
  6247. * Compile function matches each node in nodeList against the directives. Once all directives
  6248. * for a particular node are collected their compile functions are executed. The compile
  6249. * functions return values - the linking functions - are combined into a composite linking
  6250. * function, which is the a linking function for the node.
  6251. *
  6252. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6253. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6254. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6255. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6256. * the rootElement must be set the jqLite collection of the compile root. This is
  6257. * needed so that the jqLite collection items can be replaced with widgets.
  6258. * @param {number=} maxPriority Max directive priority.
  6259. * @returns {Function} A composite linking function of all of the matched directives or null.
  6260. */
  6261. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6262. previousCompileContext) {
  6263. var linkFns = [],
  6264. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6265. for (var i = 0; i < nodeList.length; i++) {
  6266. attrs = new Attributes();
  6267. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6268. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6269. ignoreDirective);
  6270. nodeLinkFn = (directives.length)
  6271. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6272. null, [], [], previousCompileContext)
  6273. : null;
  6274. if (nodeLinkFn && nodeLinkFn.scope) {
  6275. compile.$$addScopeClass(attrs.$$element);
  6276. }
  6277. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6278. !(childNodes = nodeList[i].childNodes) ||
  6279. !childNodes.length)
  6280. ? null
  6281. : compileNodes(childNodes,
  6282. nodeLinkFn ? (
  6283. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6284. && nodeLinkFn.transclude) : transcludeFn);
  6285. if (nodeLinkFn || childLinkFn) {
  6286. linkFns.push(i, nodeLinkFn, childLinkFn);
  6287. linkFnFound = true;
  6288. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6289. }
  6290. //use the previous context only for the first element in the virtual group
  6291. previousCompileContext = null;
  6292. }
  6293. // return a linking function if we have found anything, null otherwise
  6294. return linkFnFound ? compositeLinkFn : null;
  6295. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6296. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6297. var stableNodeList;
  6298. if (nodeLinkFnFound) {
  6299. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6300. // offsets don't get screwed up
  6301. var nodeListLength = nodeList.length;
  6302. stableNodeList = new Array(nodeListLength);
  6303. // create a sparse array by only copying the elements which have a linkFn
  6304. for (i = 0; i < linkFns.length; i+=3) {
  6305. idx = linkFns[i];
  6306. stableNodeList[idx] = nodeList[idx];
  6307. }
  6308. } else {
  6309. stableNodeList = nodeList;
  6310. }
  6311. for (i = 0, ii = linkFns.length; i < ii;) {
  6312. node = stableNodeList[linkFns[i++]];
  6313. nodeLinkFn = linkFns[i++];
  6314. childLinkFn = linkFns[i++];
  6315. if (nodeLinkFn) {
  6316. if (nodeLinkFn.scope) {
  6317. childScope = scope.$new();
  6318. compile.$$addScopeInfo(jqLite(node), childScope);
  6319. } else {
  6320. childScope = scope;
  6321. }
  6322. if (nodeLinkFn.transcludeOnThisElement) {
  6323. childBoundTranscludeFn = createBoundTranscludeFn(
  6324. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6325. nodeLinkFn.elementTranscludeOnThisElement);
  6326. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6327. childBoundTranscludeFn = parentBoundTranscludeFn;
  6328. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6329. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6330. } else {
  6331. childBoundTranscludeFn = null;
  6332. }
  6333. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6334. } else if (childLinkFn) {
  6335. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6336. }
  6337. }
  6338. }
  6339. }
  6340. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6341. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6342. if (!transcludedScope) {
  6343. transcludedScope = scope.$new(false, containingScope);
  6344. transcludedScope.$$transcluded = true;
  6345. }
  6346. return transcludeFn(transcludedScope, cloneFn, {
  6347. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6348. transcludeControllers: controllers,
  6349. futureParentElement: futureParentElement
  6350. });
  6351. };
  6352. return boundTranscludeFn;
  6353. }
  6354. /**
  6355. * Looks for directives on the given node and adds them to the directive collection which is
  6356. * sorted.
  6357. *
  6358. * @param node Node to search.
  6359. * @param directives An array to which the directives are added to. This array is sorted before
  6360. * the function returns.
  6361. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6362. * @param {number=} maxPriority Max directive priority.
  6363. */
  6364. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6365. var nodeType = node.nodeType,
  6366. attrsMap = attrs.$attr,
  6367. match,
  6368. className;
  6369. switch (nodeType) {
  6370. case NODE_TYPE_ELEMENT: /* Element */
  6371. // use the node name: <directive>
  6372. addDirective(directives,
  6373. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6374. // iterate over the attributes
  6375. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6376. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6377. var attrStartName = false;
  6378. var attrEndName = false;
  6379. attr = nAttrs[j];
  6380. name = attr.name;
  6381. value = trim(attr.value);
  6382. // support ngAttr attribute binding
  6383. ngAttrName = directiveNormalize(name);
  6384. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6385. name = snake_case(ngAttrName.substr(6), '-');
  6386. }
  6387. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6388. if (directiveIsMultiElement(directiveNName)) {
  6389. if (ngAttrName === directiveNName + 'Start') {
  6390. attrStartName = name;
  6391. attrEndName = name.substr(0, name.length - 5) + 'end';
  6392. name = name.substr(0, name.length - 6);
  6393. }
  6394. }
  6395. nName = directiveNormalize(name.toLowerCase());
  6396. attrsMap[nName] = name;
  6397. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6398. attrs[nName] = value;
  6399. if (getBooleanAttrName(node, nName)) {
  6400. attrs[nName] = true; // presence means true
  6401. }
  6402. }
  6403. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6404. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6405. attrEndName);
  6406. }
  6407. // use class as directive
  6408. className = node.className;
  6409. if (isString(className) && className !== '') {
  6410. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6411. nName = directiveNormalize(match[2]);
  6412. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6413. attrs[nName] = trim(match[3]);
  6414. }
  6415. className = className.substr(match.index + match[0].length);
  6416. }
  6417. }
  6418. break;
  6419. case NODE_TYPE_TEXT: /* Text Node */
  6420. addTextInterpolateDirective(directives, node.nodeValue);
  6421. break;
  6422. case NODE_TYPE_COMMENT: /* Comment */
  6423. try {
  6424. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6425. if (match) {
  6426. nName = directiveNormalize(match[1]);
  6427. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6428. attrs[nName] = trim(match[2]);
  6429. }
  6430. }
  6431. } catch (e) {
  6432. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6433. // comment's node value.
  6434. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6435. }
  6436. break;
  6437. }
  6438. directives.sort(byPriority);
  6439. return directives;
  6440. }
  6441. /**
  6442. * Given a node with an directive-start it collects all of the siblings until it finds
  6443. * directive-end.
  6444. * @param node
  6445. * @param attrStart
  6446. * @param attrEnd
  6447. * @returns {*}
  6448. */
  6449. function groupScan(node, attrStart, attrEnd) {
  6450. var nodes = [];
  6451. var depth = 0;
  6452. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6453. do {
  6454. if (!node) {
  6455. throw $compileMinErr('uterdir',
  6456. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6457. attrStart, attrEnd);
  6458. }
  6459. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6460. if (node.hasAttribute(attrStart)) depth++;
  6461. if (node.hasAttribute(attrEnd)) depth--;
  6462. }
  6463. nodes.push(node);
  6464. node = node.nextSibling;
  6465. } while (depth > 0);
  6466. } else {
  6467. nodes.push(node);
  6468. }
  6469. return jqLite(nodes);
  6470. }
  6471. /**
  6472. * Wrapper for linking function which converts normal linking function into a grouped
  6473. * linking function.
  6474. * @param linkFn
  6475. * @param attrStart
  6476. * @param attrEnd
  6477. * @returns {Function}
  6478. */
  6479. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6480. return function(scope, element, attrs, controllers, transcludeFn) {
  6481. element = groupScan(element[0], attrStart, attrEnd);
  6482. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6483. };
  6484. }
  6485. /**
  6486. * Once the directives have been collected, their compile functions are executed. This method
  6487. * is responsible for inlining directive templates as well as terminating the application
  6488. * of the directives if the terminal directive has been reached.
  6489. *
  6490. * @param {Array} directives Array of collected directives to execute their compile function.
  6491. * this needs to be pre-sorted by priority order.
  6492. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6493. * @param {Object} templateAttrs The shared attribute function
  6494. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6495. * scope argument is auto-generated to the new
  6496. * child of the transcluded parent scope.
  6497. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6498. * argument has the root jqLite array so that we can replace nodes
  6499. * on it.
  6500. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6501. * compiling the transclusion.
  6502. * @param {Array.<Function>} preLinkFns
  6503. * @param {Array.<Function>} postLinkFns
  6504. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6505. * node
  6506. * @returns {Function} linkFn
  6507. */
  6508. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6509. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6510. previousCompileContext) {
  6511. previousCompileContext = previousCompileContext || {};
  6512. var terminalPriority = -Number.MAX_VALUE,
  6513. newScopeDirective,
  6514. controllerDirectives = previousCompileContext.controllerDirectives,
  6515. controllers,
  6516. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6517. templateDirective = previousCompileContext.templateDirective,
  6518. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6519. hasTranscludeDirective = false,
  6520. hasTemplate = false,
  6521. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6522. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6523. directive,
  6524. directiveName,
  6525. $template,
  6526. replaceDirective = originalReplaceDirective,
  6527. childTranscludeFn = transcludeFn,
  6528. linkFn,
  6529. directiveValue;
  6530. // executes all directives on the current element
  6531. for (var i = 0, ii = directives.length; i < ii; i++) {
  6532. directive = directives[i];
  6533. var attrStart = directive.$$start;
  6534. var attrEnd = directive.$$end;
  6535. // collect multiblock sections
  6536. if (attrStart) {
  6537. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6538. }
  6539. $template = undefined;
  6540. if (terminalPriority > directive.priority) {
  6541. break; // prevent further processing of directives
  6542. }
  6543. if (directiveValue = directive.scope) {
  6544. // skip the check for directives with async templates, we'll check the derived sync
  6545. // directive when the template arrives
  6546. if (!directive.templateUrl) {
  6547. if (isObject(directiveValue)) {
  6548. // This directive is trying to add an isolated scope.
  6549. // Check that there is no scope of any kind already
  6550. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6551. directive, $compileNode);
  6552. newIsolateScopeDirective = directive;
  6553. } else {
  6554. // This directive is trying to add a child scope.
  6555. // Check that there is no isolated scope already
  6556. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6557. $compileNode);
  6558. }
  6559. }
  6560. newScopeDirective = newScopeDirective || directive;
  6561. }
  6562. directiveName = directive.name;
  6563. if (!directive.templateUrl && directive.controller) {
  6564. directiveValue = directive.controller;
  6565. controllerDirectives = controllerDirectives || {};
  6566. assertNoDuplicate("'" + directiveName + "' controller",
  6567. controllerDirectives[directiveName], directive, $compileNode);
  6568. controllerDirectives[directiveName] = directive;
  6569. }
  6570. if (directiveValue = directive.transclude) {
  6571. hasTranscludeDirective = true;
  6572. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6573. // This option should only be used by directives that know how to safely handle element transclusion,
  6574. // where the transcluded nodes are added or replaced after linking.
  6575. if (!directive.$$tlb) {
  6576. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6577. nonTlbTranscludeDirective = directive;
  6578. }
  6579. if (directiveValue == 'element') {
  6580. hasElementTranscludeDirective = true;
  6581. terminalPriority = directive.priority;
  6582. $template = $compileNode;
  6583. $compileNode = templateAttrs.$$element =
  6584. jqLite(document.createComment(' ' + directiveName + ': ' +
  6585. templateAttrs[directiveName] + ' '));
  6586. compileNode = $compileNode[0];
  6587. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6588. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6589. replaceDirective && replaceDirective.name, {
  6590. // Don't pass in:
  6591. // - controllerDirectives - otherwise we'll create duplicates controllers
  6592. // - newIsolateScopeDirective or templateDirective - combining templates with
  6593. // element transclusion doesn't make sense.
  6594. //
  6595. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6596. // on the same element more than once.
  6597. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6598. });
  6599. } else {
  6600. $template = jqLite(jqLiteClone(compileNode)).contents();
  6601. $compileNode.empty(); // clear contents
  6602. childTranscludeFn = compile($template, transcludeFn);
  6603. }
  6604. }
  6605. if (directive.template) {
  6606. hasTemplate = true;
  6607. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6608. templateDirective = directive;
  6609. directiveValue = (isFunction(directive.template))
  6610. ? directive.template($compileNode, templateAttrs)
  6611. : directive.template;
  6612. directiveValue = denormalizeTemplate(directiveValue);
  6613. if (directive.replace) {
  6614. replaceDirective = directive;
  6615. if (jqLiteIsTextNode(directiveValue)) {
  6616. $template = [];
  6617. } else {
  6618. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6619. }
  6620. compileNode = $template[0];
  6621. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6622. throw $compileMinErr('tplrt',
  6623. "Template for directive '{0}' must have exactly one root element. {1}",
  6624. directiveName, '');
  6625. }
  6626. replaceWith(jqCollection, $compileNode, compileNode);
  6627. var newTemplateAttrs = {$attr: {}};
  6628. // combine directives from the original node and from the template:
  6629. // - take the array of directives for this element
  6630. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6631. // - collect directives from the template and sort them by priority
  6632. // - combine directives as: processed + template + unprocessed
  6633. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6634. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6635. if (newIsolateScopeDirective) {
  6636. markDirectivesAsIsolate(templateDirectives);
  6637. }
  6638. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6639. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6640. ii = directives.length;
  6641. } else {
  6642. $compileNode.html(directiveValue);
  6643. }
  6644. }
  6645. if (directive.templateUrl) {
  6646. hasTemplate = true;
  6647. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6648. templateDirective = directive;
  6649. if (directive.replace) {
  6650. replaceDirective = directive;
  6651. }
  6652. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6653. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6654. controllerDirectives: controllerDirectives,
  6655. newIsolateScopeDirective: newIsolateScopeDirective,
  6656. templateDirective: templateDirective,
  6657. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6658. });
  6659. ii = directives.length;
  6660. } else if (directive.compile) {
  6661. try {
  6662. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6663. if (isFunction(linkFn)) {
  6664. addLinkFns(null, linkFn, attrStart, attrEnd);
  6665. } else if (linkFn) {
  6666. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6667. }
  6668. } catch (e) {
  6669. $exceptionHandler(e, startingTag($compileNode));
  6670. }
  6671. }
  6672. if (directive.terminal) {
  6673. nodeLinkFn.terminal = true;
  6674. terminalPriority = Math.max(terminalPriority, directive.priority);
  6675. }
  6676. }
  6677. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6678. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6679. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6680. nodeLinkFn.templateOnThisElement = hasTemplate;
  6681. nodeLinkFn.transclude = childTranscludeFn;
  6682. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6683. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6684. return nodeLinkFn;
  6685. ////////////////////
  6686. function addLinkFns(pre, post, attrStart, attrEnd) {
  6687. if (pre) {
  6688. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6689. pre.require = directive.require;
  6690. pre.directiveName = directiveName;
  6691. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6692. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6693. }
  6694. preLinkFns.push(pre);
  6695. }
  6696. if (post) {
  6697. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6698. post.require = directive.require;
  6699. post.directiveName = directiveName;
  6700. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6701. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6702. }
  6703. postLinkFns.push(post);
  6704. }
  6705. }
  6706. function getControllers(directiveName, require, $element, elementControllers) {
  6707. var value, retrievalMethod = 'data', optional = false;
  6708. var $searchElement = $element;
  6709. var match;
  6710. if (isString(require)) {
  6711. match = require.match(REQUIRE_PREFIX_REGEXP);
  6712. require = require.substring(match[0].length);
  6713. if (match[3]) {
  6714. if (match[1]) match[3] = null;
  6715. else match[1] = match[3];
  6716. }
  6717. if (match[1] === '^') {
  6718. retrievalMethod = 'inheritedData';
  6719. } else if (match[1] === '^^') {
  6720. retrievalMethod = 'inheritedData';
  6721. $searchElement = $element.parent();
  6722. }
  6723. if (match[2] === '?') {
  6724. optional = true;
  6725. }
  6726. value = null;
  6727. if (elementControllers && retrievalMethod === 'data') {
  6728. if (value = elementControllers[require]) {
  6729. value = value.instance;
  6730. }
  6731. }
  6732. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6733. if (!value && !optional) {
  6734. throw $compileMinErr('ctreq',
  6735. "Controller '{0}', required by directive '{1}', can't be found!",
  6736. require, directiveName);
  6737. }
  6738. return value || null;
  6739. } else if (isArray(require)) {
  6740. value = [];
  6741. forEach(require, function(require) {
  6742. value.push(getControllers(directiveName, require, $element, elementControllers));
  6743. });
  6744. }
  6745. return value;
  6746. }
  6747. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6748. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6749. attrs;
  6750. if (compileNode === linkNode) {
  6751. attrs = templateAttrs;
  6752. $element = templateAttrs.$$element;
  6753. } else {
  6754. $element = jqLite(linkNode);
  6755. attrs = new Attributes($element, templateAttrs);
  6756. }
  6757. if (newIsolateScopeDirective) {
  6758. isolateScope = scope.$new(true);
  6759. }
  6760. if (boundTranscludeFn) {
  6761. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6762. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6763. transcludeFn = controllersBoundTransclude;
  6764. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6765. }
  6766. if (controllerDirectives) {
  6767. // TODO: merge `controllers` and `elementControllers` into single object.
  6768. controllers = {};
  6769. elementControllers = {};
  6770. forEach(controllerDirectives, function(directive) {
  6771. var locals = {
  6772. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6773. $element: $element,
  6774. $attrs: attrs,
  6775. $transclude: transcludeFn
  6776. }, controllerInstance;
  6777. controller = directive.controller;
  6778. if (controller == '@') {
  6779. controller = attrs[directive.name];
  6780. }
  6781. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6782. // For directives with element transclusion the element is a comment,
  6783. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6784. // clean up (http://bugs.jquery.com/ticket/8335).
  6785. // Instead, we save the controllers for the element in a local hash and attach to .data
  6786. // later, once we have the actual element.
  6787. elementControllers[directive.name] = controllerInstance;
  6788. if (!hasElementTranscludeDirective) {
  6789. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6790. }
  6791. controllers[directive.name] = controllerInstance;
  6792. });
  6793. }
  6794. if (newIsolateScopeDirective) {
  6795. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6796. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6797. compile.$$addScopeClass($element, true);
  6798. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6799. var isolateBindingContext = isolateScope;
  6800. if (isolateScopeController && isolateScopeController.identifier &&
  6801. newIsolateScopeDirective.bindToController === true) {
  6802. isolateBindingContext = isolateScopeController.instance;
  6803. }
  6804. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6805. var attrName = definition.attrName,
  6806. optional = definition.optional,
  6807. mode = definition.mode, // @, =, or &
  6808. lastValue,
  6809. parentGet, parentSet, compare;
  6810. switch (mode) {
  6811. case '@':
  6812. attrs.$observe(attrName, function(value) {
  6813. isolateBindingContext[scopeName] = value;
  6814. });
  6815. attrs.$$observers[attrName].$$scope = scope;
  6816. if (attrs[attrName]) {
  6817. // If the attribute has been provided then we trigger an interpolation to ensure
  6818. // the value is there for use in the link fn
  6819. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6820. }
  6821. break;
  6822. case '=':
  6823. if (optional && !attrs[attrName]) {
  6824. return;
  6825. }
  6826. parentGet = $parse(attrs[attrName]);
  6827. if (parentGet.literal) {
  6828. compare = equals;
  6829. } else {
  6830. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6831. }
  6832. parentSet = parentGet.assign || function() {
  6833. // reset the change, or we will throw this exception on every $digest
  6834. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6835. throw $compileMinErr('nonassign',
  6836. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6837. attrs[attrName], newIsolateScopeDirective.name);
  6838. };
  6839. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6840. var parentValueWatch = function parentValueWatch(parentValue) {
  6841. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6842. // we are out of sync and need to copy
  6843. if (!compare(parentValue, lastValue)) {
  6844. // parent changed and it has precedence
  6845. isolateBindingContext[scopeName] = parentValue;
  6846. } else {
  6847. // if the parent can be assigned then do so
  6848. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6849. }
  6850. }
  6851. return lastValue = parentValue;
  6852. };
  6853. parentValueWatch.$stateful = true;
  6854. var unwatch;
  6855. if (definition.collection) {
  6856. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6857. } else {
  6858. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6859. }
  6860. isolateScope.$on('$destroy', unwatch);
  6861. break;
  6862. case '&':
  6863. parentGet = $parse(attrs[attrName]);
  6864. isolateBindingContext[scopeName] = function(locals) {
  6865. return parentGet(scope, locals);
  6866. };
  6867. break;
  6868. }
  6869. });
  6870. }
  6871. if (controllers) {
  6872. forEach(controllers, function(controller) {
  6873. controller();
  6874. });
  6875. controllers = null;
  6876. }
  6877. // PRELINKING
  6878. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  6879. linkFn = preLinkFns[i];
  6880. invokeLinkFn(linkFn,
  6881. linkFn.isolateScope ? isolateScope : scope,
  6882. $element,
  6883. attrs,
  6884. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6885. transcludeFn
  6886. );
  6887. }
  6888. // RECURSION
  6889. // We only pass the isolate scope, if the isolate directive has a template,
  6890. // otherwise the child elements do not belong to the isolate directive.
  6891. var scopeToChild = scope;
  6892. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6893. scopeToChild = isolateScope;
  6894. }
  6895. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6896. // POSTLINKING
  6897. for (i = postLinkFns.length - 1; i >= 0; i--) {
  6898. linkFn = postLinkFns[i];
  6899. invokeLinkFn(linkFn,
  6900. linkFn.isolateScope ? isolateScope : scope,
  6901. $element,
  6902. attrs,
  6903. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6904. transcludeFn
  6905. );
  6906. }
  6907. // This is the function that is injected as `$transclude`.
  6908. // Note: all arguments are optional!
  6909. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  6910. var transcludeControllers;
  6911. // No scope passed in:
  6912. if (!isScope(scope)) {
  6913. futureParentElement = cloneAttachFn;
  6914. cloneAttachFn = scope;
  6915. scope = undefined;
  6916. }
  6917. if (hasElementTranscludeDirective) {
  6918. transcludeControllers = elementControllers;
  6919. }
  6920. if (!futureParentElement) {
  6921. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  6922. }
  6923. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  6924. }
  6925. }
  6926. }
  6927. function markDirectivesAsIsolate(directives) {
  6928. // mark all directives as needing isolate scope.
  6929. for (var j = 0, jj = directives.length; j < jj; j++) {
  6930. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6931. }
  6932. }
  6933. /**
  6934. * looks up the directive and decorates it with exception handling and proper parameters. We
  6935. * call this the boundDirective.
  6936. *
  6937. * @param {string} name name of the directive to look up.
  6938. * @param {string} location The directive must be found in specific format.
  6939. * String containing any of theses characters:
  6940. *
  6941. * * `E`: element name
  6942. * * `A': attribute
  6943. * * `C`: class
  6944. * * `M`: comment
  6945. * @returns {boolean} true if directive was added.
  6946. */
  6947. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6948. endAttrName) {
  6949. if (name === ignoreDirective) return null;
  6950. var match = null;
  6951. if (hasDirectives.hasOwnProperty(name)) {
  6952. for (var directive, directives = $injector.get(name + Suffix),
  6953. i = 0, ii = directives.length; i < ii; i++) {
  6954. try {
  6955. directive = directives[i];
  6956. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  6957. directive.restrict.indexOf(location) != -1) {
  6958. if (startAttrName) {
  6959. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6960. }
  6961. tDirectives.push(directive);
  6962. match = directive;
  6963. }
  6964. } catch (e) { $exceptionHandler(e); }
  6965. }
  6966. }
  6967. return match;
  6968. }
  6969. /**
  6970. * looks up the directive and returns true if it is a multi-element directive,
  6971. * and therefore requires DOM nodes between -start and -end markers to be grouped
  6972. * together.
  6973. *
  6974. * @param {string} name name of the directive to look up.
  6975. * @returns true if directive was registered as multi-element.
  6976. */
  6977. function directiveIsMultiElement(name) {
  6978. if (hasDirectives.hasOwnProperty(name)) {
  6979. for (var directive, directives = $injector.get(name + Suffix),
  6980. i = 0, ii = directives.length; i < ii; i++) {
  6981. directive = directives[i];
  6982. if (directive.multiElement) {
  6983. return true;
  6984. }
  6985. }
  6986. }
  6987. return false;
  6988. }
  6989. /**
  6990. * When the element is replaced with HTML template then the new attributes
  6991. * on the template need to be merged with the existing attributes in the DOM.
  6992. * The desired effect is to have both of the attributes present.
  6993. *
  6994. * @param {object} dst destination attributes (original DOM)
  6995. * @param {object} src source attributes (from the directive template)
  6996. */
  6997. function mergeTemplateAttributes(dst, src) {
  6998. var srcAttr = src.$attr,
  6999. dstAttr = dst.$attr,
  7000. $element = dst.$$element;
  7001. // reapply the old attributes to the new element
  7002. forEach(dst, function(value, key) {
  7003. if (key.charAt(0) != '$') {
  7004. if (src[key] && src[key] !== value) {
  7005. value += (key === 'style' ? ';' : ' ') + src[key];
  7006. }
  7007. dst.$set(key, value, true, srcAttr[key]);
  7008. }
  7009. });
  7010. // copy the new attributes on the old attrs object
  7011. forEach(src, function(value, key) {
  7012. if (key == 'class') {
  7013. safeAddClass($element, value);
  7014. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7015. } else if (key == 'style') {
  7016. $element.attr('style', $element.attr('style') + ';' + value);
  7017. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7018. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7019. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7020. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7021. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7022. dst[key] = value;
  7023. dstAttr[key] = srcAttr[key];
  7024. }
  7025. });
  7026. }
  7027. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7028. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7029. var linkQueue = [],
  7030. afterTemplateNodeLinkFn,
  7031. afterTemplateChildLinkFn,
  7032. beforeTemplateCompileNode = $compileNode[0],
  7033. origAsyncDirective = directives.shift(),
  7034. // The fact that we have to copy and patch the directive seems wrong!
  7035. derivedSyncDirective = extend({}, origAsyncDirective, {
  7036. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7037. }),
  7038. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7039. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7040. : origAsyncDirective.templateUrl,
  7041. templateNamespace = origAsyncDirective.templateNamespace;
  7042. $compileNode.empty();
  7043. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7044. .then(function(content) {
  7045. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7046. content = denormalizeTemplate(content);
  7047. if (origAsyncDirective.replace) {
  7048. if (jqLiteIsTextNode(content)) {
  7049. $template = [];
  7050. } else {
  7051. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7052. }
  7053. compileNode = $template[0];
  7054. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7055. throw $compileMinErr('tplrt',
  7056. "Template for directive '{0}' must have exactly one root element. {1}",
  7057. origAsyncDirective.name, templateUrl);
  7058. }
  7059. tempTemplateAttrs = {$attr: {}};
  7060. replaceWith($rootElement, $compileNode, compileNode);
  7061. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7062. if (isObject(origAsyncDirective.scope)) {
  7063. markDirectivesAsIsolate(templateDirectives);
  7064. }
  7065. directives = templateDirectives.concat(directives);
  7066. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7067. } else {
  7068. compileNode = beforeTemplateCompileNode;
  7069. $compileNode.html(content);
  7070. }
  7071. directives.unshift(derivedSyncDirective);
  7072. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7073. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7074. previousCompileContext);
  7075. forEach($rootElement, function(node, i) {
  7076. if (node == compileNode) {
  7077. $rootElement[i] = $compileNode[0];
  7078. }
  7079. });
  7080. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7081. while (linkQueue.length) {
  7082. var scope = linkQueue.shift(),
  7083. beforeTemplateLinkNode = linkQueue.shift(),
  7084. linkRootElement = linkQueue.shift(),
  7085. boundTranscludeFn = linkQueue.shift(),
  7086. linkNode = $compileNode[0];
  7087. if (scope.$$destroyed) continue;
  7088. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7089. var oldClasses = beforeTemplateLinkNode.className;
  7090. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7091. origAsyncDirective.replace)) {
  7092. // it was cloned therefore we have to clone as well.
  7093. linkNode = jqLiteClone(compileNode);
  7094. }
  7095. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7096. // Copy in CSS classes from original node
  7097. safeAddClass(jqLite(linkNode), oldClasses);
  7098. }
  7099. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7100. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7101. } else {
  7102. childBoundTranscludeFn = boundTranscludeFn;
  7103. }
  7104. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7105. childBoundTranscludeFn);
  7106. }
  7107. linkQueue = null;
  7108. });
  7109. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7110. var childBoundTranscludeFn = boundTranscludeFn;
  7111. if (scope.$$destroyed) return;
  7112. if (linkQueue) {
  7113. linkQueue.push(scope,
  7114. node,
  7115. rootElement,
  7116. childBoundTranscludeFn);
  7117. } else {
  7118. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7119. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7120. }
  7121. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7122. }
  7123. };
  7124. }
  7125. /**
  7126. * Sorting function for bound directives.
  7127. */
  7128. function byPriority(a, b) {
  7129. var diff = b.priority - a.priority;
  7130. if (diff !== 0) return diff;
  7131. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7132. return a.index - b.index;
  7133. }
  7134. function assertNoDuplicate(what, previousDirective, directive, element) {
  7135. if (previousDirective) {
  7136. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7137. previousDirective.name, directive.name, what, startingTag(element));
  7138. }
  7139. }
  7140. function addTextInterpolateDirective(directives, text) {
  7141. var interpolateFn = $interpolate(text, true);
  7142. if (interpolateFn) {
  7143. directives.push({
  7144. priority: 0,
  7145. compile: function textInterpolateCompileFn(templateNode) {
  7146. var templateNodeParent = templateNode.parent(),
  7147. hasCompileParent = !!templateNodeParent.length;
  7148. // When transcluding a template that has bindings in the root
  7149. // we don't have a parent and thus need to add the class during linking fn.
  7150. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7151. return function textInterpolateLinkFn(scope, node) {
  7152. var parent = node.parent();
  7153. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7154. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7155. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7156. node[0].nodeValue = value;
  7157. });
  7158. };
  7159. }
  7160. });
  7161. }
  7162. }
  7163. function wrapTemplate(type, template) {
  7164. type = lowercase(type || 'html');
  7165. switch (type) {
  7166. case 'svg':
  7167. case 'math':
  7168. var wrapper = document.createElement('div');
  7169. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7170. return wrapper.childNodes[0].childNodes;
  7171. default:
  7172. return template;
  7173. }
  7174. }
  7175. function getTrustedContext(node, attrNormalizedName) {
  7176. if (attrNormalizedName == "srcdoc") {
  7177. return $sce.HTML;
  7178. }
  7179. var tag = nodeName_(node);
  7180. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7181. if (attrNormalizedName == "xlinkHref" ||
  7182. (tag == "form" && attrNormalizedName == "action") ||
  7183. (tag != "img" && (attrNormalizedName == "src" ||
  7184. attrNormalizedName == "ngSrc"))) {
  7185. return $sce.RESOURCE_URL;
  7186. }
  7187. }
  7188. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7189. var interpolateFn = $interpolate(value, true);
  7190. // no interpolation found -> ignore
  7191. if (!interpolateFn) return;
  7192. if (name === "multiple" && nodeName_(node) === "select") {
  7193. throw $compileMinErr("selmulti",
  7194. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7195. startingTag(node));
  7196. }
  7197. directives.push({
  7198. priority: 100,
  7199. compile: function() {
  7200. return {
  7201. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7202. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7203. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7204. throw $compileMinErr('nodomevents',
  7205. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7206. "ng- versions (such as ng-click instead of onclick) instead.");
  7207. }
  7208. // If the attribute was removed, then we are done
  7209. if (!attr[name]) {
  7210. return;
  7211. }
  7212. // we need to interpolate again, in case the attribute value has been updated
  7213. // (e.g. by another directive's compile function)
  7214. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name),
  7215. ALL_OR_NOTHING_ATTRS[name] || allOrNothing);
  7216. // if attribute was updated so that there is no interpolation going on we don't want to
  7217. // register any observers
  7218. if (!interpolateFn) return;
  7219. // initialize attr object so that it's ready in case we need the value for isolate
  7220. // scope initialization, otherwise the value would not be available from isolate
  7221. // directive's linking fn during linking phase
  7222. attr[name] = interpolateFn(scope);
  7223. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7224. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7225. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7226. //special case for class attribute addition + removal
  7227. //so that class changes can tap into the animation
  7228. //hooks provided by the $animate service. Be sure to
  7229. //skip animations when the first digest occurs (when
  7230. //both the new and the old values are the same) since
  7231. //the CSS classes are the non-interpolated values
  7232. if (name === 'class' && newValue != oldValue) {
  7233. attr.$updateClass(newValue, oldValue);
  7234. } else {
  7235. attr.$set(name, newValue);
  7236. }
  7237. });
  7238. }
  7239. };
  7240. }
  7241. });
  7242. }
  7243. /**
  7244. * This is a special jqLite.replaceWith, which can replace items which
  7245. * have no parents, provided that the containing jqLite collection is provided.
  7246. *
  7247. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7248. * in the root of the tree.
  7249. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7250. * the shell, but replace its DOM node reference.
  7251. * @param {Node} newNode The new DOM node.
  7252. */
  7253. function replaceWith($rootElement, elementsToRemove, newNode) {
  7254. var firstElementToRemove = elementsToRemove[0],
  7255. removeCount = elementsToRemove.length,
  7256. parent = firstElementToRemove.parentNode,
  7257. i, ii;
  7258. if ($rootElement) {
  7259. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7260. if ($rootElement[i] == firstElementToRemove) {
  7261. $rootElement[i++] = newNode;
  7262. for (var j = i, j2 = j + removeCount - 1,
  7263. jj = $rootElement.length;
  7264. j < jj; j++, j2++) {
  7265. if (j2 < jj) {
  7266. $rootElement[j] = $rootElement[j2];
  7267. } else {
  7268. delete $rootElement[j];
  7269. }
  7270. }
  7271. $rootElement.length -= removeCount - 1;
  7272. // If the replaced element is also the jQuery .context then replace it
  7273. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7274. // http://api.jquery.com/context/
  7275. if ($rootElement.context === firstElementToRemove) {
  7276. $rootElement.context = newNode;
  7277. }
  7278. break;
  7279. }
  7280. }
  7281. }
  7282. if (parent) {
  7283. parent.replaceChild(newNode, firstElementToRemove);
  7284. }
  7285. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7286. var fragment = document.createDocumentFragment();
  7287. fragment.appendChild(firstElementToRemove);
  7288. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7289. // data here because there's no public interface in jQuery to do that and copying over
  7290. // event listeners (which is the main use of private data) wouldn't work anyway.
  7291. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7292. // Remove data of the replaced element. We cannot just call .remove()
  7293. // on the element it since that would deallocate scope that is needed
  7294. // for the new node. Instead, remove the data "manually".
  7295. if (!jQuery) {
  7296. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7297. } else {
  7298. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7299. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7300. // the scope to be trashed and we do need the very same scope to work with the new
  7301. // element. However, we cannot just cache the non-patched version and use it here as
  7302. // that would break if another library patches the method after Angular does (one
  7303. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7304. // skipped this one time.
  7305. skipDestroyOnNextJQueryCleanData = true;
  7306. jQuery.cleanData([firstElementToRemove]);
  7307. }
  7308. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7309. var element = elementsToRemove[k];
  7310. jqLite(element).remove(); // must do this way to clean up expando
  7311. fragment.appendChild(element);
  7312. delete elementsToRemove[k];
  7313. }
  7314. elementsToRemove[0] = newNode;
  7315. elementsToRemove.length = 1;
  7316. }
  7317. function cloneAndAnnotateFn(fn, annotation) {
  7318. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7319. }
  7320. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7321. try {
  7322. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7323. } catch (e) {
  7324. $exceptionHandler(e, startingTag($element));
  7325. }
  7326. }
  7327. }];
  7328. }
  7329. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7330. /**
  7331. * Converts all accepted directives format into proper directive name.
  7332. * All of these will become 'myDirective':
  7333. * my:Directive
  7334. * my-directive
  7335. * x-my-directive
  7336. * data-my:directive
  7337. *
  7338. * Also there is special case for Moz prefix starting with upper case letter.
  7339. * @param name Name to normalize
  7340. */
  7341. function directiveNormalize(name) {
  7342. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7343. }
  7344. /**
  7345. * @ngdoc type
  7346. * @name $compile.directive.Attributes
  7347. *
  7348. * @description
  7349. * A shared object between directive compile / linking functions which contains normalized DOM
  7350. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7351. * needed since all of these are treated as equivalent in Angular:
  7352. *
  7353. * ```
  7354. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7355. * ```
  7356. */
  7357. /**
  7358. * @ngdoc property
  7359. * @name $compile.directive.Attributes#$attr
  7360. *
  7361. * @description
  7362. * A map of DOM element attribute names to the normalized name. This is
  7363. * needed to do reverse lookup from normalized name back to actual name.
  7364. */
  7365. /**
  7366. * @ngdoc method
  7367. * @name $compile.directive.Attributes#$set
  7368. * @kind function
  7369. *
  7370. * @description
  7371. * Set DOM element attribute value.
  7372. *
  7373. *
  7374. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7375. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7376. * property to the original name.
  7377. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7378. */
  7379. /**
  7380. * Closure compiler type information
  7381. */
  7382. function nodesetLinkingFn(
  7383. /* angular.Scope */ scope,
  7384. /* NodeList */ nodeList,
  7385. /* Element */ rootElement,
  7386. /* function(Function) */ boundTranscludeFn
  7387. ) {}
  7388. function directiveLinkingFn(
  7389. /* nodesetLinkingFn */ nodesetLinkingFn,
  7390. /* angular.Scope */ scope,
  7391. /* Node */ node,
  7392. /* Element */ rootElement,
  7393. /* function(Function) */ boundTranscludeFn
  7394. ) {}
  7395. function tokenDifference(str1, str2) {
  7396. var values = '',
  7397. tokens1 = str1.split(/\s+/),
  7398. tokens2 = str2.split(/\s+/);
  7399. outer:
  7400. for (var i = 0; i < tokens1.length; i++) {
  7401. var token = tokens1[i];
  7402. for (var j = 0; j < tokens2.length; j++) {
  7403. if (token == tokens2[j]) continue outer;
  7404. }
  7405. values += (values.length > 0 ? ' ' : '') + token;
  7406. }
  7407. return values;
  7408. }
  7409. function removeComments(jqNodes) {
  7410. jqNodes = jqLite(jqNodes);
  7411. var i = jqNodes.length;
  7412. if (i <= 1) {
  7413. return jqNodes;
  7414. }
  7415. while (i--) {
  7416. var node = jqNodes[i];
  7417. if (node.nodeType === NODE_TYPE_COMMENT) {
  7418. splice.call(jqNodes, i, 1);
  7419. }
  7420. }
  7421. return jqNodes;
  7422. }
  7423. /**
  7424. * @ngdoc provider
  7425. * @name $controllerProvider
  7426. * @description
  7427. * The {@link ng.$controller $controller service} is used by Angular to create new
  7428. * controllers.
  7429. *
  7430. * This provider allows controller registration via the
  7431. * {@link ng.$controllerProvider#register register} method.
  7432. */
  7433. function $ControllerProvider() {
  7434. var controllers = {},
  7435. globals = false,
  7436. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7437. /**
  7438. * @ngdoc method
  7439. * @name $controllerProvider#register
  7440. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7441. * the names and the values are the constructors.
  7442. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7443. * annotations in the array notation).
  7444. */
  7445. this.register = function(name, constructor) {
  7446. assertNotHasOwnProperty(name, 'controller');
  7447. if (isObject(name)) {
  7448. extend(controllers, name);
  7449. } else {
  7450. controllers[name] = constructor;
  7451. }
  7452. };
  7453. /**
  7454. * @ngdoc method
  7455. * @name $controllerProvider#allowGlobals
  7456. * @description If called, allows `$controller` to find controller constructors on `window`
  7457. */
  7458. this.allowGlobals = function() {
  7459. globals = true;
  7460. };
  7461. this.$get = ['$injector', '$window', function($injector, $window) {
  7462. /**
  7463. * @ngdoc service
  7464. * @name $controller
  7465. * @requires $injector
  7466. *
  7467. * @param {Function|string} constructor If called with a function then it's considered to be the
  7468. * controller constructor function. Otherwise it's considered to be a string which is used
  7469. * to retrieve the controller constructor using the following steps:
  7470. *
  7471. * * check if a controller with given name is registered via `$controllerProvider`
  7472. * * check if evaluating the string on the current scope returns a constructor
  7473. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7474. * `window` object (not recommended)
  7475. *
  7476. * The string can use the `controller as property` syntax, where the controller instance is published
  7477. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  7478. * to work correctly.
  7479. *
  7480. * @param {Object} locals Injection locals for Controller.
  7481. * @return {Object} Instance of given controller.
  7482. *
  7483. * @description
  7484. * `$controller` service is responsible for instantiating controllers.
  7485. *
  7486. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7487. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7488. */
  7489. return function(expression, locals, later, ident) {
  7490. // PRIVATE API:
  7491. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7492. // If true, $controller will allocate the object with the correct
  7493. // prototype chain, but will not invoke the controller until a returned
  7494. // callback is invoked.
  7495. // param `ident` --- An optional label which overrides the label parsed from the controller
  7496. // expression, if any.
  7497. var instance, match, constructor, identifier;
  7498. later = later === true;
  7499. if (ident && isString(ident)) {
  7500. identifier = ident;
  7501. }
  7502. if (isString(expression)) {
  7503. match = expression.match(CNTRL_REG),
  7504. constructor = match[1],
  7505. identifier = identifier || match[3];
  7506. expression = controllers.hasOwnProperty(constructor)
  7507. ? controllers[constructor]
  7508. : getter(locals.$scope, constructor, true) ||
  7509. (globals ? getter($window, constructor, true) : undefined);
  7510. assertArgFn(expression, constructor, true);
  7511. }
  7512. if (later) {
  7513. // Instantiate controller later:
  7514. // This machinery is used to create an instance of the object before calling the
  7515. // controller's constructor itself.
  7516. //
  7517. // This allows properties to be added to the controller before the constructor is
  7518. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7519. //
  7520. // This feature is not intended for use by applications, and is thus not documented
  7521. // publicly.
  7522. // Object creation: http://jsperf.com/create-constructor/2
  7523. var controllerPrototype = (isArray(expression) ?
  7524. expression[expression.length - 1] : expression).prototype;
  7525. instance = Object.create(controllerPrototype);
  7526. if (identifier) {
  7527. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7528. }
  7529. return extend(function() {
  7530. $injector.invoke(expression, instance, locals, constructor);
  7531. return instance;
  7532. }, {
  7533. instance: instance,
  7534. identifier: identifier
  7535. });
  7536. }
  7537. instance = $injector.instantiate(expression, locals, constructor);
  7538. if (identifier) {
  7539. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7540. }
  7541. return instance;
  7542. };
  7543. function addIdentifier(locals, identifier, instance, name) {
  7544. if (!(locals && isObject(locals.$scope))) {
  7545. throw minErr('$controller')('noscp',
  7546. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7547. name, identifier);
  7548. }
  7549. locals.$scope[identifier] = instance;
  7550. }
  7551. }];
  7552. }
  7553. /**
  7554. * @ngdoc service
  7555. * @name $document
  7556. * @requires $window
  7557. *
  7558. * @description
  7559. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7560. *
  7561. * @example
  7562. <example module="documentExample">
  7563. <file name="index.html">
  7564. <div ng-controller="ExampleController">
  7565. <p>$document title: <b ng-bind="title"></b></p>
  7566. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7567. </div>
  7568. </file>
  7569. <file name="script.js">
  7570. angular.module('documentExample', [])
  7571. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7572. $scope.title = $document[0].title;
  7573. $scope.windowTitle = angular.element(window.document)[0].title;
  7574. }]);
  7575. </file>
  7576. </example>
  7577. */
  7578. function $DocumentProvider() {
  7579. this.$get = ['$window', function(window) {
  7580. return jqLite(window.document);
  7581. }];
  7582. }
  7583. /**
  7584. * @ngdoc service
  7585. * @name $exceptionHandler
  7586. * @requires ng.$log
  7587. *
  7588. * @description
  7589. * Any uncaught exception in angular expressions is delegated to this service.
  7590. * The default implementation simply delegates to `$log.error` which logs it into
  7591. * the browser console.
  7592. *
  7593. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7594. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7595. *
  7596. * ## Example:
  7597. *
  7598. * ```js
  7599. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7600. * return function(exception, cause) {
  7601. * exception.message += ' (caused by "' + cause + '")';
  7602. * throw exception;
  7603. * };
  7604. * });
  7605. * ```
  7606. *
  7607. * This example will override the normal action of `$exceptionHandler`, to make angular
  7608. * exceptions fail hard when they happen, instead of just logging to the console.
  7609. *
  7610. * <hr />
  7611. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7612. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7613. * (unless executed during a digest).
  7614. *
  7615. * If you wish, you can manually delegate exceptions, e.g.
  7616. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7617. *
  7618. * @param {Error} exception Exception associated with the error.
  7619. * @param {string=} cause optional information about the context in which
  7620. * the error was thrown.
  7621. *
  7622. */
  7623. function $ExceptionHandlerProvider() {
  7624. this.$get = ['$log', function($log) {
  7625. return function(exception, cause) {
  7626. $log.error.apply($log, arguments);
  7627. };
  7628. }];
  7629. }
  7630. var APPLICATION_JSON = 'application/json';
  7631. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7632. var JSON_START = /^\s*(\[|\{[^\{])/;
  7633. var JSON_END = /[\}\]]\s*$/;
  7634. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7635. function defaultHttpResponseTransform(data, headers) {
  7636. if (isString(data)) {
  7637. // strip json vulnerability protection prefix
  7638. data = data.replace(JSON_PROTECTION_PREFIX, '');
  7639. var contentType = headers('Content-Type');
  7640. if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0 && data.trim()) ||
  7641. (JSON_START.test(data) && JSON_END.test(data))) {
  7642. data = fromJson(data);
  7643. }
  7644. }
  7645. return data;
  7646. }
  7647. /**
  7648. * Parse headers into key value object
  7649. *
  7650. * @param {string} headers Raw headers as a string
  7651. * @returns {Object} Parsed headers as key value object
  7652. */
  7653. function parseHeaders(headers) {
  7654. var parsed = createMap(), key, val, i;
  7655. if (!headers) return parsed;
  7656. forEach(headers.split('\n'), function(line) {
  7657. i = line.indexOf(':');
  7658. key = lowercase(trim(line.substr(0, i)));
  7659. val = trim(line.substr(i + 1));
  7660. if (key) {
  7661. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7662. }
  7663. });
  7664. return parsed;
  7665. }
  7666. /**
  7667. * Returns a function that provides access to parsed headers.
  7668. *
  7669. * Headers are lazy parsed when first requested.
  7670. * @see parseHeaders
  7671. *
  7672. * @param {(string|Object)} headers Headers to provide access to.
  7673. * @returns {function(string=)} Returns a getter function which if called with:
  7674. *
  7675. * - if called with single an argument returns a single header value or null
  7676. * - if called with no arguments returns an object containing all headers.
  7677. */
  7678. function headersGetter(headers) {
  7679. var headersObj = isObject(headers) ? headers : undefined;
  7680. return function(name) {
  7681. if (!headersObj) headersObj = parseHeaders(headers);
  7682. if (name) {
  7683. var value = headersObj[lowercase(name)];
  7684. if (value === void 0) {
  7685. value = null;
  7686. }
  7687. return value;
  7688. }
  7689. return headersObj;
  7690. };
  7691. }
  7692. /**
  7693. * Chain all given functions
  7694. *
  7695. * This function is used for both request and response transforming
  7696. *
  7697. * @param {*} data Data to transform.
  7698. * @param {function(string=)} headers Http headers getter fn.
  7699. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7700. * @returns {*} Transformed data.
  7701. */
  7702. function transformData(data, headers, fns) {
  7703. if (isFunction(fns))
  7704. return fns(data, headers);
  7705. forEach(fns, function(fn) {
  7706. data = fn(data, headers);
  7707. });
  7708. return data;
  7709. }
  7710. function isSuccess(status) {
  7711. return 200 <= status && status < 300;
  7712. }
  7713. /**
  7714. * @ngdoc provider
  7715. * @name $httpProvider
  7716. * @description
  7717. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7718. * */
  7719. function $HttpProvider() {
  7720. /**
  7721. * @ngdoc property
  7722. * @name $httpProvider#defaults
  7723. * @description
  7724. *
  7725. * Object containing default values for all {@link ng.$http $http} requests.
  7726. *
  7727. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  7728. * that will provide the cache for all requests who set their `cache` property to `true`.
  7729. * If you set the `default.cache = false` then only requests that specify their own custom
  7730. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  7731. *
  7732. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7733. * Defaults value is `'XSRF-TOKEN'`.
  7734. *
  7735. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7736. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7737. *
  7738. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7739. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7740. * setting default headers.
  7741. * - **`defaults.headers.common`**
  7742. * - **`defaults.headers.post`**
  7743. * - **`defaults.headers.put`**
  7744. * - **`defaults.headers.patch`**
  7745. *
  7746. **/
  7747. var defaults = this.defaults = {
  7748. // transform incoming response data
  7749. transformResponse: [defaultHttpResponseTransform],
  7750. // transform outgoing request data
  7751. transformRequest: [function(d) {
  7752. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  7753. }],
  7754. // default headers
  7755. headers: {
  7756. common: {
  7757. 'Accept': 'application/json, text/plain, */*'
  7758. },
  7759. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7760. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7761. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7762. },
  7763. xsrfCookieName: 'XSRF-TOKEN',
  7764. xsrfHeaderName: 'X-XSRF-TOKEN'
  7765. };
  7766. var useApplyAsync = false;
  7767. /**
  7768. * @ngdoc method
  7769. * @name $httpProvider#useApplyAsync
  7770. * @description
  7771. *
  7772. * Configure $http service to combine processing of multiple http responses received at around
  7773. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7774. * significant performance improvement for bigger applications that make many HTTP requests
  7775. * concurrently (common during application bootstrap).
  7776. *
  7777. * Defaults to false. If no value is specifed, returns the current configured value.
  7778. *
  7779. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7780. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7781. * to load and share the same digest cycle.
  7782. *
  7783. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7784. * otherwise, returns the current configured value.
  7785. **/
  7786. this.useApplyAsync = function(value) {
  7787. if (isDefined(value)) {
  7788. useApplyAsync = !!value;
  7789. return this;
  7790. }
  7791. return useApplyAsync;
  7792. };
  7793. /**
  7794. * @ngdoc property
  7795. * @name $httpProvider#interceptors
  7796. * @description
  7797. *
  7798. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7799. * pre-processing of request or postprocessing of responses.
  7800. *
  7801. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7802. * array, on request, but reverse order, on response.
  7803. *
  7804. * {@link ng.$http#interceptors Interceptors detailed info}
  7805. **/
  7806. var interceptorFactories = this.interceptors = [];
  7807. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7808. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7809. var defaultCache = $cacheFactory('$http');
  7810. /**
  7811. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7812. * The reversal is needed so that we can build up the interception chain around the
  7813. * server request.
  7814. */
  7815. var reversedInterceptors = [];
  7816. forEach(interceptorFactories, function(interceptorFactory) {
  7817. reversedInterceptors.unshift(isString(interceptorFactory)
  7818. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7819. });
  7820. /**
  7821. * @ngdoc service
  7822. * @kind function
  7823. * @name $http
  7824. * @requires ng.$httpBackend
  7825. * @requires $cacheFactory
  7826. * @requires $rootScope
  7827. * @requires $q
  7828. * @requires $injector
  7829. *
  7830. * @description
  7831. * The `$http` service is a core Angular service that facilitates communication with the remote
  7832. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7833. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7834. *
  7835. * For unit testing applications that use `$http` service, see
  7836. * {@link ngMock.$httpBackend $httpBackend mock}.
  7837. *
  7838. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7839. * $resource} service.
  7840. *
  7841. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7842. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7843. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7844. *
  7845. *
  7846. * ## General usage
  7847. * The `$http` service is a function which takes a single argument — a configuration object —
  7848. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7849. * with two $http specific methods: `success` and `error`.
  7850. *
  7851. * ```js
  7852. * // Simple GET request example :
  7853. * $http.get('/someUrl').
  7854. * success(function(data, status, headers, config) {
  7855. * // this callback will be called asynchronously
  7856. * // when the response is available
  7857. * }).
  7858. * error(function(data, status, headers, config) {
  7859. * // called asynchronously if an error occurs
  7860. * // or server returns response with an error status.
  7861. * });
  7862. * ```
  7863. *
  7864. * ```js
  7865. * // Simple POST request example (passing data) :
  7866. * $http.post('/someUrl', {msg:'hello word!'}).
  7867. * success(function(data, status, headers, config) {
  7868. * // this callback will be called asynchronously
  7869. * // when the response is available
  7870. * }).
  7871. * error(function(data, status, headers, config) {
  7872. * // called asynchronously if an error occurs
  7873. * // or server returns response with an error status.
  7874. * });
  7875. * ```
  7876. *
  7877. *
  7878. * Since the returned value of calling the $http function is a `promise`, you can also use
  7879. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7880. * an object representing the response. See the API signature and type info below for more
  7881. * details.
  7882. *
  7883. * A response status code between 200 and 299 is considered a success status and
  7884. * will result in the success callback being called. Note that if the response is a redirect,
  7885. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  7886. * called for such responses.
  7887. *
  7888. * ## Writing Unit Tests that use $http
  7889. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  7890. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  7891. * request using trained responses.
  7892. *
  7893. * ```
  7894. * $httpBackend.expectGET(...);
  7895. * $http.get(...);
  7896. * $httpBackend.flush();
  7897. * ```
  7898. *
  7899. * ## Shortcut methods
  7900. *
  7901. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  7902. * request data must be passed in for POST/PUT requests.
  7903. *
  7904. * ```js
  7905. * $http.get('/someUrl').success(successCallback);
  7906. * $http.post('/someUrl', data).success(successCallback);
  7907. * ```
  7908. *
  7909. * Complete list of shortcut methods:
  7910. *
  7911. * - {@link ng.$http#get $http.get}
  7912. * - {@link ng.$http#head $http.head}
  7913. * - {@link ng.$http#post $http.post}
  7914. * - {@link ng.$http#put $http.put}
  7915. * - {@link ng.$http#delete $http.delete}
  7916. * - {@link ng.$http#jsonp $http.jsonp}
  7917. * - {@link ng.$http#patch $http.patch}
  7918. *
  7919. *
  7920. * ## Setting HTTP Headers
  7921. *
  7922. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  7923. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  7924. * object, which currently contains this default configuration:
  7925. *
  7926. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  7927. * - `Accept: application/json, text/plain, * / *`
  7928. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  7929. * - `Content-Type: application/json`
  7930. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  7931. * - `Content-Type: application/json`
  7932. *
  7933. * To add or overwrite these defaults, simply add or remove a property from these configuration
  7934. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  7935. * with the lowercased HTTP method name as the key, e.g.
  7936. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  7937. *
  7938. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  7939. * fashion. For example:
  7940. *
  7941. * ```
  7942. * module.run(function($http) {
  7943. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  7944. * });
  7945. * ```
  7946. *
  7947. * In addition, you can supply a `headers` property in the config object passed when
  7948. * calling `$http(config)`, which overrides the defaults without changing them globally.
  7949. *
  7950. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  7951. * Use the `headers` property, setting the desired header to `undefined`. For example:
  7952. *
  7953. * ```js
  7954. * var req = {
  7955. * method: 'POST',
  7956. * url: 'http://example.com',
  7957. * headers: {
  7958. * 'Content-Type': undefined
  7959. * },
  7960. * data: { test: 'test' },
  7961. * }
  7962. *
  7963. * $http(req).success(function(){...}).error(function(){...});
  7964. * ```
  7965. *
  7966. * ## Transforming Requests and Responses
  7967. *
  7968. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  7969. * and `transformResponse`. These properties can be a single function that returns
  7970. * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions,
  7971. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  7972. *
  7973. * ### Default Transformations
  7974. *
  7975. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  7976. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  7977. * then these will be applied.
  7978. *
  7979. * You can augment or replace the default transformations by modifying these properties by adding to or
  7980. * replacing the array.
  7981. *
  7982. * Angular provides the following default transformations:
  7983. *
  7984. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  7985. *
  7986. * - If the `data` property of the request configuration object contains an object, serialize it
  7987. * into JSON format.
  7988. *
  7989. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  7990. *
  7991. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  7992. * - If JSON response is detected, deserialize it using a JSON parser.
  7993. *
  7994. *
  7995. * ### Overriding the Default Transformations Per Request
  7996. *
  7997. * If you wish override the request/response transformations only for a single request then provide
  7998. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  7999. * into `$http`.
  8000. *
  8001. * Note that if you provide these properties on the config object the default transformations will be
  8002. * overwritten. If you wish to augment the default transformations then you must include them in your
  8003. * local transformation array.
  8004. *
  8005. * The following code demonstrates adding a new response transformation to be run after the default response
  8006. * transformations have been run.
  8007. *
  8008. * ```js
  8009. * function appendTransform(defaults, transform) {
  8010. *
  8011. * // We can't guarantee that the default transformation is an array
  8012. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8013. *
  8014. * // Append the new transformation to the defaults
  8015. * return defaults.concat(transform);
  8016. * }
  8017. *
  8018. * $http({
  8019. * url: '...',
  8020. * method: 'GET',
  8021. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8022. * return doTransform(value);
  8023. * })
  8024. * });
  8025. * ```
  8026. *
  8027. *
  8028. * ## Caching
  8029. *
  8030. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8031. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8032. * When the cache is enabled, `$http` stores the response from the server in the specified
  8033. * cache. The next time the same request is made, the response is served from the cache without
  8034. * sending a request to the server.
  8035. *
  8036. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8037. * the same way that real requests are.
  8038. *
  8039. * If there are multiple GET requests for the same URL that should be cached using the same
  8040. * cache, but the cache is not populated yet, only one request to the server will be made and
  8041. * the remaining requests will be fulfilled using the response from the first request.
  8042. *
  8043. * You can change the default cache to a new object (built with
  8044. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8045. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8046. * their `cache` property to `true` will now use this cache object.
  8047. *
  8048. * If you set the default cache to `false` then only requests that specify their own custom
  8049. * cache object will be cached.
  8050. *
  8051. * ## Interceptors
  8052. *
  8053. * Before you start creating interceptors, be sure to understand the
  8054. * {@link ng.$q $q and deferred/promise APIs}.
  8055. *
  8056. * For purposes of global error handling, authentication, or any kind of synchronous or
  8057. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8058. * able to intercept requests before they are handed to the server and
  8059. * responses before they are handed over to the application code that
  8060. * initiated these requests. The interceptors leverage the {@link ng.$q
  8061. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8062. *
  8063. * The interceptors are service factories that are registered with the `$httpProvider` by
  8064. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8065. * injected with dependencies (if specified) and returns the interceptor.
  8066. *
  8067. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8068. *
  8069. * * `request`: interceptors get called with a http `config` object. The function is free to
  8070. * modify the `config` object or create a new one. The function needs to return the `config`
  8071. * object directly, or a promise containing the `config` or a new `config` object.
  8072. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8073. * resolved with a rejection.
  8074. * * `response`: interceptors get called with http `response` object. The function is free to
  8075. * modify the `response` object or create a new one. The function needs to return the `response`
  8076. * object directly, or as a promise containing the `response` or a new `response` object.
  8077. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8078. * resolved with a rejection.
  8079. *
  8080. *
  8081. * ```js
  8082. * // register the interceptor as a service
  8083. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8084. * return {
  8085. * // optional method
  8086. * 'request': function(config) {
  8087. * // do something on success
  8088. * return config;
  8089. * },
  8090. *
  8091. * // optional method
  8092. * 'requestError': function(rejection) {
  8093. * // do something on error
  8094. * if (canRecover(rejection)) {
  8095. * return responseOrNewPromise
  8096. * }
  8097. * return $q.reject(rejection);
  8098. * },
  8099. *
  8100. *
  8101. *
  8102. * // optional method
  8103. * 'response': function(response) {
  8104. * // do something on success
  8105. * return response;
  8106. * },
  8107. *
  8108. * // optional method
  8109. * 'responseError': function(rejection) {
  8110. * // do something on error
  8111. * if (canRecover(rejection)) {
  8112. * return responseOrNewPromise
  8113. * }
  8114. * return $q.reject(rejection);
  8115. * }
  8116. * };
  8117. * });
  8118. *
  8119. * $httpProvider.interceptors.push('myHttpInterceptor');
  8120. *
  8121. *
  8122. * // alternatively, register the interceptor via an anonymous factory
  8123. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8124. * return {
  8125. * 'request': function(config) {
  8126. * // same as above
  8127. * },
  8128. *
  8129. * 'response': function(response) {
  8130. * // same as above
  8131. * }
  8132. * };
  8133. * });
  8134. * ```
  8135. *
  8136. * ## Security Considerations
  8137. *
  8138. * When designing web applications, consider security threats from:
  8139. *
  8140. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8141. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8142. *
  8143. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8144. * pre-configured with strategies that address these issues, but for this to work backend server
  8145. * cooperation is required.
  8146. *
  8147. * ### JSON Vulnerability Protection
  8148. *
  8149. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8150. * allows third party website to turn your JSON resource URL into
  8151. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8152. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8153. * Angular will automatically strip the prefix before processing it as JSON.
  8154. *
  8155. * For example if your server needs to return:
  8156. * ```js
  8157. * ['one','two']
  8158. * ```
  8159. *
  8160. * which is vulnerable to attack, your server can return:
  8161. * ```js
  8162. * )]}',
  8163. * ['one','two']
  8164. * ```
  8165. *
  8166. * Angular will strip the prefix, before processing the JSON.
  8167. *
  8168. *
  8169. * ### Cross Site Request Forgery (XSRF) Protection
  8170. *
  8171. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8172. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8173. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8174. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8175. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8176. * the XHR came from JavaScript running on your domain. The header will not be set for
  8177. * cross-domain requests.
  8178. *
  8179. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8180. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8181. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8182. * that only JavaScript running on your domain could have sent the request. The token must be
  8183. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8184. * making up its own tokens). We recommend that the token is a digest of your site's
  8185. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8186. * for added security.
  8187. *
  8188. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8189. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8190. * or the per-request config object.
  8191. *
  8192. *
  8193. * @param {object} config Object describing the request to be made and how it should be
  8194. * processed. The object has following properties:
  8195. *
  8196. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8197. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8198. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8199. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8200. * JSONified.
  8201. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8202. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8203. * HTTP headers to send to the server. If the return value of a function is null, the
  8204. * header will not be sent.
  8205. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8206. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8207. * - **transformRequest** –
  8208. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8209. * transform function or an array of such functions. The transform function takes the http
  8210. * request body and headers and returns its transformed (typically serialized) version.
  8211. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8212. * - **transformResponse** –
  8213. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8214. * transform function or an array of such functions. The transform function takes the http
  8215. * response body and headers and returns its transformed (typically deserialized) version.
  8216. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8217. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8218. * GET request, otherwise if a cache instance built with
  8219. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8220. * caching.
  8221. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8222. * that should abort the request when resolved.
  8223. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8224. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8225. * for more information.
  8226. * - **responseType** - `{string}` - see
  8227. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8228. *
  8229. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8230. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8231. * method takes two arguments a success and an error callback which will be called with a
  8232. * response object. The `success` and `error` methods take a single argument - a function that
  8233. * will be called when the request succeeds or fails respectively. The arguments passed into
  8234. * these functions are destructured representation of the response object passed into the
  8235. * `then` method. The response object has these properties:
  8236. *
  8237. * - **data** – `{string|Object}` – The response body transformed with the transform
  8238. * functions.
  8239. * - **status** – `{number}` – HTTP status code of the response.
  8240. * - **headers** – `{function([headerName])}` – Header getter function.
  8241. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8242. * - **statusText** – `{string}` – HTTP status text of the response.
  8243. *
  8244. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8245. * requests. This is primarily meant to be used for debugging purposes.
  8246. *
  8247. *
  8248. * @example
  8249. <example module="httpExample">
  8250. <file name="index.html">
  8251. <div ng-controller="FetchController">
  8252. <select ng-model="method">
  8253. <option>GET</option>
  8254. <option>JSONP</option>
  8255. </select>
  8256. <input type="text" ng-model="url" size="80"/>
  8257. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8258. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8259. <button id="samplejsonpbtn"
  8260. ng-click="updateModel('JSONP',
  8261. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8262. Sample JSONP
  8263. </button>
  8264. <button id="invalidjsonpbtn"
  8265. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8266. Invalid JSONP
  8267. </button>
  8268. <pre>http status code: {{status}}</pre>
  8269. <pre>http response data: {{data}}</pre>
  8270. </div>
  8271. </file>
  8272. <file name="script.js">
  8273. angular.module('httpExample', [])
  8274. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8275. function($scope, $http, $templateCache) {
  8276. $scope.method = 'GET';
  8277. $scope.url = 'http-hello.html';
  8278. $scope.fetch = function() {
  8279. $scope.code = null;
  8280. $scope.response = null;
  8281. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8282. success(function(data, status) {
  8283. $scope.status = status;
  8284. $scope.data = data;
  8285. }).
  8286. error(function(data, status) {
  8287. $scope.data = data || "Request failed";
  8288. $scope.status = status;
  8289. });
  8290. };
  8291. $scope.updateModel = function(method, url) {
  8292. $scope.method = method;
  8293. $scope.url = url;
  8294. };
  8295. }]);
  8296. </file>
  8297. <file name="http-hello.html">
  8298. Hello, $http!
  8299. </file>
  8300. <file name="protractor.js" type="protractor">
  8301. var status = element(by.binding('status'));
  8302. var data = element(by.binding('data'));
  8303. var fetchBtn = element(by.id('fetchbtn'));
  8304. var sampleGetBtn = element(by.id('samplegetbtn'));
  8305. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8306. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8307. it('should make an xhr GET request', function() {
  8308. sampleGetBtn.click();
  8309. fetchBtn.click();
  8310. expect(status.getText()).toMatch('200');
  8311. expect(data.getText()).toMatch(/Hello, \$http!/);
  8312. });
  8313. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8314. // it('should make a JSONP request to angularjs.org', function() {
  8315. // sampleJsonpBtn.click();
  8316. // fetchBtn.click();
  8317. // expect(status.getText()).toMatch('200');
  8318. // expect(data.getText()).toMatch(/Super Hero!/);
  8319. // });
  8320. it('should make JSONP request to invalid URL and invoke the error handler',
  8321. function() {
  8322. invalidJsonpBtn.click();
  8323. fetchBtn.click();
  8324. expect(status.getText()).toMatch('0');
  8325. expect(data.getText()).toMatch('Request failed');
  8326. });
  8327. </file>
  8328. </example>
  8329. */
  8330. function $http(requestConfig) {
  8331. var config = {
  8332. method: 'get',
  8333. transformRequest: defaults.transformRequest,
  8334. transformResponse: defaults.transformResponse
  8335. };
  8336. var headers = mergeHeaders(requestConfig);
  8337. if (!angular.isObject(requestConfig)) {
  8338. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8339. }
  8340. extend(config, requestConfig);
  8341. config.headers = headers;
  8342. config.method = uppercase(config.method);
  8343. var serverRequest = function(config) {
  8344. headers = config.headers;
  8345. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  8346. // strip content-type if data is undefined
  8347. if (isUndefined(reqData)) {
  8348. forEach(headers, function(value, header) {
  8349. if (lowercase(header) === 'content-type') {
  8350. delete headers[header];
  8351. }
  8352. });
  8353. }
  8354. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8355. config.withCredentials = defaults.withCredentials;
  8356. }
  8357. // send request
  8358. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  8359. };
  8360. var chain = [serverRequest, undefined];
  8361. var promise = $q.when(config);
  8362. // apply interceptors
  8363. forEach(reversedInterceptors, function(interceptor) {
  8364. if (interceptor.request || interceptor.requestError) {
  8365. chain.unshift(interceptor.request, interceptor.requestError);
  8366. }
  8367. if (interceptor.response || interceptor.responseError) {
  8368. chain.push(interceptor.response, interceptor.responseError);
  8369. }
  8370. });
  8371. while (chain.length) {
  8372. var thenFn = chain.shift();
  8373. var rejectFn = chain.shift();
  8374. promise = promise.then(thenFn, rejectFn);
  8375. }
  8376. promise.success = function(fn) {
  8377. promise.then(function(response) {
  8378. fn(response.data, response.status, response.headers, config);
  8379. });
  8380. return promise;
  8381. };
  8382. promise.error = function(fn) {
  8383. promise.then(null, function(response) {
  8384. fn(response.data, response.status, response.headers, config);
  8385. });
  8386. return promise;
  8387. };
  8388. return promise;
  8389. function transformResponse(response) {
  8390. // make a copy since the response must be cacheable
  8391. var resp = extend({}, response);
  8392. if (!response.data) {
  8393. resp.data = response.data;
  8394. } else {
  8395. resp.data = transformData(response.data, response.headers, config.transformResponse);
  8396. }
  8397. return (isSuccess(response.status))
  8398. ? resp
  8399. : $q.reject(resp);
  8400. }
  8401. function mergeHeaders(config) {
  8402. var defHeaders = defaults.headers,
  8403. reqHeaders = extend({}, config.headers),
  8404. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8405. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8406. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8407. defaultHeadersIteration:
  8408. for (defHeaderName in defHeaders) {
  8409. lowercaseDefHeaderName = lowercase(defHeaderName);
  8410. for (reqHeaderName in reqHeaders) {
  8411. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8412. continue defaultHeadersIteration;
  8413. }
  8414. }
  8415. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8416. }
  8417. // execute if header value is a function for merged headers
  8418. execHeaders(reqHeaders);
  8419. return reqHeaders;
  8420. function execHeaders(headers) {
  8421. var headerContent;
  8422. forEach(headers, function(headerFn, header) {
  8423. if (isFunction(headerFn)) {
  8424. headerContent = headerFn();
  8425. if (headerContent != null) {
  8426. headers[header] = headerContent;
  8427. } else {
  8428. delete headers[header];
  8429. }
  8430. }
  8431. });
  8432. }
  8433. }
  8434. }
  8435. $http.pendingRequests = [];
  8436. /**
  8437. * @ngdoc method
  8438. * @name $http#get
  8439. *
  8440. * @description
  8441. * Shortcut method to perform `GET` request.
  8442. *
  8443. * @param {string} url Relative or absolute URL specifying the destination of the request
  8444. * @param {Object=} config Optional configuration object
  8445. * @returns {HttpPromise} Future object
  8446. */
  8447. /**
  8448. * @ngdoc method
  8449. * @name $http#delete
  8450. *
  8451. * @description
  8452. * Shortcut method to perform `DELETE` request.
  8453. *
  8454. * @param {string} url Relative or absolute URL specifying the destination of the request
  8455. * @param {Object=} config Optional configuration object
  8456. * @returns {HttpPromise} Future object
  8457. */
  8458. /**
  8459. * @ngdoc method
  8460. * @name $http#head
  8461. *
  8462. * @description
  8463. * Shortcut method to perform `HEAD` request.
  8464. *
  8465. * @param {string} url Relative or absolute URL specifying the destination of the request
  8466. * @param {Object=} config Optional configuration object
  8467. * @returns {HttpPromise} Future object
  8468. */
  8469. /**
  8470. * @ngdoc method
  8471. * @name $http#jsonp
  8472. *
  8473. * @description
  8474. * Shortcut method to perform `JSONP` request.
  8475. *
  8476. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8477. * The name of the callback should be the string `JSON_CALLBACK`.
  8478. * @param {Object=} config Optional configuration object
  8479. * @returns {HttpPromise} Future object
  8480. */
  8481. createShortMethods('get', 'delete', 'head', 'jsonp');
  8482. /**
  8483. * @ngdoc method
  8484. * @name $http#post
  8485. *
  8486. * @description
  8487. * Shortcut method to perform `POST` request.
  8488. *
  8489. * @param {string} url Relative or absolute URL specifying the destination of the request
  8490. * @param {*} data Request content
  8491. * @param {Object=} config Optional configuration object
  8492. * @returns {HttpPromise} Future object
  8493. */
  8494. /**
  8495. * @ngdoc method
  8496. * @name $http#put
  8497. *
  8498. * @description
  8499. * Shortcut method to perform `PUT` request.
  8500. *
  8501. * @param {string} url Relative or absolute URL specifying the destination of the request
  8502. * @param {*} data Request content
  8503. * @param {Object=} config Optional configuration object
  8504. * @returns {HttpPromise} Future object
  8505. */
  8506. /**
  8507. * @ngdoc method
  8508. * @name $http#patch
  8509. *
  8510. * @description
  8511. * Shortcut method to perform `PATCH` request.
  8512. *
  8513. * @param {string} url Relative or absolute URL specifying the destination of the request
  8514. * @param {*} data Request content
  8515. * @param {Object=} config Optional configuration object
  8516. * @returns {HttpPromise} Future object
  8517. */
  8518. createShortMethodsWithData('post', 'put', 'patch');
  8519. /**
  8520. * @ngdoc property
  8521. * @name $http#defaults
  8522. *
  8523. * @description
  8524. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8525. * default headers, withCredentials as well as request and response transformations.
  8526. *
  8527. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8528. */
  8529. $http.defaults = defaults;
  8530. return $http;
  8531. function createShortMethods(names) {
  8532. forEach(arguments, function(name) {
  8533. $http[name] = function(url, config) {
  8534. return $http(extend(config || {}, {
  8535. method: name,
  8536. url: url
  8537. }));
  8538. };
  8539. });
  8540. }
  8541. function createShortMethodsWithData(name) {
  8542. forEach(arguments, function(name) {
  8543. $http[name] = function(url, data, config) {
  8544. return $http(extend(config || {}, {
  8545. method: name,
  8546. url: url,
  8547. data: data
  8548. }));
  8549. };
  8550. });
  8551. }
  8552. /**
  8553. * Makes the request.
  8554. *
  8555. * !!! ACCESSES CLOSURE VARS:
  8556. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8557. */
  8558. function sendReq(config, reqData, reqHeaders) {
  8559. var deferred = $q.defer(),
  8560. promise = deferred.promise,
  8561. cache,
  8562. cachedResp,
  8563. url = buildUrl(config.url, config.params);
  8564. $http.pendingRequests.push(config);
  8565. promise.then(removePendingReq, removePendingReq);
  8566. if ((config.cache || defaults.cache) && config.cache !== false &&
  8567. (config.method === 'GET' || config.method === 'JSONP')) {
  8568. cache = isObject(config.cache) ? config.cache
  8569. : isObject(defaults.cache) ? defaults.cache
  8570. : defaultCache;
  8571. }
  8572. if (cache) {
  8573. cachedResp = cache.get(url);
  8574. if (isDefined(cachedResp)) {
  8575. if (isPromiseLike(cachedResp)) {
  8576. // cached request has already been sent, but there is no response yet
  8577. cachedResp.then(removePendingReq, removePendingReq);
  8578. return cachedResp;
  8579. } else {
  8580. // serving from cache
  8581. if (isArray(cachedResp)) {
  8582. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8583. } else {
  8584. resolvePromise(cachedResp, 200, {}, 'OK');
  8585. }
  8586. }
  8587. } else {
  8588. // put the promise for the non-transformed response into cache as a placeholder
  8589. cache.put(url, promise);
  8590. }
  8591. }
  8592. // if we won't have the response in cache, set the xsrf headers and
  8593. // send the request to the backend
  8594. if (isUndefined(cachedResp)) {
  8595. var xsrfValue = urlIsSameOrigin(config.url)
  8596. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8597. : undefined;
  8598. if (xsrfValue) {
  8599. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8600. }
  8601. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8602. config.withCredentials, config.responseType);
  8603. }
  8604. return promise;
  8605. /**
  8606. * Callback registered to $httpBackend():
  8607. * - caches the response if desired
  8608. * - resolves the raw $http promise
  8609. * - calls $apply
  8610. */
  8611. function done(status, response, headersString, statusText) {
  8612. if (cache) {
  8613. if (isSuccess(status)) {
  8614. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8615. } else {
  8616. // remove promise from the cache
  8617. cache.remove(url);
  8618. }
  8619. }
  8620. function resolveHttpPromise() {
  8621. resolvePromise(response, status, headersString, statusText);
  8622. }
  8623. if (useApplyAsync) {
  8624. $rootScope.$applyAsync(resolveHttpPromise);
  8625. } else {
  8626. resolveHttpPromise();
  8627. if (!$rootScope.$$phase) $rootScope.$apply();
  8628. }
  8629. }
  8630. /**
  8631. * Resolves the raw $http promise.
  8632. */
  8633. function resolvePromise(response, status, headers, statusText) {
  8634. // normalize internal statuses to 0
  8635. status = Math.max(status, 0);
  8636. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8637. data: response,
  8638. status: status,
  8639. headers: headersGetter(headers),
  8640. config: config,
  8641. statusText: statusText
  8642. });
  8643. }
  8644. function removePendingReq() {
  8645. var idx = $http.pendingRequests.indexOf(config);
  8646. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8647. }
  8648. }
  8649. function buildUrl(url, params) {
  8650. if (!params) return url;
  8651. var parts = [];
  8652. forEachSorted(params, function(value, key) {
  8653. if (value === null || isUndefined(value)) return;
  8654. if (!isArray(value)) value = [value];
  8655. forEach(value, function(v) {
  8656. if (isObject(v)) {
  8657. if (isDate(v)) {
  8658. v = v.toISOString();
  8659. } else {
  8660. v = toJson(v);
  8661. }
  8662. }
  8663. parts.push(encodeUriQuery(key) + '=' +
  8664. encodeUriQuery(v));
  8665. });
  8666. });
  8667. if (parts.length > 0) {
  8668. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8669. }
  8670. return url;
  8671. }
  8672. }];
  8673. }
  8674. function createXhr() {
  8675. return new window.XMLHttpRequest();
  8676. }
  8677. /**
  8678. * @ngdoc service
  8679. * @name $httpBackend
  8680. * @requires $window
  8681. * @requires $document
  8682. *
  8683. * @description
  8684. * HTTP backend used by the {@link ng.$http service} that delegates to
  8685. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8686. *
  8687. * You should never need to use this service directly, instead use the higher-level abstractions:
  8688. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8689. *
  8690. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8691. * $httpBackend} which can be trained with responses.
  8692. */
  8693. function $HttpBackendProvider() {
  8694. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8695. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8696. }];
  8697. }
  8698. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8699. // TODO(vojta): fix the signature
  8700. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8701. $browser.$$incOutstandingRequestCount();
  8702. url = url || $browser.url();
  8703. if (lowercase(method) == 'jsonp') {
  8704. var callbackId = '_' + (callbacks.counter++).toString(36);
  8705. callbacks[callbackId] = function(data) {
  8706. callbacks[callbackId].data = data;
  8707. callbacks[callbackId].called = true;
  8708. };
  8709. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8710. callbackId, function(status, text) {
  8711. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8712. callbacks[callbackId] = noop;
  8713. });
  8714. } else {
  8715. var xhr = createXhr();
  8716. xhr.open(method, url, true);
  8717. forEach(headers, function(value, key) {
  8718. if (isDefined(value)) {
  8719. xhr.setRequestHeader(key, value);
  8720. }
  8721. });
  8722. xhr.onload = function requestLoaded() {
  8723. var statusText = xhr.statusText || '';
  8724. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8725. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8726. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8727. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8728. var status = xhr.status === 1223 ? 204 : xhr.status;
  8729. // fix status code when it is 0 (0 status is undocumented).
  8730. // Occurs when accessing file resources or on Android 4.1 stock browser
  8731. // while retrieving files from application cache.
  8732. if (status === 0) {
  8733. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8734. }
  8735. completeRequest(callback,
  8736. status,
  8737. response,
  8738. xhr.getAllResponseHeaders(),
  8739. statusText);
  8740. };
  8741. var requestError = function() {
  8742. // The response is always empty
  8743. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8744. completeRequest(callback, -1, null, null, '');
  8745. };
  8746. xhr.onerror = requestError;
  8747. xhr.onabort = requestError;
  8748. if (withCredentials) {
  8749. xhr.withCredentials = true;
  8750. }
  8751. if (responseType) {
  8752. try {
  8753. xhr.responseType = responseType;
  8754. } catch (e) {
  8755. // WebKit added support for the json responseType value on 09/03/2013
  8756. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8757. // known to throw when setting the value "json" as the response type. Other older
  8758. // browsers implementing the responseType
  8759. //
  8760. // The json response type can be ignored if not supported, because JSON payloads are
  8761. // parsed on the client-side regardless.
  8762. if (responseType !== 'json') {
  8763. throw e;
  8764. }
  8765. }
  8766. }
  8767. xhr.send(post || null);
  8768. }
  8769. if (timeout > 0) {
  8770. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8771. } else if (isPromiseLike(timeout)) {
  8772. timeout.then(timeoutRequest);
  8773. }
  8774. function timeoutRequest() {
  8775. jsonpDone && jsonpDone();
  8776. xhr && xhr.abort();
  8777. }
  8778. function completeRequest(callback, status, response, headersString, statusText) {
  8779. // cancel timeout and subsequent timeout promise resolution
  8780. timeoutId && $browserDefer.cancel(timeoutId);
  8781. jsonpDone = xhr = null;
  8782. callback(status, response, headersString, statusText);
  8783. $browser.$$completeOutstandingRequest(noop);
  8784. }
  8785. };
  8786. function jsonpReq(url, callbackId, done) {
  8787. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8788. // - fetches local scripts via XHR and evals them
  8789. // - adds and immediately removes script elements from the document
  8790. var script = rawDocument.createElement('script'), callback = null;
  8791. script.type = "text/javascript";
  8792. script.src = url;
  8793. script.async = true;
  8794. callback = function(event) {
  8795. removeEventListenerFn(script, "load", callback);
  8796. removeEventListenerFn(script, "error", callback);
  8797. rawDocument.body.removeChild(script);
  8798. script = null;
  8799. var status = -1;
  8800. var text = "unknown";
  8801. if (event) {
  8802. if (event.type === "load" && !callbacks[callbackId].called) {
  8803. event = { type: "error" };
  8804. }
  8805. text = event.type;
  8806. status = event.type === "error" ? 404 : 200;
  8807. }
  8808. if (done) {
  8809. done(status, text);
  8810. }
  8811. };
  8812. addEventListenerFn(script, "load", callback);
  8813. addEventListenerFn(script, "error", callback);
  8814. rawDocument.body.appendChild(script);
  8815. return callback;
  8816. }
  8817. }
  8818. var $interpolateMinErr = minErr('$interpolate');
  8819. /**
  8820. * @ngdoc provider
  8821. * @name $interpolateProvider
  8822. *
  8823. * @description
  8824. *
  8825. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8826. *
  8827. * @example
  8828. <example module="customInterpolationApp">
  8829. <file name="index.html">
  8830. <script>
  8831. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8832. customInterpolationApp.config(function($interpolateProvider) {
  8833. $interpolateProvider.startSymbol('//');
  8834. $interpolateProvider.endSymbol('//');
  8835. });
  8836. customInterpolationApp.controller('DemoController', function() {
  8837. this.label = "This binding is brought you by // interpolation symbols.";
  8838. });
  8839. </script>
  8840. <div ng-app="App" ng-controller="DemoController as demo">
  8841. //demo.label//
  8842. </div>
  8843. </file>
  8844. <file name="protractor.js" type="protractor">
  8845. it('should interpolate binding with custom symbols', function() {
  8846. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8847. });
  8848. </file>
  8849. </example>
  8850. */
  8851. function $InterpolateProvider() {
  8852. var startSymbol = '{{';
  8853. var endSymbol = '}}';
  8854. /**
  8855. * @ngdoc method
  8856. * @name $interpolateProvider#startSymbol
  8857. * @description
  8858. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8859. *
  8860. * @param {string=} value new value to set the starting symbol to.
  8861. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8862. */
  8863. this.startSymbol = function(value) {
  8864. if (value) {
  8865. startSymbol = value;
  8866. return this;
  8867. } else {
  8868. return startSymbol;
  8869. }
  8870. };
  8871. /**
  8872. * @ngdoc method
  8873. * @name $interpolateProvider#endSymbol
  8874. * @description
  8875. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8876. *
  8877. * @param {string=} value new value to set the ending symbol to.
  8878. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8879. */
  8880. this.endSymbol = function(value) {
  8881. if (value) {
  8882. endSymbol = value;
  8883. return this;
  8884. } else {
  8885. return endSymbol;
  8886. }
  8887. };
  8888. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  8889. var startSymbolLength = startSymbol.length,
  8890. endSymbolLength = endSymbol.length,
  8891. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  8892. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  8893. function escape(ch) {
  8894. return '\\\\\\' + ch;
  8895. }
  8896. /**
  8897. * @ngdoc service
  8898. * @name $interpolate
  8899. * @kind function
  8900. *
  8901. * @requires $parse
  8902. * @requires $sce
  8903. *
  8904. * @description
  8905. *
  8906. * Compiles a string with markup into an interpolation function. This service is used by the
  8907. * HTML {@link ng.$compile $compile} service for data binding. See
  8908. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  8909. * interpolation markup.
  8910. *
  8911. *
  8912. * ```js
  8913. * var $interpolate = ...; // injected
  8914. * var exp = $interpolate('Hello {{name | uppercase}}!');
  8915. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  8916. * ```
  8917. *
  8918. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  8919. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  8920. * evaluate to a value other than `undefined`.
  8921. *
  8922. * ```js
  8923. * var $interpolate = ...; // injected
  8924. * var context = {greeting: 'Hello', name: undefined };
  8925. *
  8926. * // default "forgiving" mode
  8927. * var exp = $interpolate('{{greeting}} {{name}}!');
  8928. * expect(exp(context)).toEqual('Hello !');
  8929. *
  8930. * // "allOrNothing" mode
  8931. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  8932. * expect(exp(context)).toBeUndefined();
  8933. * context.name = 'Angular';
  8934. * expect(exp(context)).toEqual('Hello Angular!');
  8935. * ```
  8936. *
  8937. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  8938. *
  8939. * ####Escaped Interpolation
  8940. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  8941. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  8942. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  8943. * or binding.
  8944. *
  8945. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  8946. * degree, while also enabling code examples to work without relying on the
  8947. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  8948. *
  8949. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  8950. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  8951. * interpolation start/end markers with their escaped counterparts.**
  8952. *
  8953. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  8954. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  8955. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  8956. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  8957. * this is typically useful only when user-data is used in rendering a template from the server, or
  8958. * when otherwise untrusted data is used by a directive.
  8959. *
  8960. * <example>
  8961. * <file name="index.html">
  8962. * <div ng-init="username='A user'">
  8963. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  8964. * </p>
  8965. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  8966. * application, but fails to accomplish their task, because the server has correctly
  8967. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  8968. * characters.</p>
  8969. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  8970. * from the database by an administrator.</p>
  8971. * </div>
  8972. * </file>
  8973. * </example>
  8974. *
  8975. * @param {string} text The text with markup to interpolate.
  8976. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  8977. * embedded expression in order to return an interpolation function. Strings with no
  8978. * embedded expression will return null for the interpolation function.
  8979. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  8980. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  8981. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  8982. * provides Strict Contextual Escaping for details.
  8983. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  8984. * unless all embedded expressions evaluate to a value other than `undefined`.
  8985. * @returns {function(context)} an interpolation function which is used to compute the
  8986. * interpolated string. The function has these parameters:
  8987. *
  8988. * - `context`: evaluation context for all expressions embedded in the interpolated text
  8989. */
  8990. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  8991. allOrNothing = !!allOrNothing;
  8992. var startIndex,
  8993. endIndex,
  8994. index = 0,
  8995. expressions = [],
  8996. parseFns = [],
  8997. textLength = text.length,
  8998. exp,
  8999. concat = [],
  9000. expressionPositions = [];
  9001. while (index < textLength) {
  9002. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9003. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9004. if (index !== startIndex) {
  9005. concat.push(unescapeText(text.substring(index, startIndex)));
  9006. }
  9007. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9008. expressions.push(exp);
  9009. parseFns.push($parse(exp, parseStringifyInterceptor));
  9010. index = endIndex + endSymbolLength;
  9011. expressionPositions.push(concat.length);
  9012. concat.push('');
  9013. } else {
  9014. // we did not find an interpolation, so we have to add the remainder to the separators array
  9015. if (index !== textLength) {
  9016. concat.push(unescapeText(text.substring(index)));
  9017. }
  9018. break;
  9019. }
  9020. }
  9021. // Concatenating expressions makes it hard to reason about whether some combination of
  9022. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9023. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9024. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9025. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9026. // the load when auditing for XSS issues.
  9027. if (trustedContext && concat.length > 1) {
  9028. throw $interpolateMinErr('noconcat',
  9029. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9030. "interpolations that concatenate multiple expressions when a trusted value is " +
  9031. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9032. }
  9033. if (!mustHaveExpression || expressions.length) {
  9034. var compute = function(values) {
  9035. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9036. if (allOrNothing && isUndefined(values[i])) return;
  9037. concat[expressionPositions[i]] = values[i];
  9038. }
  9039. return concat.join('');
  9040. };
  9041. var getValue = function(value) {
  9042. return trustedContext ?
  9043. $sce.getTrusted(trustedContext, value) :
  9044. $sce.valueOf(value);
  9045. };
  9046. var stringify = function(value) {
  9047. if (value == null) { // null || undefined
  9048. return '';
  9049. }
  9050. switch (typeof value) {
  9051. case 'string':
  9052. break;
  9053. case 'number':
  9054. value = '' + value;
  9055. break;
  9056. default:
  9057. value = toJson(value);
  9058. }
  9059. return value;
  9060. };
  9061. return extend(function interpolationFn(context) {
  9062. var i = 0;
  9063. var ii = expressions.length;
  9064. var values = new Array(ii);
  9065. try {
  9066. for (; i < ii; i++) {
  9067. values[i] = parseFns[i](context);
  9068. }
  9069. return compute(values);
  9070. } catch (err) {
  9071. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9072. err.toString());
  9073. $exceptionHandler(newErr);
  9074. }
  9075. }, {
  9076. // all of these properties are undocumented for now
  9077. exp: text, //just for compatibility with regular watchers created via $watch
  9078. expressions: expressions,
  9079. $$watchDelegate: function(scope, listener, objectEquality) {
  9080. var lastValue;
  9081. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9082. var currValue = compute(values);
  9083. if (isFunction(listener)) {
  9084. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9085. }
  9086. lastValue = currValue;
  9087. }, objectEquality);
  9088. }
  9089. });
  9090. }
  9091. function unescapeText(text) {
  9092. return text.replace(escapedStartRegexp, startSymbol).
  9093. replace(escapedEndRegexp, endSymbol);
  9094. }
  9095. function parseStringifyInterceptor(value) {
  9096. try {
  9097. value = getValue(value);
  9098. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9099. } catch (err) {
  9100. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9101. err.toString());
  9102. $exceptionHandler(newErr);
  9103. }
  9104. }
  9105. }
  9106. /**
  9107. * @ngdoc method
  9108. * @name $interpolate#startSymbol
  9109. * @description
  9110. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9111. *
  9112. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9113. * the symbol.
  9114. *
  9115. * @returns {string} start symbol.
  9116. */
  9117. $interpolate.startSymbol = function() {
  9118. return startSymbol;
  9119. };
  9120. /**
  9121. * @ngdoc method
  9122. * @name $interpolate#endSymbol
  9123. * @description
  9124. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9125. *
  9126. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9127. * the symbol.
  9128. *
  9129. * @returns {string} end symbol.
  9130. */
  9131. $interpolate.endSymbol = function() {
  9132. return endSymbol;
  9133. };
  9134. return $interpolate;
  9135. }];
  9136. }
  9137. function $IntervalProvider() {
  9138. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9139. function($rootScope, $window, $q, $$q) {
  9140. var intervals = {};
  9141. /**
  9142. * @ngdoc service
  9143. * @name $interval
  9144. *
  9145. * @description
  9146. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9147. * milliseconds.
  9148. *
  9149. * The return value of registering an interval function is a promise. This promise will be
  9150. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9151. * run indefinitely if `count` is not defined. The value of the notification will be the
  9152. * number of iterations that have run.
  9153. * To cancel an interval, call `$interval.cancel(promise)`.
  9154. *
  9155. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9156. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9157. * time.
  9158. *
  9159. * <div class="alert alert-warning">
  9160. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9161. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9162. * directive's element are destroyed.
  9163. * You should take this into consideration and make sure to always cancel the interval at the
  9164. * appropriate moment. See the example below for more details on how and when to do this.
  9165. * </div>
  9166. *
  9167. * @param {function()} fn A function that should be called repeatedly.
  9168. * @param {number} delay Number of milliseconds between each function call.
  9169. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9170. * indefinitely.
  9171. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9172. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9173. * @returns {promise} A promise which will be notified on each iteration.
  9174. *
  9175. * @example
  9176. * <example module="intervalExample">
  9177. * <file name="index.html">
  9178. * <script>
  9179. * angular.module('intervalExample', [])
  9180. * .controller('ExampleController', ['$scope', '$interval',
  9181. * function($scope, $interval) {
  9182. * $scope.format = 'M/d/yy h:mm:ss a';
  9183. * $scope.blood_1 = 100;
  9184. * $scope.blood_2 = 120;
  9185. *
  9186. * var stop;
  9187. * $scope.fight = function() {
  9188. * // Don't start a new fight if we are already fighting
  9189. * if ( angular.isDefined(stop) ) return;
  9190. *
  9191. * stop = $interval(function() {
  9192. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9193. * $scope.blood_1 = $scope.blood_1 - 3;
  9194. * $scope.blood_2 = $scope.blood_2 - 4;
  9195. * } else {
  9196. * $scope.stopFight();
  9197. * }
  9198. * }, 100);
  9199. * };
  9200. *
  9201. * $scope.stopFight = function() {
  9202. * if (angular.isDefined(stop)) {
  9203. * $interval.cancel(stop);
  9204. * stop = undefined;
  9205. * }
  9206. * };
  9207. *
  9208. * $scope.resetFight = function() {
  9209. * $scope.blood_1 = 100;
  9210. * $scope.blood_2 = 120;
  9211. * };
  9212. *
  9213. * $scope.$on('$destroy', function() {
  9214. * // Make sure that the interval is destroyed too
  9215. * $scope.stopFight();
  9216. * });
  9217. * }])
  9218. * // Register the 'myCurrentTime' directive factory method.
  9219. * // We inject $interval and dateFilter service since the factory method is DI.
  9220. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9221. * function($interval, dateFilter) {
  9222. * // return the directive link function. (compile function not needed)
  9223. * return function(scope, element, attrs) {
  9224. * var format, // date format
  9225. * stopTime; // so that we can cancel the time updates
  9226. *
  9227. * // used to update the UI
  9228. * function updateTime() {
  9229. * element.text(dateFilter(new Date(), format));
  9230. * }
  9231. *
  9232. * // watch the expression, and update the UI on change.
  9233. * scope.$watch(attrs.myCurrentTime, function(value) {
  9234. * format = value;
  9235. * updateTime();
  9236. * });
  9237. *
  9238. * stopTime = $interval(updateTime, 1000);
  9239. *
  9240. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9241. * // to prevent updating time after the DOM element was removed.
  9242. * element.on('$destroy', function() {
  9243. * $interval.cancel(stopTime);
  9244. * });
  9245. * }
  9246. * }]);
  9247. * </script>
  9248. *
  9249. * <div>
  9250. * <div ng-controller="ExampleController">
  9251. * Date format: <input ng-model="format"> <hr/>
  9252. * Current time is: <span my-current-time="format"></span>
  9253. * <hr/>
  9254. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9255. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9256. * <button type="button" data-ng-click="fight()">Fight</button>
  9257. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9258. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9259. * </div>
  9260. * </div>
  9261. *
  9262. * </file>
  9263. * </example>
  9264. */
  9265. function interval(fn, delay, count, invokeApply) {
  9266. var setInterval = $window.setInterval,
  9267. clearInterval = $window.clearInterval,
  9268. iteration = 0,
  9269. skipApply = (isDefined(invokeApply) && !invokeApply),
  9270. deferred = (skipApply ? $$q : $q).defer(),
  9271. promise = deferred.promise;
  9272. count = isDefined(count) ? count : 0;
  9273. promise.then(null, null, fn);
  9274. promise.$$intervalId = setInterval(function tick() {
  9275. deferred.notify(iteration++);
  9276. if (count > 0 && iteration >= count) {
  9277. deferred.resolve(iteration);
  9278. clearInterval(promise.$$intervalId);
  9279. delete intervals[promise.$$intervalId];
  9280. }
  9281. if (!skipApply) $rootScope.$apply();
  9282. }, delay);
  9283. intervals[promise.$$intervalId] = deferred;
  9284. return promise;
  9285. }
  9286. /**
  9287. * @ngdoc method
  9288. * @name $interval#cancel
  9289. *
  9290. * @description
  9291. * Cancels a task associated with the `promise`.
  9292. *
  9293. * @param {promise} promise returned by the `$interval` function.
  9294. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9295. */
  9296. interval.cancel = function(promise) {
  9297. if (promise && promise.$$intervalId in intervals) {
  9298. intervals[promise.$$intervalId].reject('canceled');
  9299. $window.clearInterval(promise.$$intervalId);
  9300. delete intervals[promise.$$intervalId];
  9301. return true;
  9302. }
  9303. return false;
  9304. };
  9305. return interval;
  9306. }];
  9307. }
  9308. /**
  9309. * @ngdoc service
  9310. * @name $locale
  9311. *
  9312. * @description
  9313. * $locale service provides localization rules for various Angular components. As of right now the
  9314. * only public api is:
  9315. *
  9316. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9317. */
  9318. function $LocaleProvider() {
  9319. this.$get = function() {
  9320. return {
  9321. id: 'en-us',
  9322. NUMBER_FORMATS: {
  9323. DECIMAL_SEP: '.',
  9324. GROUP_SEP: ',',
  9325. PATTERNS: [
  9326. { // Decimal Pattern
  9327. minInt: 1,
  9328. minFrac: 0,
  9329. maxFrac: 3,
  9330. posPre: '',
  9331. posSuf: '',
  9332. negPre: '-',
  9333. negSuf: '',
  9334. gSize: 3,
  9335. lgSize: 3
  9336. },{ //Currency Pattern
  9337. minInt: 1,
  9338. minFrac: 2,
  9339. maxFrac: 2,
  9340. posPre: '\u00A4',
  9341. posSuf: '',
  9342. negPre: '(\u00A4',
  9343. negSuf: ')',
  9344. gSize: 3,
  9345. lgSize: 3
  9346. }
  9347. ],
  9348. CURRENCY_SYM: '$'
  9349. },
  9350. DATETIME_FORMATS: {
  9351. MONTH:
  9352. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9353. .split(','),
  9354. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9355. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9356. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9357. AMPMS: ['AM','PM'],
  9358. medium: 'MMM d, y h:mm:ss a',
  9359. 'short': 'M/d/yy h:mm a',
  9360. fullDate: 'EEEE, MMMM d, y',
  9361. longDate: 'MMMM d, y',
  9362. mediumDate: 'MMM d, y',
  9363. shortDate: 'M/d/yy',
  9364. mediumTime: 'h:mm:ss a',
  9365. shortTime: 'h:mm a'
  9366. },
  9367. pluralCat: function(num) {
  9368. if (num === 1) {
  9369. return 'one';
  9370. }
  9371. return 'other';
  9372. }
  9373. };
  9374. };
  9375. }
  9376. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9377. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9378. var $locationMinErr = minErr('$location');
  9379. /**
  9380. * Encode path using encodeUriSegment, ignoring forward slashes
  9381. *
  9382. * @param {string} path Path to encode
  9383. * @returns {string}
  9384. */
  9385. function encodePath(path) {
  9386. var segments = path.split('/'),
  9387. i = segments.length;
  9388. while (i--) {
  9389. segments[i] = encodeUriSegment(segments[i]);
  9390. }
  9391. return segments.join('/');
  9392. }
  9393. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  9394. var parsedUrl = urlResolve(absoluteUrl);
  9395. locationObj.$$protocol = parsedUrl.protocol;
  9396. locationObj.$$host = parsedUrl.hostname;
  9397. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9398. }
  9399. function parseAppUrl(relativeUrl, locationObj) {
  9400. var prefixed = (relativeUrl.charAt(0) !== '/');
  9401. if (prefixed) {
  9402. relativeUrl = '/' + relativeUrl;
  9403. }
  9404. var match = urlResolve(relativeUrl);
  9405. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9406. match.pathname.substring(1) : match.pathname);
  9407. locationObj.$$search = parseKeyValue(match.search);
  9408. locationObj.$$hash = decodeURIComponent(match.hash);
  9409. // make sure path starts with '/';
  9410. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9411. locationObj.$$path = '/' + locationObj.$$path;
  9412. }
  9413. }
  9414. /**
  9415. *
  9416. * @param {string} begin
  9417. * @param {string} whole
  9418. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9419. * expected string.
  9420. */
  9421. function beginsWith(begin, whole) {
  9422. if (whole.indexOf(begin) === 0) {
  9423. return whole.substr(begin.length);
  9424. }
  9425. }
  9426. function stripHash(url) {
  9427. var index = url.indexOf('#');
  9428. return index == -1 ? url : url.substr(0, index);
  9429. }
  9430. function stripFile(url) {
  9431. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9432. }
  9433. /* return the server only (scheme://host:port) */
  9434. function serverBase(url) {
  9435. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9436. }
  9437. /**
  9438. * LocationHtml5Url represents an url
  9439. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9440. *
  9441. * @constructor
  9442. * @param {string} appBase application base URL
  9443. * @param {string} basePrefix url path prefix
  9444. */
  9445. function LocationHtml5Url(appBase, basePrefix) {
  9446. this.$$html5 = true;
  9447. basePrefix = basePrefix || '';
  9448. var appBaseNoFile = stripFile(appBase);
  9449. parseAbsoluteUrl(appBase, this);
  9450. /**
  9451. * Parse given html5 (regular) url string into properties
  9452. * @param {string} url HTML5 url
  9453. * @private
  9454. */
  9455. this.$$parse = function(url) {
  9456. var pathUrl = beginsWith(appBaseNoFile, url);
  9457. if (!isString(pathUrl)) {
  9458. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9459. appBaseNoFile);
  9460. }
  9461. parseAppUrl(pathUrl, this);
  9462. if (!this.$$path) {
  9463. this.$$path = '/';
  9464. }
  9465. this.$$compose();
  9466. };
  9467. /**
  9468. * Compose url and update `absUrl` property
  9469. * @private
  9470. */
  9471. this.$$compose = function() {
  9472. var search = toKeyValue(this.$$search),
  9473. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9474. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9475. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9476. };
  9477. this.$$parseLinkUrl = function(url, relHref) {
  9478. if (relHref && relHref[0] === '#') {
  9479. // special case for links to hash fragments:
  9480. // keep the old url and only replace the hash fragment
  9481. this.hash(relHref.slice(1));
  9482. return true;
  9483. }
  9484. var appUrl, prevAppUrl;
  9485. var rewrittenUrl;
  9486. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9487. prevAppUrl = appUrl;
  9488. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9489. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9490. } else {
  9491. rewrittenUrl = appBase + prevAppUrl;
  9492. }
  9493. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9494. rewrittenUrl = appBaseNoFile + appUrl;
  9495. } else if (appBaseNoFile == url + '/') {
  9496. rewrittenUrl = appBaseNoFile;
  9497. }
  9498. if (rewrittenUrl) {
  9499. this.$$parse(rewrittenUrl);
  9500. }
  9501. return !!rewrittenUrl;
  9502. };
  9503. }
  9504. /**
  9505. * LocationHashbangUrl represents url
  9506. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9507. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9508. *
  9509. * @constructor
  9510. * @param {string} appBase application base URL
  9511. * @param {string} hashPrefix hashbang prefix
  9512. */
  9513. function LocationHashbangUrl(appBase, hashPrefix) {
  9514. var appBaseNoFile = stripFile(appBase);
  9515. parseAbsoluteUrl(appBase, this);
  9516. /**
  9517. * Parse given hashbang url into properties
  9518. * @param {string} url Hashbang url
  9519. * @private
  9520. */
  9521. this.$$parse = function(url) {
  9522. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9523. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  9524. ? beginsWith(hashPrefix, withoutBaseUrl)
  9525. : (this.$$html5)
  9526. ? withoutBaseUrl
  9527. : '';
  9528. if (!isString(withoutHashUrl)) {
  9529. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  9530. hashPrefix);
  9531. }
  9532. parseAppUrl(withoutHashUrl, this);
  9533. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9534. this.$$compose();
  9535. /*
  9536. * In Windows, on an anchor node on documents loaded from
  9537. * the filesystem, the browser will return a pathname
  9538. * prefixed with the drive name ('/C:/path') when a
  9539. * pathname without a drive is set:
  9540. * * a.setAttribute('href', '/foo')
  9541. * * a.pathname === '/C:/foo' //true
  9542. *
  9543. * Inside of Angular, we're always using pathnames that
  9544. * do not include drive names for routing.
  9545. */
  9546. function removeWindowsDriveName(path, url, base) {
  9547. /*
  9548. Matches paths for file protocol on windows,
  9549. such as /C:/foo/bar, and captures only /foo/bar.
  9550. */
  9551. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9552. var firstPathSegmentMatch;
  9553. //Get the relative path from the input URL.
  9554. if (url.indexOf(base) === 0) {
  9555. url = url.replace(base, '');
  9556. }
  9557. // The input URL intentionally contains a first path segment that ends with a colon.
  9558. if (windowsFilePathExp.exec(url)) {
  9559. return path;
  9560. }
  9561. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9562. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9563. }
  9564. };
  9565. /**
  9566. * Compose hashbang url and update `absUrl` property
  9567. * @private
  9568. */
  9569. this.$$compose = function() {
  9570. var search = toKeyValue(this.$$search),
  9571. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9572. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9573. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9574. };
  9575. this.$$parseLinkUrl = function(url, relHref) {
  9576. if (stripHash(appBase) == stripHash(url)) {
  9577. this.$$parse(url);
  9578. return true;
  9579. }
  9580. return false;
  9581. };
  9582. }
  9583. /**
  9584. * LocationHashbangUrl represents url
  9585. * This object is exposed as $location service when html5 history api is enabled but the browser
  9586. * does not support it.
  9587. *
  9588. * @constructor
  9589. * @param {string} appBase application base URL
  9590. * @param {string} hashPrefix hashbang prefix
  9591. */
  9592. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9593. this.$$html5 = true;
  9594. LocationHashbangUrl.apply(this, arguments);
  9595. var appBaseNoFile = stripFile(appBase);
  9596. this.$$parseLinkUrl = function(url, relHref) {
  9597. if (relHref && relHref[0] === '#') {
  9598. // special case for links to hash fragments:
  9599. // keep the old url and only replace the hash fragment
  9600. this.hash(relHref.slice(1));
  9601. return true;
  9602. }
  9603. var rewrittenUrl;
  9604. var appUrl;
  9605. if (appBase == stripHash(url)) {
  9606. rewrittenUrl = url;
  9607. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9608. rewrittenUrl = appBase + hashPrefix + appUrl;
  9609. } else if (appBaseNoFile === url + '/') {
  9610. rewrittenUrl = appBaseNoFile;
  9611. }
  9612. if (rewrittenUrl) {
  9613. this.$$parse(rewrittenUrl);
  9614. }
  9615. return !!rewrittenUrl;
  9616. };
  9617. this.$$compose = function() {
  9618. var search = toKeyValue(this.$$search),
  9619. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9620. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9621. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9622. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9623. };
  9624. }
  9625. var locationPrototype = {
  9626. /**
  9627. * Are we in html5 mode?
  9628. * @private
  9629. */
  9630. $$html5: false,
  9631. /**
  9632. * Has any change been replacing?
  9633. * @private
  9634. */
  9635. $$replace: false,
  9636. /**
  9637. * @ngdoc method
  9638. * @name $location#absUrl
  9639. *
  9640. * @description
  9641. * This method is getter only.
  9642. *
  9643. * Return full url representation with all segments encoded according to rules specified in
  9644. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9645. *
  9646. *
  9647. * ```js
  9648. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9649. * var absUrl = $location.absUrl();
  9650. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  9651. * ```
  9652. *
  9653. * @return {string} full url
  9654. */
  9655. absUrl: locationGetter('$$absUrl'),
  9656. /**
  9657. * @ngdoc method
  9658. * @name $location#url
  9659. *
  9660. * @description
  9661. * This method is getter / setter.
  9662. *
  9663. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9664. *
  9665. * Change path, search and hash, when called with parameter and return `$location`.
  9666. *
  9667. *
  9668. * ```js
  9669. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9670. * var url = $location.url();
  9671. * // => "/some/path?foo=bar&baz=xoxo"
  9672. * ```
  9673. *
  9674. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9675. * @return {string} url
  9676. */
  9677. url: function(url) {
  9678. if (isUndefined(url))
  9679. return this.$$url;
  9680. var match = PATH_MATCH.exec(url);
  9681. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  9682. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  9683. this.hash(match[5] || '');
  9684. return this;
  9685. },
  9686. /**
  9687. * @ngdoc method
  9688. * @name $location#protocol
  9689. *
  9690. * @description
  9691. * This method is getter only.
  9692. *
  9693. * Return protocol of current url.
  9694. *
  9695. *
  9696. * ```js
  9697. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9698. * var protocol = $location.protocol();
  9699. * // => "http"
  9700. * ```
  9701. *
  9702. * @return {string} protocol of current url
  9703. */
  9704. protocol: locationGetter('$$protocol'),
  9705. /**
  9706. * @ngdoc method
  9707. * @name $location#host
  9708. *
  9709. * @description
  9710. * This method is getter only.
  9711. *
  9712. * Return host of current url.
  9713. *
  9714. *
  9715. * ```js
  9716. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9717. * var host = $location.host();
  9718. * // => "example.com"
  9719. * ```
  9720. *
  9721. * @return {string} host of current url.
  9722. */
  9723. host: locationGetter('$$host'),
  9724. /**
  9725. * @ngdoc method
  9726. * @name $location#port
  9727. *
  9728. * @description
  9729. * This method is getter only.
  9730. *
  9731. * Return port of current url.
  9732. *
  9733. *
  9734. * ```js
  9735. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9736. * var port = $location.port();
  9737. * // => 80
  9738. * ```
  9739. *
  9740. * @return {Number} port
  9741. */
  9742. port: locationGetter('$$port'),
  9743. /**
  9744. * @ngdoc method
  9745. * @name $location#path
  9746. *
  9747. * @description
  9748. * This method is getter / setter.
  9749. *
  9750. * Return path of current url when called without any parameter.
  9751. *
  9752. * Change path when called with parameter and return `$location`.
  9753. *
  9754. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9755. * if it is missing.
  9756. *
  9757. *
  9758. * ```js
  9759. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9760. * var path = $location.path();
  9761. * // => "/some/path"
  9762. * ```
  9763. *
  9764. * @param {(string|number)=} path New path
  9765. * @return {string} path
  9766. */
  9767. path: locationGetterSetter('$$path', function(path) {
  9768. path = path !== null ? path.toString() : '';
  9769. return path.charAt(0) == '/' ? path : '/' + path;
  9770. }),
  9771. /**
  9772. * @ngdoc method
  9773. * @name $location#search
  9774. *
  9775. * @description
  9776. * This method is getter / setter.
  9777. *
  9778. * Return search part (as object) of current url when called without any parameter.
  9779. *
  9780. * Change search part when called with parameter and return `$location`.
  9781. *
  9782. *
  9783. * ```js
  9784. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9785. * var searchObject = $location.search();
  9786. * // => {foo: 'bar', baz: 'xoxo'}
  9787. *
  9788. * // set foo to 'yipee'
  9789. * $location.search('foo', 'yipee');
  9790. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  9791. * ```
  9792. *
  9793. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9794. * hash object.
  9795. *
  9796. * When called with a single argument the method acts as a setter, setting the `search` component
  9797. * of `$location` to the specified value.
  9798. *
  9799. * If the argument is a hash object containing an array of values, these values will be encoded
  9800. * as duplicate search parameters in the url.
  9801. *
  9802. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9803. * will override only a single search property.
  9804. *
  9805. * If `paramValue` is an array, it will override the property of the `search` component of
  9806. * `$location` specified via the first argument.
  9807. *
  9808. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9809. *
  9810. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9811. * value nor trailing equal sign.
  9812. *
  9813. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9814. * one or more arguments returns `$location` object itself.
  9815. */
  9816. search: function(search, paramValue) {
  9817. switch (arguments.length) {
  9818. case 0:
  9819. return this.$$search;
  9820. case 1:
  9821. if (isString(search) || isNumber(search)) {
  9822. search = search.toString();
  9823. this.$$search = parseKeyValue(search);
  9824. } else if (isObject(search)) {
  9825. search = copy(search, {});
  9826. // remove object undefined or null properties
  9827. forEach(search, function(value, key) {
  9828. if (value == null) delete search[key];
  9829. });
  9830. this.$$search = search;
  9831. } else {
  9832. throw $locationMinErr('isrcharg',
  9833. 'The first argument of the `$location#search()` call must be a string or an object.');
  9834. }
  9835. break;
  9836. default:
  9837. if (isUndefined(paramValue) || paramValue === null) {
  9838. delete this.$$search[search];
  9839. } else {
  9840. this.$$search[search] = paramValue;
  9841. }
  9842. }
  9843. this.$$compose();
  9844. return this;
  9845. },
  9846. /**
  9847. * @ngdoc method
  9848. * @name $location#hash
  9849. *
  9850. * @description
  9851. * This method is getter / setter.
  9852. *
  9853. * Return hash fragment when called without any parameter.
  9854. *
  9855. * Change hash fragment when called with parameter and return `$location`.
  9856. *
  9857. *
  9858. * ```js
  9859. * // given url http://example.com/some/path?foo=bar&baz=xoxo#hashValue
  9860. * var hash = $location.hash();
  9861. * // => "hashValue"
  9862. * ```
  9863. *
  9864. * @param {(string|number)=} hash New hash fragment
  9865. * @return {string} hash
  9866. */
  9867. hash: locationGetterSetter('$$hash', function(hash) {
  9868. return hash !== null ? hash.toString() : '';
  9869. }),
  9870. /**
  9871. * @ngdoc method
  9872. * @name $location#replace
  9873. *
  9874. * @description
  9875. * If called, all changes to $location during current `$digest` will be replacing current history
  9876. * record, instead of adding new one.
  9877. */
  9878. replace: function() {
  9879. this.$$replace = true;
  9880. return this;
  9881. }
  9882. };
  9883. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  9884. Location.prototype = Object.create(locationPrototype);
  9885. /**
  9886. * @ngdoc method
  9887. * @name $location#state
  9888. *
  9889. * @description
  9890. * This method is getter / setter.
  9891. *
  9892. * Return the history state object when called without any parameter.
  9893. *
  9894. * Change the history state object when called with one parameter and return `$location`.
  9895. * The state object is later passed to `pushState` or `replaceState`.
  9896. *
  9897. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  9898. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  9899. * older browsers (like IE9 or Android < 4.0), don't use this method.
  9900. *
  9901. * @param {object=} state State object for pushState or replaceState
  9902. * @return {object} state
  9903. */
  9904. Location.prototype.state = function(state) {
  9905. if (!arguments.length)
  9906. return this.$$state;
  9907. if (Location !== LocationHtml5Url || !this.$$html5) {
  9908. throw $locationMinErr('nostate', 'History API state support is available only ' +
  9909. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  9910. }
  9911. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  9912. // but we're changing the $$state reference to $browser.state() during the $digest
  9913. // so the modification window is narrow.
  9914. this.$$state = isUndefined(state) ? null : state;
  9915. return this;
  9916. };
  9917. });
  9918. function locationGetter(property) {
  9919. return function() {
  9920. return this[property];
  9921. };
  9922. }
  9923. function locationGetterSetter(property, preprocess) {
  9924. return function(value) {
  9925. if (isUndefined(value))
  9926. return this[property];
  9927. this[property] = preprocess(value);
  9928. this.$$compose();
  9929. return this;
  9930. };
  9931. }
  9932. /**
  9933. * @ngdoc service
  9934. * @name $location
  9935. *
  9936. * @requires $rootElement
  9937. *
  9938. * @description
  9939. * The $location service parses the URL in the browser address bar (based on the
  9940. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  9941. * available to your application. Changes to the URL in the address bar are reflected into
  9942. * $location service and changes to $location are reflected into the browser address bar.
  9943. *
  9944. * **The $location service:**
  9945. *
  9946. * - Exposes the current URL in the browser address bar, so you can
  9947. * - Watch and observe the URL.
  9948. * - Change the URL.
  9949. * - Synchronizes the URL with the browser when the user
  9950. * - Changes the address bar.
  9951. * - Clicks the back or forward button (or clicks a History link).
  9952. * - Clicks on a link.
  9953. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  9954. *
  9955. * For more information see {@link guide/$location Developer Guide: Using $location}
  9956. */
  9957. /**
  9958. * @ngdoc provider
  9959. * @name $locationProvider
  9960. * @description
  9961. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  9962. */
  9963. function $LocationProvider() {
  9964. var hashPrefix = '',
  9965. html5Mode = {
  9966. enabled: false,
  9967. requireBase: true,
  9968. rewriteLinks: true
  9969. };
  9970. /**
  9971. * @ngdoc method
  9972. * @name $locationProvider#hashPrefix
  9973. * @description
  9974. * @param {string=} prefix Prefix for hash part (containing path and search)
  9975. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9976. */
  9977. this.hashPrefix = function(prefix) {
  9978. if (isDefined(prefix)) {
  9979. hashPrefix = prefix;
  9980. return this;
  9981. } else {
  9982. return hashPrefix;
  9983. }
  9984. };
  9985. /**
  9986. * @ngdoc method
  9987. * @name $locationProvider#html5Mode
  9988. * @description
  9989. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  9990. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  9991. * properties:
  9992. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  9993. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  9994. * support `pushState`.
  9995. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  9996. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  9997. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  9998. * See the {@link guide/$location $location guide for more information}
  9999. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10000. * enables/disables url rewriting for relative links.
  10001. *
  10002. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10003. */
  10004. this.html5Mode = function(mode) {
  10005. if (isBoolean(mode)) {
  10006. html5Mode.enabled = mode;
  10007. return this;
  10008. } else if (isObject(mode)) {
  10009. if (isBoolean(mode.enabled)) {
  10010. html5Mode.enabled = mode.enabled;
  10011. }
  10012. if (isBoolean(mode.requireBase)) {
  10013. html5Mode.requireBase = mode.requireBase;
  10014. }
  10015. if (isBoolean(mode.rewriteLinks)) {
  10016. html5Mode.rewriteLinks = mode.rewriteLinks;
  10017. }
  10018. return this;
  10019. } else {
  10020. return html5Mode;
  10021. }
  10022. };
  10023. /**
  10024. * @ngdoc event
  10025. * @name $location#$locationChangeStart
  10026. * @eventType broadcast on root scope
  10027. * @description
  10028. * Broadcasted before a URL will change.
  10029. *
  10030. * This change can be prevented by calling
  10031. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10032. * details about event object. Upon successful change
  10033. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10034. *
  10035. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10036. * the browser supports the HTML5 History API.
  10037. *
  10038. * @param {Object} angularEvent Synthetic event object.
  10039. * @param {string} newUrl New URL
  10040. * @param {string=} oldUrl URL that was before it was changed.
  10041. * @param {string=} newState New history state object
  10042. * @param {string=} oldState History state object that was before it was changed.
  10043. */
  10044. /**
  10045. * @ngdoc event
  10046. * @name $location#$locationChangeSuccess
  10047. * @eventType broadcast on root scope
  10048. * @description
  10049. * Broadcasted after a URL was changed.
  10050. *
  10051. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10052. * the browser supports the HTML5 History API.
  10053. *
  10054. * @param {Object} angularEvent Synthetic event object.
  10055. * @param {string} newUrl New URL
  10056. * @param {string=} oldUrl URL that was before it was changed.
  10057. * @param {string=} newState New history state object
  10058. * @param {string=} oldState History state object that was before it was changed.
  10059. */
  10060. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  10061. function($rootScope, $browser, $sniffer, $rootElement) {
  10062. var $location,
  10063. LocationMode,
  10064. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10065. initialUrl = $browser.url(),
  10066. appBase;
  10067. if (html5Mode.enabled) {
  10068. if (!baseHref && html5Mode.requireBase) {
  10069. throw $locationMinErr('nobase',
  10070. "$location in HTML5 mode requires a <base> tag to be present!");
  10071. }
  10072. appBase = serverBase(initialUrl) + (baseHref || '/');
  10073. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10074. } else {
  10075. appBase = stripHash(initialUrl);
  10076. LocationMode = LocationHashbangUrl;
  10077. }
  10078. $location = new LocationMode(appBase, '#' + hashPrefix);
  10079. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10080. $location.$$state = $browser.state();
  10081. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10082. function setBrowserUrlWithFallback(url, replace, state) {
  10083. var oldUrl = $location.url();
  10084. var oldState = $location.$$state;
  10085. try {
  10086. $browser.url(url, replace, state);
  10087. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10088. // state object; this makes possible quick checking if the state changed in the digest
  10089. // loop. Checking deep equality would be too expensive.
  10090. $location.$$state = $browser.state();
  10091. } catch (e) {
  10092. // Restore old values if pushState fails
  10093. $location.url(oldUrl);
  10094. $location.$$state = oldState;
  10095. throw e;
  10096. }
  10097. }
  10098. $rootElement.on('click', function(event) {
  10099. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10100. // currently we open nice url link and redirect then
  10101. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return;
  10102. var elm = jqLite(event.target);
  10103. // traverse the DOM up to find first A tag
  10104. while (nodeName_(elm[0]) !== 'a') {
  10105. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10106. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10107. }
  10108. var absHref = elm.prop('href');
  10109. // get the actual href attribute - see
  10110. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10111. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10112. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10113. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10114. // an animation.
  10115. absHref = urlResolve(absHref.animVal).href;
  10116. }
  10117. // Ignore when url is started with javascript: or mailto:
  10118. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10119. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10120. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10121. // We do a preventDefault for all urls that are part of the angular application,
  10122. // in html5mode and also without, so that we are able to abort navigation without
  10123. // getting double entries in the location history.
  10124. event.preventDefault();
  10125. // update location manually
  10126. if ($location.absUrl() != $browser.url()) {
  10127. $rootScope.$apply();
  10128. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10129. window.angular['ff-684208-preventDefault'] = true;
  10130. }
  10131. }
  10132. }
  10133. });
  10134. // rewrite hashbang url <> html5 url
  10135. if ($location.absUrl() != initialUrl) {
  10136. $browser.url($location.absUrl(), true);
  10137. }
  10138. var initializing = true;
  10139. // update $location when $browser url changes
  10140. $browser.onUrlChange(function(newUrl, newState) {
  10141. $rootScope.$evalAsync(function() {
  10142. var oldUrl = $location.absUrl();
  10143. var oldState = $location.$$state;
  10144. var defaultPrevented;
  10145. $location.$$parse(newUrl);
  10146. $location.$$state = newState;
  10147. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10148. newState, oldState).defaultPrevented;
  10149. // if the location was changed by a `$locationChangeStart` handler then stop
  10150. // processing this location change
  10151. if ($location.absUrl() !== newUrl) return;
  10152. if (defaultPrevented) {
  10153. $location.$$parse(oldUrl);
  10154. $location.$$state = oldState;
  10155. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10156. } else {
  10157. initializing = false;
  10158. afterLocationChange(oldUrl, oldState);
  10159. }
  10160. });
  10161. if (!$rootScope.$$phase) $rootScope.$digest();
  10162. });
  10163. // update browser
  10164. $rootScope.$watch(function $locationWatch() {
  10165. var oldUrl = $browser.url();
  10166. var oldState = $browser.state();
  10167. var currentReplace = $location.$$replace;
  10168. var urlOrStateChanged = oldUrl !== $location.absUrl() ||
  10169. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10170. if (initializing || urlOrStateChanged) {
  10171. initializing = false;
  10172. $rootScope.$evalAsync(function() {
  10173. var newUrl = $location.absUrl();
  10174. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10175. $location.$$state, oldState).defaultPrevented;
  10176. // if the location was changed by a `$locationChangeStart` handler then stop
  10177. // processing this location change
  10178. if ($location.absUrl() !== newUrl) return;
  10179. if (defaultPrevented) {
  10180. $location.$$parse(oldUrl);
  10181. $location.$$state = oldState;
  10182. } else {
  10183. if (urlOrStateChanged) {
  10184. setBrowserUrlWithFallback(newUrl, currentReplace,
  10185. oldState === $location.$$state ? null : $location.$$state);
  10186. }
  10187. afterLocationChange(oldUrl, oldState);
  10188. }
  10189. });
  10190. }
  10191. $location.$$replace = false;
  10192. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10193. // there is a change
  10194. });
  10195. return $location;
  10196. function afterLocationChange(oldUrl, oldState) {
  10197. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10198. $location.$$state, oldState);
  10199. }
  10200. }];
  10201. }
  10202. /**
  10203. * @ngdoc service
  10204. * @name $log
  10205. * @requires $window
  10206. *
  10207. * @description
  10208. * Simple service for logging. Default implementation safely writes the message
  10209. * into the browser's console (if present).
  10210. *
  10211. * The main purpose of this service is to simplify debugging and troubleshooting.
  10212. *
  10213. * The default is to log `debug` messages. You can use
  10214. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10215. *
  10216. * @example
  10217. <example module="logExample">
  10218. <file name="script.js">
  10219. angular.module('logExample', [])
  10220. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10221. $scope.$log = $log;
  10222. $scope.message = 'Hello World!';
  10223. }]);
  10224. </file>
  10225. <file name="index.html">
  10226. <div ng-controller="LogController">
  10227. <p>Reload this page with open console, enter text and hit the log button...</p>
  10228. Message:
  10229. <input type="text" ng-model="message"/>
  10230. <button ng-click="$log.log(message)">log</button>
  10231. <button ng-click="$log.warn(message)">warn</button>
  10232. <button ng-click="$log.info(message)">info</button>
  10233. <button ng-click="$log.error(message)">error</button>
  10234. </div>
  10235. </file>
  10236. </example>
  10237. */
  10238. /**
  10239. * @ngdoc provider
  10240. * @name $logProvider
  10241. * @description
  10242. * Use the `$logProvider` to configure how the application logs messages
  10243. */
  10244. function $LogProvider() {
  10245. var debug = true,
  10246. self = this;
  10247. /**
  10248. * @ngdoc method
  10249. * @name $logProvider#debugEnabled
  10250. * @description
  10251. * @param {boolean=} flag enable or disable debug level messages
  10252. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10253. */
  10254. this.debugEnabled = function(flag) {
  10255. if (isDefined(flag)) {
  10256. debug = flag;
  10257. return this;
  10258. } else {
  10259. return debug;
  10260. }
  10261. };
  10262. this.$get = ['$window', function($window) {
  10263. return {
  10264. /**
  10265. * @ngdoc method
  10266. * @name $log#log
  10267. *
  10268. * @description
  10269. * Write a log message
  10270. */
  10271. log: consoleLog('log'),
  10272. /**
  10273. * @ngdoc method
  10274. * @name $log#info
  10275. *
  10276. * @description
  10277. * Write an information message
  10278. */
  10279. info: consoleLog('info'),
  10280. /**
  10281. * @ngdoc method
  10282. * @name $log#warn
  10283. *
  10284. * @description
  10285. * Write a warning message
  10286. */
  10287. warn: consoleLog('warn'),
  10288. /**
  10289. * @ngdoc method
  10290. * @name $log#error
  10291. *
  10292. * @description
  10293. * Write an error message
  10294. */
  10295. error: consoleLog('error'),
  10296. /**
  10297. * @ngdoc method
  10298. * @name $log#debug
  10299. *
  10300. * @description
  10301. * Write a debug message
  10302. */
  10303. debug: (function() {
  10304. var fn = consoleLog('debug');
  10305. return function() {
  10306. if (debug) {
  10307. fn.apply(self, arguments);
  10308. }
  10309. };
  10310. }())
  10311. };
  10312. function formatError(arg) {
  10313. if (arg instanceof Error) {
  10314. if (arg.stack) {
  10315. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10316. ? 'Error: ' + arg.message + '\n' + arg.stack
  10317. : arg.stack;
  10318. } else if (arg.sourceURL) {
  10319. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10320. }
  10321. }
  10322. return arg;
  10323. }
  10324. function consoleLog(type) {
  10325. var console = $window.console || {},
  10326. logFn = console[type] || console.log || noop,
  10327. hasApply = false;
  10328. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10329. // The reason behind this is that console.log has type "object" in IE8...
  10330. try {
  10331. hasApply = !!logFn.apply;
  10332. } catch (e) {}
  10333. if (hasApply) {
  10334. return function() {
  10335. var args = [];
  10336. forEach(arguments, function(arg) {
  10337. args.push(formatError(arg));
  10338. });
  10339. return logFn.apply(console, args);
  10340. };
  10341. }
  10342. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10343. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10344. return function(arg1, arg2) {
  10345. logFn(arg1, arg2 == null ? '' : arg2);
  10346. };
  10347. }
  10348. }];
  10349. }
  10350. var $parseMinErr = minErr('$parse');
  10351. // Sandboxing Angular Expressions
  10352. // ------------------------------
  10353. // Angular expressions are generally considered safe because these expressions only have direct
  10354. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  10355. // obtaining a reference to native JS functions such as the Function constructor.
  10356. //
  10357. // As an example, consider the following Angular expression:
  10358. //
  10359. // {}.toString.constructor('alert("evil JS code")')
  10360. //
  10361. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10362. // against the expression language, but not to prevent exploits that were enabled by exposing
  10363. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  10364. // practice and therefore we are not even trying to protect against interaction with an object
  10365. // explicitly exposed in this way.
  10366. //
  10367. // In general, it is not possible to access a Window object from an angular expression unless a
  10368. // window or some DOM object that has a reference to window is published onto a Scope.
  10369. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10370. // native objects.
  10371. //
  10372. // See https://docs.angularjs.org/guide/security
  10373. function ensureSafeMemberName(name, fullExpression) {
  10374. if (name === "__defineGetter__" || name === "__defineSetter__"
  10375. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10376. || name === "__proto__") {
  10377. throw $parseMinErr('isecfld',
  10378. 'Attempting to access a disallowed field in Angular expressions! '
  10379. + 'Expression: {0}', fullExpression);
  10380. }
  10381. return name;
  10382. }
  10383. function ensureSafeObject(obj, fullExpression) {
  10384. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10385. if (obj) {
  10386. if (obj.constructor === obj) {
  10387. throw $parseMinErr('isecfn',
  10388. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10389. fullExpression);
  10390. } else if (// isWindow(obj)
  10391. obj.window === obj) {
  10392. throw $parseMinErr('isecwindow',
  10393. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10394. fullExpression);
  10395. } else if (// isElement(obj)
  10396. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10397. throw $parseMinErr('isecdom',
  10398. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10399. fullExpression);
  10400. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10401. obj === Object) {
  10402. throw $parseMinErr('isecobj',
  10403. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10404. fullExpression);
  10405. }
  10406. }
  10407. return obj;
  10408. }
  10409. var CALL = Function.prototype.call;
  10410. var APPLY = Function.prototype.apply;
  10411. var BIND = Function.prototype.bind;
  10412. function ensureSafeFunction(obj, fullExpression) {
  10413. if (obj) {
  10414. if (obj.constructor === obj) {
  10415. throw $parseMinErr('isecfn',
  10416. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10417. fullExpression);
  10418. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10419. throw $parseMinErr('isecff',
  10420. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10421. fullExpression);
  10422. }
  10423. }
  10424. }
  10425. //Keyword constants
  10426. var CONSTANTS = createMap();
  10427. forEach({
  10428. 'null': function() { return null; },
  10429. 'true': function() { return true; },
  10430. 'false': function() { return false; },
  10431. 'undefined': function() {}
  10432. }, function(constantGetter, name) {
  10433. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10434. CONSTANTS[name] = constantGetter;
  10435. });
  10436. //Not quite a constant, but can be lex/parsed the same
  10437. CONSTANTS['this'] = function(self) { return self; };
  10438. CONSTANTS['this'].sharedGetter = true;
  10439. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10440. var OPERATORS = extend(createMap(), {
  10441. '+':function(self, locals, a, b) {
  10442. a=a(self, locals); b=b(self, locals);
  10443. if (isDefined(a)) {
  10444. if (isDefined(b)) {
  10445. return a + b;
  10446. }
  10447. return a;
  10448. }
  10449. return isDefined(b) ? b : undefined;},
  10450. '-':function(self, locals, a, b) {
  10451. a=a(self, locals); b=b(self, locals);
  10452. return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
  10453. },
  10454. '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},
  10455. '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},
  10456. '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},
  10457. '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},
  10458. '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},
  10459. '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},
  10460. '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
  10461. '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
  10462. '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
  10463. '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
  10464. '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
  10465. '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
  10466. '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
  10467. '!':function(self, locals, a) {return !a(self, locals);},
  10468. //Tokenized as operators but parsed as assignment/filters
  10469. '=':true,
  10470. '|':true
  10471. });
  10472. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10473. /////////////////////////////////////////
  10474. /**
  10475. * @constructor
  10476. */
  10477. var Lexer = function(options) {
  10478. this.options = options;
  10479. };
  10480. Lexer.prototype = {
  10481. constructor: Lexer,
  10482. lex: function(text) {
  10483. this.text = text;
  10484. this.index = 0;
  10485. this.tokens = [];
  10486. while (this.index < this.text.length) {
  10487. var ch = this.text.charAt(this.index);
  10488. if (ch === '"' || ch === "'") {
  10489. this.readString(ch);
  10490. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  10491. this.readNumber();
  10492. } else if (this.isIdent(ch)) {
  10493. this.readIdent();
  10494. } else if (this.is(ch, '(){}[].,;:?')) {
  10495. this.tokens.push({index: this.index, text: ch});
  10496. this.index++;
  10497. } else if (this.isWhitespace(ch)) {
  10498. this.index++;
  10499. } else {
  10500. var ch2 = ch + this.peek();
  10501. var ch3 = ch2 + this.peek(2);
  10502. var op1 = OPERATORS[ch];
  10503. var op2 = OPERATORS[ch2];
  10504. var op3 = OPERATORS[ch3];
  10505. if (op1 || op2 || op3) {
  10506. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  10507. this.tokens.push({index: this.index, text: token, operator: true});
  10508. this.index += token.length;
  10509. } else {
  10510. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10511. }
  10512. }
  10513. }
  10514. return this.tokens;
  10515. },
  10516. is: function(ch, chars) {
  10517. return chars.indexOf(ch) !== -1;
  10518. },
  10519. peek: function(i) {
  10520. var num = i || 1;
  10521. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10522. },
  10523. isNumber: function(ch) {
  10524. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  10525. },
  10526. isWhitespace: function(ch) {
  10527. // IE treats non-breaking space as \u00A0
  10528. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10529. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10530. },
  10531. isIdent: function(ch) {
  10532. return ('a' <= ch && ch <= 'z' ||
  10533. 'A' <= ch && ch <= 'Z' ||
  10534. '_' === ch || ch === '$');
  10535. },
  10536. isExpOperator: function(ch) {
  10537. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10538. },
  10539. throwError: function(error, start, end) {
  10540. end = end || this.index;
  10541. var colStr = (isDefined(start)
  10542. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10543. : ' ' + end);
  10544. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10545. error, colStr, this.text);
  10546. },
  10547. readNumber: function() {
  10548. var number = '';
  10549. var start = this.index;
  10550. while (this.index < this.text.length) {
  10551. var ch = lowercase(this.text.charAt(this.index));
  10552. if (ch == '.' || this.isNumber(ch)) {
  10553. number += ch;
  10554. } else {
  10555. var peekCh = this.peek();
  10556. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10557. number += ch;
  10558. } else if (this.isExpOperator(ch) &&
  10559. peekCh && this.isNumber(peekCh) &&
  10560. number.charAt(number.length - 1) == 'e') {
  10561. number += ch;
  10562. } else if (this.isExpOperator(ch) &&
  10563. (!peekCh || !this.isNumber(peekCh)) &&
  10564. number.charAt(number.length - 1) == 'e') {
  10565. this.throwError('Invalid exponent');
  10566. } else {
  10567. break;
  10568. }
  10569. }
  10570. this.index++;
  10571. }
  10572. this.tokens.push({
  10573. index: start,
  10574. text: number,
  10575. constant: true,
  10576. value: Number(number)
  10577. });
  10578. },
  10579. readIdent: function() {
  10580. var start = this.index;
  10581. while (this.index < this.text.length) {
  10582. var ch = this.text.charAt(this.index);
  10583. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  10584. break;
  10585. }
  10586. this.index++;
  10587. }
  10588. this.tokens.push({
  10589. index: start,
  10590. text: this.text.slice(start, this.index),
  10591. identifier: true
  10592. });
  10593. },
  10594. readString: function(quote) {
  10595. var start = this.index;
  10596. this.index++;
  10597. var string = '';
  10598. var rawString = quote;
  10599. var escape = false;
  10600. while (this.index < this.text.length) {
  10601. var ch = this.text.charAt(this.index);
  10602. rawString += ch;
  10603. if (escape) {
  10604. if (ch === 'u') {
  10605. var hex = this.text.substring(this.index + 1, this.index + 5);
  10606. if (!hex.match(/[\da-f]{4}/i))
  10607. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10608. this.index += 4;
  10609. string += String.fromCharCode(parseInt(hex, 16));
  10610. } else {
  10611. var rep = ESCAPE[ch];
  10612. string = string + (rep || ch);
  10613. }
  10614. escape = false;
  10615. } else if (ch === '\\') {
  10616. escape = true;
  10617. } else if (ch === quote) {
  10618. this.index++;
  10619. this.tokens.push({
  10620. index: start,
  10621. text: rawString,
  10622. constant: true,
  10623. value: string
  10624. });
  10625. return;
  10626. } else {
  10627. string += ch;
  10628. }
  10629. this.index++;
  10630. }
  10631. this.throwError('Unterminated quote', start);
  10632. }
  10633. };
  10634. function isConstant(exp) {
  10635. return exp.constant;
  10636. }
  10637. /**
  10638. * @constructor
  10639. */
  10640. var Parser = function(lexer, $filter, options) {
  10641. this.lexer = lexer;
  10642. this.$filter = $filter;
  10643. this.options = options;
  10644. };
  10645. Parser.ZERO = extend(function() {
  10646. return 0;
  10647. }, {
  10648. sharedGetter: true,
  10649. constant: true
  10650. });
  10651. Parser.prototype = {
  10652. constructor: Parser,
  10653. parse: function(text) {
  10654. this.text = text;
  10655. this.tokens = this.lexer.lex(text);
  10656. var value = this.statements();
  10657. if (this.tokens.length !== 0) {
  10658. this.throwError('is an unexpected token', this.tokens[0]);
  10659. }
  10660. value.literal = !!value.literal;
  10661. value.constant = !!value.constant;
  10662. return value;
  10663. },
  10664. primary: function() {
  10665. var primary;
  10666. if (this.expect('(')) {
  10667. primary = this.filterChain();
  10668. this.consume(')');
  10669. } else if (this.expect('[')) {
  10670. primary = this.arrayDeclaration();
  10671. } else if (this.expect('{')) {
  10672. primary = this.object();
  10673. } else if (this.peek().identifier) {
  10674. primary = this.identifier();
  10675. } else if (this.peek().constant) {
  10676. primary = this.constant();
  10677. } else {
  10678. this.throwError('not a primary expression', this.peek());
  10679. }
  10680. var next, context;
  10681. while ((next = this.expect('(', '[', '.'))) {
  10682. if (next.text === '(') {
  10683. primary = this.functionCall(primary, context);
  10684. context = null;
  10685. } else if (next.text === '[') {
  10686. context = primary;
  10687. primary = this.objectIndex(primary);
  10688. } else if (next.text === '.') {
  10689. context = primary;
  10690. primary = this.fieldAccess(primary);
  10691. } else {
  10692. this.throwError('IMPOSSIBLE');
  10693. }
  10694. }
  10695. return primary;
  10696. },
  10697. throwError: function(msg, token) {
  10698. throw $parseMinErr('syntax',
  10699. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10700. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10701. },
  10702. peekToken: function() {
  10703. if (this.tokens.length === 0)
  10704. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10705. return this.tokens[0];
  10706. },
  10707. peek: function(e1, e2, e3, e4) {
  10708. return this.peekAhead(0, e1, e2, e3, e4);
  10709. },
  10710. peekAhead: function(i, e1, e2, e3, e4) {
  10711. if (this.tokens.length > i) {
  10712. var token = this.tokens[i];
  10713. var t = token.text;
  10714. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10715. (!e1 && !e2 && !e3 && !e4)) {
  10716. return token;
  10717. }
  10718. }
  10719. return false;
  10720. },
  10721. expect: function(e1, e2, e3, e4) {
  10722. var token = this.peek(e1, e2, e3, e4);
  10723. if (token) {
  10724. this.tokens.shift();
  10725. return token;
  10726. }
  10727. return false;
  10728. },
  10729. consume: function(e1) {
  10730. if (this.tokens.length === 0) {
  10731. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10732. }
  10733. var token = this.expect(e1);
  10734. if (!token) {
  10735. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10736. }
  10737. return token;
  10738. },
  10739. unaryFn: function(op, right) {
  10740. var fn = OPERATORS[op];
  10741. return extend(function $parseUnaryFn(self, locals) {
  10742. return fn(self, locals, right);
  10743. }, {
  10744. constant:right.constant,
  10745. inputs: [right]
  10746. });
  10747. },
  10748. binaryFn: function(left, op, right, isBranching) {
  10749. var fn = OPERATORS[op];
  10750. return extend(function $parseBinaryFn(self, locals) {
  10751. return fn(self, locals, left, right);
  10752. }, {
  10753. constant: left.constant && right.constant,
  10754. inputs: !isBranching && [left, right]
  10755. });
  10756. },
  10757. identifier: function() {
  10758. var id = this.consume().text;
  10759. //Continue reading each `.identifier` unless it is a method invocation
  10760. while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
  10761. id += this.consume().text + this.consume().text;
  10762. }
  10763. return CONSTANTS[id] || getterFn(id, this.options, this.text);
  10764. },
  10765. constant: function() {
  10766. var value = this.consume().value;
  10767. return extend(function $parseConstant() {
  10768. return value;
  10769. }, {
  10770. constant: true,
  10771. literal: true
  10772. });
  10773. },
  10774. statements: function() {
  10775. var statements = [];
  10776. while (true) {
  10777. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10778. statements.push(this.filterChain());
  10779. if (!this.expect(';')) {
  10780. // optimize for the common case where there is only one statement.
  10781. // TODO(size): maybe we should not support multiple statements?
  10782. return (statements.length === 1)
  10783. ? statements[0]
  10784. : function $parseStatements(self, locals) {
  10785. var value;
  10786. for (var i = 0, ii = statements.length; i < ii; i++) {
  10787. value = statements[i](self, locals);
  10788. }
  10789. return value;
  10790. };
  10791. }
  10792. }
  10793. },
  10794. filterChain: function() {
  10795. var left = this.expression();
  10796. var token;
  10797. while ((token = this.expect('|'))) {
  10798. left = this.filter(left);
  10799. }
  10800. return left;
  10801. },
  10802. filter: function(inputFn) {
  10803. var fn = this.$filter(this.consume().text);
  10804. var argsFn;
  10805. var args;
  10806. if (this.peek(':')) {
  10807. argsFn = [];
  10808. args = []; // we can safely reuse the array
  10809. while (this.expect(':')) {
  10810. argsFn.push(this.expression());
  10811. }
  10812. }
  10813. var inputs = [inputFn].concat(argsFn || []);
  10814. return extend(function $parseFilter(self, locals) {
  10815. var input = inputFn(self, locals);
  10816. if (args) {
  10817. args[0] = input;
  10818. var i = argsFn.length;
  10819. while (i--) {
  10820. args[i + 1] = argsFn[i](self, locals);
  10821. }
  10822. return fn.apply(undefined, args);
  10823. }
  10824. return fn(input);
  10825. }, {
  10826. constant: !fn.$stateful && inputs.every(isConstant),
  10827. inputs: !fn.$stateful && inputs
  10828. });
  10829. },
  10830. expression: function() {
  10831. return this.assignment();
  10832. },
  10833. assignment: function() {
  10834. var left = this.ternary();
  10835. var right;
  10836. var token;
  10837. if ((token = this.expect('='))) {
  10838. if (!left.assign) {
  10839. this.throwError('implies assignment but [' +
  10840. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10841. }
  10842. right = this.ternary();
  10843. return extend(function $parseAssignment(scope, locals) {
  10844. return left.assign(scope, right(scope, locals), locals);
  10845. }, {
  10846. inputs: [left, right]
  10847. });
  10848. }
  10849. return left;
  10850. },
  10851. ternary: function() {
  10852. var left = this.logicalOR();
  10853. var middle;
  10854. var token;
  10855. if ((token = this.expect('?'))) {
  10856. middle = this.assignment();
  10857. if (this.consume(':')) {
  10858. var right = this.assignment();
  10859. return extend(function $parseTernary(self, locals) {
  10860. return left(self, locals) ? middle(self, locals) : right(self, locals);
  10861. }, {
  10862. constant: left.constant && middle.constant && right.constant
  10863. });
  10864. }
  10865. }
  10866. return left;
  10867. },
  10868. logicalOR: function() {
  10869. var left = this.logicalAND();
  10870. var token;
  10871. while ((token = this.expect('||'))) {
  10872. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  10873. }
  10874. return left;
  10875. },
  10876. logicalAND: function() {
  10877. var left = this.equality();
  10878. var token;
  10879. if ((token = this.expect('&&'))) {
  10880. left = this.binaryFn(left, token.text, this.logicalAND(), true);
  10881. }
  10882. return left;
  10883. },
  10884. equality: function() {
  10885. var left = this.relational();
  10886. var token;
  10887. if ((token = this.expect('==','!=','===','!=='))) {
  10888. left = this.binaryFn(left, token.text, this.equality());
  10889. }
  10890. return left;
  10891. },
  10892. relational: function() {
  10893. var left = this.additive();
  10894. var token;
  10895. if ((token = this.expect('<', '>', '<=', '>='))) {
  10896. left = this.binaryFn(left, token.text, this.relational());
  10897. }
  10898. return left;
  10899. },
  10900. additive: function() {
  10901. var left = this.multiplicative();
  10902. var token;
  10903. while ((token = this.expect('+','-'))) {
  10904. left = this.binaryFn(left, token.text, this.multiplicative());
  10905. }
  10906. return left;
  10907. },
  10908. multiplicative: function() {
  10909. var left = this.unary();
  10910. var token;
  10911. while ((token = this.expect('*','/','%'))) {
  10912. left = this.binaryFn(left, token.text, this.unary());
  10913. }
  10914. return left;
  10915. },
  10916. unary: function() {
  10917. var token;
  10918. if (this.expect('+')) {
  10919. return this.primary();
  10920. } else if ((token = this.expect('-'))) {
  10921. return this.binaryFn(Parser.ZERO, token.text, this.unary());
  10922. } else if ((token = this.expect('!'))) {
  10923. return this.unaryFn(token.text, this.unary());
  10924. } else {
  10925. return this.primary();
  10926. }
  10927. },
  10928. fieldAccess: function(object) {
  10929. var expression = this.text;
  10930. var field = this.consume().text;
  10931. var getter = getterFn(field, this.options, expression);
  10932. return extend(function $parseFieldAccess(scope, locals, self) {
  10933. return getter(self || object(scope, locals));
  10934. }, {
  10935. assign: function(scope, value, locals) {
  10936. var o = object(scope, locals);
  10937. if (!o) object.assign(scope, o = {});
  10938. return setter(o, field, value, expression);
  10939. }
  10940. });
  10941. },
  10942. objectIndex: function(obj) {
  10943. var expression = this.text;
  10944. var indexFn = this.expression();
  10945. this.consume(']');
  10946. return extend(function $parseObjectIndex(self, locals) {
  10947. var o = obj(self, locals),
  10948. i = indexFn(self, locals),
  10949. v;
  10950. ensureSafeMemberName(i, expression);
  10951. if (!o) return undefined;
  10952. v = ensureSafeObject(o[i], expression);
  10953. return v;
  10954. }, {
  10955. assign: function(self, value, locals) {
  10956. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  10957. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  10958. var o = ensureSafeObject(obj(self, locals), expression);
  10959. if (!o) obj.assign(self, o = {});
  10960. return o[key] = value;
  10961. }
  10962. });
  10963. },
  10964. functionCall: function(fnGetter, contextGetter) {
  10965. var argsFn = [];
  10966. if (this.peekToken().text !== ')') {
  10967. do {
  10968. argsFn.push(this.expression());
  10969. } while (this.expect(','));
  10970. }
  10971. this.consume(')');
  10972. var expressionText = this.text;
  10973. // we can safely reuse the array across invocations
  10974. var args = argsFn.length ? [] : null;
  10975. return function $parseFunctionCall(scope, locals) {
  10976. var context = contextGetter ? contextGetter(scope, locals) : scope;
  10977. var fn = fnGetter(scope, locals, context) || noop;
  10978. if (args) {
  10979. var i = argsFn.length;
  10980. while (i--) {
  10981. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  10982. }
  10983. }
  10984. ensureSafeObject(context, expressionText);
  10985. ensureSafeFunction(fn, expressionText);
  10986. // IE stupidity! (IE doesn't have apply for some native functions)
  10987. var v = fn.apply
  10988. ? fn.apply(context, args)
  10989. : fn(args[0], args[1], args[2], args[3], args[4]);
  10990. return ensureSafeObject(v, expressionText);
  10991. };
  10992. },
  10993. // This is used with json array declaration
  10994. arrayDeclaration: function() {
  10995. var elementFns = [];
  10996. if (this.peekToken().text !== ']') {
  10997. do {
  10998. if (this.peek(']')) {
  10999. // Support trailing commas per ES5.1.
  11000. break;
  11001. }
  11002. elementFns.push(this.expression());
  11003. } while (this.expect(','));
  11004. }
  11005. this.consume(']');
  11006. return extend(function $parseArrayLiteral(self, locals) {
  11007. var array = [];
  11008. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  11009. array.push(elementFns[i](self, locals));
  11010. }
  11011. return array;
  11012. }, {
  11013. literal: true,
  11014. constant: elementFns.every(isConstant),
  11015. inputs: elementFns
  11016. });
  11017. },
  11018. object: function() {
  11019. var keys = [], valueFns = [];
  11020. if (this.peekToken().text !== '}') {
  11021. do {
  11022. if (this.peek('}')) {
  11023. // Support trailing commas per ES5.1.
  11024. break;
  11025. }
  11026. var token = this.consume();
  11027. if (token.constant) {
  11028. keys.push(token.value);
  11029. } else if (token.identifier) {
  11030. keys.push(token.text);
  11031. } else {
  11032. this.throwError("invalid key", token);
  11033. }
  11034. this.consume(':');
  11035. valueFns.push(this.expression());
  11036. } while (this.expect(','));
  11037. }
  11038. this.consume('}');
  11039. return extend(function $parseObjectLiteral(self, locals) {
  11040. var object = {};
  11041. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  11042. object[keys[i]] = valueFns[i](self, locals);
  11043. }
  11044. return object;
  11045. }, {
  11046. literal: true,
  11047. constant: valueFns.every(isConstant),
  11048. inputs: valueFns
  11049. });
  11050. }
  11051. };
  11052. //////////////////////////////////////////////////
  11053. // Parser helper functions
  11054. //////////////////////////////////////////////////
  11055. function setter(obj, path, setValue, fullExp) {
  11056. ensureSafeObject(obj, fullExp);
  11057. var element = path.split('.'), key;
  11058. for (var i = 0; element.length > 1; i++) {
  11059. key = ensureSafeMemberName(element.shift(), fullExp);
  11060. var propertyObj = ensureSafeObject(obj[key], fullExp);
  11061. if (!propertyObj) {
  11062. propertyObj = {};
  11063. obj[key] = propertyObj;
  11064. }
  11065. obj = propertyObj;
  11066. }
  11067. key = ensureSafeMemberName(element.shift(), fullExp);
  11068. ensureSafeObject(obj[key], fullExp);
  11069. obj[key] = setValue;
  11070. return setValue;
  11071. }
  11072. var getterFnCacheDefault = createMap();
  11073. var getterFnCacheExpensive = createMap();
  11074. function isPossiblyDangerousMemberName(name) {
  11075. return name == 'constructor';
  11076. }
  11077. /**
  11078. * Implementation of the "Black Hole" variant from:
  11079. * - http://jsperf.com/angularjs-parse-getter/4
  11080. * - http://jsperf.com/path-evaluation-simplified/7
  11081. */
  11082. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11083. ensureSafeMemberName(key0, fullExp);
  11084. ensureSafeMemberName(key1, fullExp);
  11085. ensureSafeMemberName(key2, fullExp);
  11086. ensureSafeMemberName(key3, fullExp);
  11087. ensureSafeMemberName(key4, fullExp);
  11088. var eso = function(o) {
  11089. return ensureSafeObject(o, fullExp);
  11090. };
  11091. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11092. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11093. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11094. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11095. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11096. return function cspSafeGetter(scope, locals) {
  11097. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11098. if (pathVal == null) return pathVal;
  11099. pathVal = eso0(pathVal[key0]);
  11100. if (!key1) return pathVal;
  11101. if (pathVal == null) return undefined;
  11102. pathVal = eso1(pathVal[key1]);
  11103. if (!key2) return pathVal;
  11104. if (pathVal == null) return undefined;
  11105. pathVal = eso2(pathVal[key2]);
  11106. if (!key3) return pathVal;
  11107. if (pathVal == null) return undefined;
  11108. pathVal = eso3(pathVal[key3]);
  11109. if (!key4) return pathVal;
  11110. if (pathVal == null) return undefined;
  11111. pathVal = eso4(pathVal[key4]);
  11112. return pathVal;
  11113. };
  11114. }
  11115. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11116. return function(s, l) {
  11117. return fn(s, l, ensureSafeObject, fullExpression);
  11118. };
  11119. }
  11120. function getterFn(path, options, fullExp) {
  11121. var expensiveChecks = options.expensiveChecks;
  11122. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11123. var fn = getterFnCache[path];
  11124. if (fn) return fn;
  11125. var pathKeys = path.split('.'),
  11126. pathKeysLength = pathKeys.length;
  11127. // http://jsperf.com/angularjs-parse-getter/6
  11128. if (options.csp) {
  11129. if (pathKeysLength < 6) {
  11130. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11131. } else {
  11132. fn = function cspSafeGetter(scope, locals) {
  11133. var i = 0, val;
  11134. do {
  11135. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11136. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11137. locals = undefined; // clear after first iteration
  11138. scope = val;
  11139. } while (i < pathKeysLength);
  11140. return val;
  11141. };
  11142. }
  11143. } else {
  11144. var code = '';
  11145. if (expensiveChecks) {
  11146. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11147. }
  11148. var needsEnsureSafeObject = expensiveChecks;
  11149. forEach(pathKeys, function(key, index) {
  11150. ensureSafeMemberName(key, fullExp);
  11151. var lookupJs = (index
  11152. // we simply dereference 's' on any .dot notation
  11153. ? 's'
  11154. // but if we are first then we check locals first, and if so read it first
  11155. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11156. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11157. lookupJs = 'eso(' + lookupJs + ', fe)';
  11158. needsEnsureSafeObject = true;
  11159. }
  11160. code += 'if(s == null) return undefined;\n' +
  11161. 's=' + lookupJs + ';\n';
  11162. });
  11163. code += 'return s;';
  11164. /* jshint -W054 */
  11165. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11166. /* jshint +W054 */
  11167. evaledFnGetter.toString = valueFn(code);
  11168. if (needsEnsureSafeObject) {
  11169. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11170. }
  11171. fn = evaledFnGetter;
  11172. }
  11173. fn.sharedGetter = true;
  11174. fn.assign = function(self, value) {
  11175. return setter(self, path, value, path);
  11176. };
  11177. getterFnCache[path] = fn;
  11178. return fn;
  11179. }
  11180. var objectValueOf = Object.prototype.valueOf;
  11181. function getValueOf(value) {
  11182. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11183. }
  11184. ///////////////////////////////////
  11185. /**
  11186. * @ngdoc service
  11187. * @name $parse
  11188. * @kind function
  11189. *
  11190. * @description
  11191. *
  11192. * Converts Angular {@link guide/expression expression} into a function.
  11193. *
  11194. * ```js
  11195. * var getter = $parse('user.name');
  11196. * var setter = getter.assign;
  11197. * var context = {user:{name:'angular'}};
  11198. * var locals = {user:{name:'local'}};
  11199. *
  11200. * expect(getter(context)).toEqual('angular');
  11201. * setter(context, 'newValue');
  11202. * expect(context.user.name).toEqual('newValue');
  11203. * expect(getter(context, locals)).toEqual('local');
  11204. * ```
  11205. *
  11206. *
  11207. * @param {string} expression String expression to compile.
  11208. * @returns {function(context, locals)} a function which represents the compiled expression:
  11209. *
  11210. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11211. * are evaluated against (typically a scope object).
  11212. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11213. * `context`.
  11214. *
  11215. * The returned function also has the following properties:
  11216. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11217. * literal.
  11218. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11219. * constant literals.
  11220. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11221. * set to a function to change its value on the given context.
  11222. *
  11223. */
  11224. /**
  11225. * @ngdoc provider
  11226. * @name $parseProvider
  11227. *
  11228. * @description
  11229. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11230. * service.
  11231. */
  11232. function $ParseProvider() {
  11233. var cacheDefault = createMap();
  11234. var cacheExpensive = createMap();
  11235. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11236. var $parseOptions = {
  11237. csp: $sniffer.csp,
  11238. expensiveChecks: false
  11239. },
  11240. $parseOptionsExpensive = {
  11241. csp: $sniffer.csp,
  11242. expensiveChecks: true
  11243. };
  11244. function wrapSharedExpression(exp) {
  11245. var wrapped = exp;
  11246. if (exp.sharedGetter) {
  11247. wrapped = function $parseWrapper(self, locals) {
  11248. return exp(self, locals);
  11249. };
  11250. wrapped.literal = exp.literal;
  11251. wrapped.constant = exp.constant;
  11252. wrapped.assign = exp.assign;
  11253. }
  11254. return wrapped;
  11255. }
  11256. return function $parse(exp, interceptorFn, expensiveChecks) {
  11257. var parsedExpression, oneTime, cacheKey;
  11258. switch (typeof exp) {
  11259. case 'string':
  11260. cacheKey = exp = exp.trim();
  11261. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11262. parsedExpression = cache[cacheKey];
  11263. if (!parsedExpression) {
  11264. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11265. oneTime = true;
  11266. exp = exp.substring(2);
  11267. }
  11268. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11269. var lexer = new Lexer(parseOptions);
  11270. var parser = new Parser(lexer, $filter, parseOptions);
  11271. parsedExpression = parser.parse(exp);
  11272. if (parsedExpression.constant) {
  11273. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11274. } else if (oneTime) {
  11275. //oneTime is not part of the exp passed to the Parser so we may have to
  11276. //wrap the parsedExpression before adding a $$watchDelegate
  11277. parsedExpression = wrapSharedExpression(parsedExpression);
  11278. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11279. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11280. } else if (parsedExpression.inputs) {
  11281. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11282. }
  11283. cache[cacheKey] = parsedExpression;
  11284. }
  11285. return addInterceptor(parsedExpression, interceptorFn);
  11286. case 'function':
  11287. return addInterceptor(exp, interceptorFn);
  11288. default:
  11289. return addInterceptor(noop, interceptorFn);
  11290. }
  11291. };
  11292. function collectExpressionInputs(inputs, list) {
  11293. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11294. var input = inputs[i];
  11295. if (!input.constant) {
  11296. if (input.inputs) {
  11297. collectExpressionInputs(input.inputs, list);
  11298. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11299. list.push(input);
  11300. }
  11301. }
  11302. }
  11303. return list;
  11304. }
  11305. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11306. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11307. return newValue === oldValueOfValue;
  11308. }
  11309. if (typeof newValue === 'object') {
  11310. // attempt to convert the value to a primitive type
  11311. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11312. // be cheaply dirty-checked
  11313. newValue = getValueOf(newValue);
  11314. if (typeof newValue === 'object') {
  11315. // objects/arrays are not supported - deep-watching them would be too expensive
  11316. return false;
  11317. }
  11318. // fall-through to the primitive equality check
  11319. }
  11320. //Primitive or NaN
  11321. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11322. }
  11323. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11324. var inputExpressions = parsedExpression.$$inputs ||
  11325. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11326. var lastResult;
  11327. if (inputExpressions.length === 1) {
  11328. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11329. inputExpressions = inputExpressions[0];
  11330. return scope.$watch(function expressionInputWatch(scope) {
  11331. var newInputValue = inputExpressions(scope);
  11332. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11333. lastResult = parsedExpression(scope);
  11334. oldInputValue = newInputValue && getValueOf(newInputValue);
  11335. }
  11336. return lastResult;
  11337. }, listener, objectEquality);
  11338. }
  11339. var oldInputValueOfValues = [];
  11340. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11341. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11342. }
  11343. return scope.$watch(function expressionInputsWatch(scope) {
  11344. var changed = false;
  11345. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11346. var newInputValue = inputExpressions[i](scope);
  11347. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11348. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11349. }
  11350. }
  11351. if (changed) {
  11352. lastResult = parsedExpression(scope);
  11353. }
  11354. return lastResult;
  11355. }, listener, objectEquality);
  11356. }
  11357. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11358. var unwatch, lastValue;
  11359. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11360. return parsedExpression(scope);
  11361. }, function oneTimeListener(value, old, scope) {
  11362. lastValue = value;
  11363. if (isFunction(listener)) {
  11364. listener.apply(this, arguments);
  11365. }
  11366. if (isDefined(value)) {
  11367. scope.$$postDigest(function() {
  11368. if (isDefined(lastValue)) {
  11369. unwatch();
  11370. }
  11371. });
  11372. }
  11373. }, objectEquality);
  11374. }
  11375. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11376. var unwatch, lastValue;
  11377. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11378. return parsedExpression(scope);
  11379. }, function oneTimeListener(value, old, scope) {
  11380. lastValue = value;
  11381. if (isFunction(listener)) {
  11382. listener.call(this, value, old, scope);
  11383. }
  11384. if (isAllDefined(value)) {
  11385. scope.$$postDigest(function() {
  11386. if (isAllDefined(lastValue)) unwatch();
  11387. });
  11388. }
  11389. }, objectEquality);
  11390. function isAllDefined(value) {
  11391. var allDefined = true;
  11392. forEach(value, function(val) {
  11393. if (!isDefined(val)) allDefined = false;
  11394. });
  11395. return allDefined;
  11396. }
  11397. }
  11398. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11399. var unwatch;
  11400. return unwatch = scope.$watch(function constantWatch(scope) {
  11401. return parsedExpression(scope);
  11402. }, function constantListener(value, old, scope) {
  11403. if (isFunction(listener)) {
  11404. listener.apply(this, arguments);
  11405. }
  11406. unwatch();
  11407. }, objectEquality);
  11408. }
  11409. function addInterceptor(parsedExpression, interceptorFn) {
  11410. if (!interceptorFn) return parsedExpression;
  11411. var watchDelegate = parsedExpression.$$watchDelegate;
  11412. var regularWatch =
  11413. watchDelegate !== oneTimeLiteralWatchDelegate &&
  11414. watchDelegate !== oneTimeWatchDelegate;
  11415. var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
  11416. var value = parsedExpression(scope, locals);
  11417. return interceptorFn(value, scope, locals);
  11418. } : function oneTimeInterceptedExpression(scope, locals) {
  11419. var value = parsedExpression(scope, locals);
  11420. var result = interceptorFn(value, scope, locals);
  11421. // we only return the interceptor's result if the
  11422. // initial value is defined (for bind-once)
  11423. return isDefined(value) ? result : value;
  11424. };
  11425. // Propagate $$watchDelegates other then inputsWatchDelegate
  11426. if (parsedExpression.$$watchDelegate &&
  11427. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11428. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11429. } else if (!interceptorFn.$stateful) {
  11430. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11431. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11432. fn.$$watchDelegate = inputsWatchDelegate;
  11433. fn.inputs = [parsedExpression];
  11434. }
  11435. return fn;
  11436. }
  11437. }];
  11438. }
  11439. /**
  11440. * @ngdoc service
  11441. * @name $q
  11442. * @requires $rootScope
  11443. *
  11444. * @description
  11445. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  11446. * when they are done processing.
  11447. *
  11448. * This is an implementation of promises/deferred objects inspired by
  11449. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  11450. *
  11451. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11452. * implementations, and the other which resembles ES6 promises to some degree.
  11453. *
  11454. * # $q constructor
  11455. *
  11456. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11457. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11458. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11459. *
  11460. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11461. * available yet.
  11462. *
  11463. * It can be used like so:
  11464. *
  11465. * ```js
  11466. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11467. * // are available in the current lexical scope (they could have been injected or passed in).
  11468. *
  11469. * function asyncGreet(name) {
  11470. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11471. * return $q(function(resolve, reject) {
  11472. * setTimeout(function() {
  11473. * if (okToGreet(name)) {
  11474. * resolve('Hello, ' + name + '!');
  11475. * } else {
  11476. * reject('Greeting ' + name + ' is not allowed.');
  11477. * }
  11478. * }, 1000);
  11479. * });
  11480. * }
  11481. *
  11482. * var promise = asyncGreet('Robin Hood');
  11483. * promise.then(function(greeting) {
  11484. * alert('Success: ' + greeting);
  11485. * }, function(reason) {
  11486. * alert('Failed: ' + reason);
  11487. * });
  11488. * ```
  11489. *
  11490. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11491. *
  11492. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11493. *
  11494. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11495. * interface for interacting with an object that represents the result of an action that is
  11496. * performed asynchronously, and may or may not be finished at any given point in time.
  11497. *
  11498. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11499. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11500. *
  11501. * ```js
  11502. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11503. * // are available in the current lexical scope (they could have been injected or passed in).
  11504. *
  11505. * function asyncGreet(name) {
  11506. * var deferred = $q.defer();
  11507. *
  11508. * setTimeout(function() {
  11509. * deferred.notify('About to greet ' + name + '.');
  11510. *
  11511. * if (okToGreet(name)) {
  11512. * deferred.resolve('Hello, ' + name + '!');
  11513. * } else {
  11514. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11515. * }
  11516. * }, 1000);
  11517. *
  11518. * return deferred.promise;
  11519. * }
  11520. *
  11521. * var promise = asyncGreet('Robin Hood');
  11522. * promise.then(function(greeting) {
  11523. * alert('Success: ' + greeting);
  11524. * }, function(reason) {
  11525. * alert('Failed: ' + reason);
  11526. * }, function(update) {
  11527. * alert('Got notification: ' + update);
  11528. * });
  11529. * ```
  11530. *
  11531. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11532. * comes in the way of guarantees that promise and deferred APIs make, see
  11533. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11534. *
  11535. * Additionally the promise api allows for composition that is very hard to do with the
  11536. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11537. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11538. * section on serial or parallel joining of promises.
  11539. *
  11540. * # The Deferred API
  11541. *
  11542. * A new instance of deferred is constructed by calling `$q.defer()`.
  11543. *
  11544. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11545. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11546. * of the task.
  11547. *
  11548. * **Methods**
  11549. *
  11550. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11551. * constructed via `$q.reject`, the promise will be rejected instead.
  11552. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11553. * resolving it with a rejection constructed via `$q.reject`.
  11554. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11555. * multiple times before the promise is either resolved or rejected.
  11556. *
  11557. * **Properties**
  11558. *
  11559. * - promise – `{Promise}` – promise object associated with this deferred.
  11560. *
  11561. *
  11562. * # The Promise API
  11563. *
  11564. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11565. * calling `deferred.promise`.
  11566. *
  11567. * The purpose of the promise object is to allow for interested parties to get access to the result
  11568. * of the deferred task when it completes.
  11569. *
  11570. * **Methods**
  11571. *
  11572. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11573. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11574. * as soon as the result is available. The callbacks are called with a single argument: the result
  11575. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11576. * provide a progress indication, before the promise is resolved or rejected.
  11577. *
  11578. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11579. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11580. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11581. * method.
  11582. *
  11583. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11584. *
  11585. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  11586. * but to do so without modifying the final value. This is useful to release resources or do some
  11587. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11588. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11589. * more information.
  11590. *
  11591. * # Chaining promises
  11592. *
  11593. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11594. * possible to create a chain of promises:
  11595. *
  11596. * ```js
  11597. * promiseB = promiseA.then(function(result) {
  11598. * return result + 1;
  11599. * });
  11600. *
  11601. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11602. * // will be the result of promiseA incremented by 1
  11603. * ```
  11604. *
  11605. * It is possible to create chains of any length and since a promise can be resolved with another
  11606. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11607. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11608. * $http's response interceptors.
  11609. *
  11610. *
  11611. * # Differences between Kris Kowal's Q and $q
  11612. *
  11613. * There are two main differences:
  11614. *
  11615. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11616. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11617. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11618. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11619. * all the important functionality needed for common async tasks.
  11620. *
  11621. * # Testing
  11622. *
  11623. * ```js
  11624. * it('should simulate promise', inject(function($q, $rootScope) {
  11625. * var deferred = $q.defer();
  11626. * var promise = deferred.promise;
  11627. * var resolvedValue;
  11628. *
  11629. * promise.then(function(value) { resolvedValue = value; });
  11630. * expect(resolvedValue).toBeUndefined();
  11631. *
  11632. * // Simulate resolving of promise
  11633. * deferred.resolve(123);
  11634. * // Note that the 'then' function does not get called synchronously.
  11635. * // This is because we want the promise API to always be async, whether or not
  11636. * // it got called synchronously or asynchronously.
  11637. * expect(resolvedValue).toBeUndefined();
  11638. *
  11639. * // Propagate promise resolution to 'then' functions using $apply().
  11640. * $rootScope.$apply();
  11641. * expect(resolvedValue).toEqual(123);
  11642. * }));
  11643. * ```
  11644. *
  11645. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11646. * rejecting the newly created promise. The first parameter is a function which resolves the
  11647. * promise, the second parameter is a function which rejects the promise.
  11648. *
  11649. * @returns {Promise} The newly created promise.
  11650. */
  11651. function $QProvider() {
  11652. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11653. return qFactory(function(callback) {
  11654. $rootScope.$evalAsync(callback);
  11655. }, $exceptionHandler);
  11656. }];
  11657. }
  11658. function $$QProvider() {
  11659. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11660. return qFactory(function(callback) {
  11661. $browser.defer(callback);
  11662. }, $exceptionHandler);
  11663. }];
  11664. }
  11665. /**
  11666. * Constructs a promise manager.
  11667. *
  11668. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11669. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11670. * debugging purposes.
  11671. * @returns {object} Promise manager.
  11672. */
  11673. function qFactory(nextTick, exceptionHandler) {
  11674. var $qMinErr = minErr('$q', TypeError);
  11675. function callOnce(self, resolveFn, rejectFn) {
  11676. var called = false;
  11677. function wrap(fn) {
  11678. return function(value) {
  11679. if (called) return;
  11680. called = true;
  11681. fn.call(self, value);
  11682. };
  11683. }
  11684. return [wrap(resolveFn), wrap(rejectFn)];
  11685. }
  11686. /**
  11687. * @ngdoc method
  11688. * @name ng.$q#defer
  11689. * @kind function
  11690. *
  11691. * @description
  11692. * Creates a `Deferred` object which represents a task which will finish in the future.
  11693. *
  11694. * @returns {Deferred} Returns a new instance of deferred.
  11695. */
  11696. var defer = function() {
  11697. return new Deferred();
  11698. };
  11699. function Promise() {
  11700. this.$$state = { status: 0 };
  11701. }
  11702. Promise.prototype = {
  11703. then: function(onFulfilled, onRejected, progressBack) {
  11704. var result = new Deferred();
  11705. this.$$state.pending = this.$$state.pending || [];
  11706. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11707. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11708. return result.promise;
  11709. },
  11710. "catch": function(callback) {
  11711. return this.then(null, callback);
  11712. },
  11713. "finally": function(callback, progressBack) {
  11714. return this.then(function(value) {
  11715. return handleCallback(value, true, callback);
  11716. }, function(error) {
  11717. return handleCallback(error, false, callback);
  11718. }, progressBack);
  11719. }
  11720. };
  11721. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11722. function simpleBind(context, fn) {
  11723. return function(value) {
  11724. fn.call(context, value);
  11725. };
  11726. }
  11727. function processQueue(state) {
  11728. var fn, promise, pending;
  11729. pending = state.pending;
  11730. state.processScheduled = false;
  11731. state.pending = undefined;
  11732. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11733. promise = pending[i][0];
  11734. fn = pending[i][state.status];
  11735. try {
  11736. if (isFunction(fn)) {
  11737. promise.resolve(fn(state.value));
  11738. } else if (state.status === 1) {
  11739. promise.resolve(state.value);
  11740. } else {
  11741. promise.reject(state.value);
  11742. }
  11743. } catch (e) {
  11744. promise.reject(e);
  11745. exceptionHandler(e);
  11746. }
  11747. }
  11748. }
  11749. function scheduleProcessQueue(state) {
  11750. if (state.processScheduled || !state.pending) return;
  11751. state.processScheduled = true;
  11752. nextTick(function() { processQueue(state); });
  11753. }
  11754. function Deferred() {
  11755. this.promise = new Promise();
  11756. //Necessary to support unbound execution :/
  11757. this.resolve = simpleBind(this, this.resolve);
  11758. this.reject = simpleBind(this, this.reject);
  11759. this.notify = simpleBind(this, this.notify);
  11760. }
  11761. Deferred.prototype = {
  11762. resolve: function(val) {
  11763. if (this.promise.$$state.status) return;
  11764. if (val === this.promise) {
  11765. this.$$reject($qMinErr(
  11766. 'qcycle',
  11767. "Expected promise to be resolved with value other than itself '{0}'",
  11768. val));
  11769. }
  11770. else {
  11771. this.$$resolve(val);
  11772. }
  11773. },
  11774. $$resolve: function(val) {
  11775. var then, fns;
  11776. fns = callOnce(this, this.$$resolve, this.$$reject);
  11777. try {
  11778. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11779. if (isFunction(then)) {
  11780. this.promise.$$state.status = -1;
  11781. then.call(val, fns[0], fns[1], this.notify);
  11782. } else {
  11783. this.promise.$$state.value = val;
  11784. this.promise.$$state.status = 1;
  11785. scheduleProcessQueue(this.promise.$$state);
  11786. }
  11787. } catch (e) {
  11788. fns[1](e);
  11789. exceptionHandler(e);
  11790. }
  11791. },
  11792. reject: function(reason) {
  11793. if (this.promise.$$state.status) return;
  11794. this.$$reject(reason);
  11795. },
  11796. $$reject: function(reason) {
  11797. this.promise.$$state.value = reason;
  11798. this.promise.$$state.status = 2;
  11799. scheduleProcessQueue(this.promise.$$state);
  11800. },
  11801. notify: function(progress) {
  11802. var callbacks = this.promise.$$state.pending;
  11803. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11804. nextTick(function() {
  11805. var callback, result;
  11806. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11807. result = callbacks[i][0];
  11808. callback = callbacks[i][3];
  11809. try {
  11810. result.notify(isFunction(callback) ? callback(progress) : progress);
  11811. } catch (e) {
  11812. exceptionHandler(e);
  11813. }
  11814. }
  11815. });
  11816. }
  11817. }
  11818. };
  11819. /**
  11820. * @ngdoc method
  11821. * @name $q#reject
  11822. * @kind function
  11823. *
  11824. * @description
  11825. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11826. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11827. * a promise chain, you don't need to worry about it.
  11828. *
  11829. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11830. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11831. * a promise error callback and you want to forward the error to the promise derived from the
  11832. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11833. * `reject`.
  11834. *
  11835. * ```js
  11836. * promiseB = promiseA.then(function(result) {
  11837. * // success: do something and resolve promiseB
  11838. * // with the old or a new result
  11839. * return result;
  11840. * }, function(reason) {
  11841. * // error: handle the error if possible and
  11842. * // resolve promiseB with newPromiseOrValue,
  11843. * // otherwise forward the rejection to promiseB
  11844. * if (canHandle(reason)) {
  11845. * // handle the error and recover
  11846. * return newPromiseOrValue;
  11847. * }
  11848. * return $q.reject(reason);
  11849. * });
  11850. * ```
  11851. *
  11852. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  11853. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  11854. */
  11855. var reject = function(reason) {
  11856. var result = new Deferred();
  11857. result.reject(reason);
  11858. return result.promise;
  11859. };
  11860. var makePromise = function makePromise(value, resolved) {
  11861. var result = new Deferred();
  11862. if (resolved) {
  11863. result.resolve(value);
  11864. } else {
  11865. result.reject(value);
  11866. }
  11867. return result.promise;
  11868. };
  11869. var handleCallback = function handleCallback(value, isResolved, callback) {
  11870. var callbackOutput = null;
  11871. try {
  11872. if (isFunction(callback)) callbackOutput = callback();
  11873. } catch (e) {
  11874. return makePromise(e, false);
  11875. }
  11876. if (isPromiseLike(callbackOutput)) {
  11877. return callbackOutput.then(function() {
  11878. return makePromise(value, isResolved);
  11879. }, function(error) {
  11880. return makePromise(error, false);
  11881. });
  11882. } else {
  11883. return makePromise(value, isResolved);
  11884. }
  11885. };
  11886. /**
  11887. * @ngdoc method
  11888. * @name $q#when
  11889. * @kind function
  11890. *
  11891. * @description
  11892. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  11893. * This is useful when you are dealing with an object that might or might not be a promise, or if
  11894. * the promise comes from a source that can't be trusted.
  11895. *
  11896. * @param {*} value Value or a promise
  11897. * @returns {Promise} Returns a promise of the passed value or promise
  11898. */
  11899. var when = function(value, callback, errback, progressBack) {
  11900. var result = new Deferred();
  11901. result.resolve(value);
  11902. return result.promise.then(callback, errback, progressBack);
  11903. };
  11904. /**
  11905. * @ngdoc method
  11906. * @name $q#all
  11907. * @kind function
  11908. *
  11909. * @description
  11910. * Combines multiple promises into a single promise that is resolved when all of the input
  11911. * promises are resolved.
  11912. *
  11913. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  11914. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  11915. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  11916. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  11917. * with the same rejection value.
  11918. */
  11919. function all(promises) {
  11920. var deferred = new Deferred(),
  11921. counter = 0,
  11922. results = isArray(promises) ? [] : {};
  11923. forEach(promises, function(promise, key) {
  11924. counter++;
  11925. when(promise).then(function(value) {
  11926. if (results.hasOwnProperty(key)) return;
  11927. results[key] = value;
  11928. if (!(--counter)) deferred.resolve(results);
  11929. }, function(reason) {
  11930. if (results.hasOwnProperty(key)) return;
  11931. deferred.reject(reason);
  11932. });
  11933. });
  11934. if (counter === 0) {
  11935. deferred.resolve(results);
  11936. }
  11937. return deferred.promise;
  11938. }
  11939. var $Q = function Q(resolver) {
  11940. if (!isFunction(resolver)) {
  11941. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  11942. }
  11943. if (!(this instanceof Q)) {
  11944. // More useful when $Q is the Promise itself.
  11945. return new Q(resolver);
  11946. }
  11947. var deferred = new Deferred();
  11948. function resolveFn(value) {
  11949. deferred.resolve(value);
  11950. }
  11951. function rejectFn(reason) {
  11952. deferred.reject(reason);
  11953. }
  11954. resolver(resolveFn, rejectFn);
  11955. return deferred.promise;
  11956. };
  11957. $Q.defer = defer;
  11958. $Q.reject = reject;
  11959. $Q.when = when;
  11960. $Q.all = all;
  11961. return $Q;
  11962. }
  11963. function $$RAFProvider() { //rAF
  11964. this.$get = ['$window', '$timeout', function($window, $timeout) {
  11965. var requestAnimationFrame = $window.requestAnimationFrame ||
  11966. $window.webkitRequestAnimationFrame ||
  11967. $window.mozRequestAnimationFrame;
  11968. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  11969. $window.webkitCancelAnimationFrame ||
  11970. $window.mozCancelAnimationFrame ||
  11971. $window.webkitCancelRequestAnimationFrame;
  11972. var rafSupported = !!requestAnimationFrame;
  11973. var raf = rafSupported
  11974. ? function(fn) {
  11975. var id = requestAnimationFrame(fn);
  11976. return function() {
  11977. cancelAnimationFrame(id);
  11978. };
  11979. }
  11980. : function(fn) {
  11981. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  11982. return function() {
  11983. $timeout.cancel(timer);
  11984. };
  11985. };
  11986. raf.supported = rafSupported;
  11987. return raf;
  11988. }];
  11989. }
  11990. /**
  11991. * DESIGN NOTES
  11992. *
  11993. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  11994. *
  11995. * The typical use of scope is to watch the expressions, which most of the time return the same
  11996. * value as last time so we optimize the operation.
  11997. *
  11998. * Closures construction is expensive in terms of speed as well as memory:
  11999. * - No closures, instead use prototypical inheritance for API
  12000. * - Internal state needs to be stored on scope directly, which means that private state is
  12001. * exposed as $$____ properties
  12002. *
  12003. * Loop operations are optimized by using while(count--) { ... }
  12004. * - this means that in order to keep the same order of execution as addition we have to add
  12005. * items to the array at the beginning (unshift) instead of at the end (push)
  12006. *
  12007. * Child scopes are created and removed often
  12008. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  12009. *
  12010. * There are few watches then a lot of observers. This is why you don't want the observer to be
  12011. * implemented in the same way as watch. Watch requires return of initialization function which
  12012. * are expensive to construct.
  12013. */
  12014. /**
  12015. * @ngdoc provider
  12016. * @name $rootScopeProvider
  12017. * @description
  12018. *
  12019. * Provider for the $rootScope service.
  12020. */
  12021. /**
  12022. * @ngdoc method
  12023. * @name $rootScopeProvider#digestTtl
  12024. * @description
  12025. *
  12026. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  12027. * assuming that the model is unstable.
  12028. *
  12029. * The current default is 10 iterations.
  12030. *
  12031. * In complex applications it's possible that the dependencies between `$watch`s will result in
  12032. * several digest iterations. However if an application needs more than the default 10 digest
  12033. * iterations for its model to stabilize then you should investigate what is causing the model to
  12034. * continuously change during the digest.
  12035. *
  12036. * Increasing the TTL could have performance implications, so you should not change it without
  12037. * proper justification.
  12038. *
  12039. * @param {number} limit The number of digest iterations.
  12040. */
  12041. /**
  12042. * @ngdoc service
  12043. * @name $rootScope
  12044. * @description
  12045. *
  12046. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  12047. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  12048. * between the model and the view, via a mechanism for watching the model for changes.
  12049. * They also provide an event emission/broadcast and subscription facility. See the
  12050. * {@link guide/scope developer guide on scopes}.
  12051. */
  12052. function $RootScopeProvider() {
  12053. var TTL = 10;
  12054. var $rootScopeMinErr = minErr('$rootScope');
  12055. var lastDirtyWatch = null;
  12056. var applyAsyncId = null;
  12057. this.digestTtl = function(value) {
  12058. if (arguments.length) {
  12059. TTL = value;
  12060. }
  12061. return TTL;
  12062. };
  12063. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  12064. function($injector, $exceptionHandler, $parse, $browser) {
  12065. /**
  12066. * @ngdoc type
  12067. * @name $rootScope.Scope
  12068. *
  12069. * @description
  12070. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  12071. * {@link auto.$injector $injector}. Child scopes are created using the
  12072. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  12073. * compiled HTML template is executed.)
  12074. *
  12075. * Here is a simple scope snippet to show how you can interact with the scope.
  12076. * ```html
  12077. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  12078. * ```
  12079. *
  12080. * # Inheritance
  12081. * A scope can inherit from a parent scope, as in this example:
  12082. * ```js
  12083. var parent = $rootScope;
  12084. var child = parent.$new();
  12085. parent.salutation = "Hello";
  12086. child.name = "World";
  12087. expect(child.salutation).toEqual('Hello');
  12088. child.salutation = "Welcome";
  12089. expect(child.salutation).toEqual('Welcome');
  12090. expect(parent.salutation).toEqual('Hello');
  12091. * ```
  12092. *
  12093. * When interacting with `Scope` in tests, additional helper methods are available on the
  12094. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12095. * details.
  12096. *
  12097. *
  12098. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12099. * provided for the current scope. Defaults to {@link ng}.
  12100. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12101. * append/override services provided by `providers`. This is handy
  12102. * when unit-testing and having the need to override a default
  12103. * service.
  12104. * @returns {Object} Newly created scope.
  12105. *
  12106. */
  12107. function Scope() {
  12108. this.$id = nextUid();
  12109. this.$$phase = this.$parent = this.$$watchers =
  12110. this.$$nextSibling = this.$$prevSibling =
  12111. this.$$childHead = this.$$childTail = null;
  12112. this.$root = this;
  12113. this.$$destroyed = false;
  12114. this.$$listeners = {};
  12115. this.$$listenerCount = {};
  12116. this.$$isolateBindings = null;
  12117. }
  12118. /**
  12119. * @ngdoc property
  12120. * @name $rootScope.Scope#$id
  12121. *
  12122. * @description
  12123. * Unique scope ID (monotonically increasing) useful for debugging.
  12124. */
  12125. /**
  12126. * @ngdoc property
  12127. * @name $rootScope.Scope#$parent
  12128. *
  12129. * @description
  12130. * Reference to the parent scope.
  12131. */
  12132. /**
  12133. * @ngdoc property
  12134. * @name $rootScope.Scope#$root
  12135. *
  12136. * @description
  12137. * Reference to the root scope.
  12138. */
  12139. Scope.prototype = {
  12140. constructor: Scope,
  12141. /**
  12142. * @ngdoc method
  12143. * @name $rootScope.Scope#$new
  12144. * @kind function
  12145. *
  12146. * @description
  12147. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12148. *
  12149. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12150. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12151. *
  12152. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12153. * desired for the scope and its child scopes to be permanently detached from the parent and
  12154. * thus stop participating in model change detection and listener notification by invoking.
  12155. *
  12156. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12157. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12158. * When creating widgets, it is useful for the widget to not accidentally read parent
  12159. * state.
  12160. *
  12161. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12162. * of the newly created scope. Defaults to `this` scope if not provided.
  12163. * This is used when creating a transclude scope to correctly place it
  12164. * in the scope hierarchy while maintaining the correct prototypical
  12165. * inheritance.
  12166. *
  12167. * @returns {Object} The newly created child scope.
  12168. *
  12169. */
  12170. $new: function(isolate, parent) {
  12171. var child;
  12172. parent = parent || this;
  12173. if (isolate) {
  12174. child = new Scope();
  12175. child.$root = this.$root;
  12176. } else {
  12177. // Only create a child scope class if somebody asks for one,
  12178. // but cache it to allow the VM to optimize lookups.
  12179. if (!this.$$ChildScope) {
  12180. this.$$ChildScope = function ChildScope() {
  12181. this.$$watchers = this.$$nextSibling =
  12182. this.$$childHead = this.$$childTail = null;
  12183. this.$$listeners = {};
  12184. this.$$listenerCount = {};
  12185. this.$id = nextUid();
  12186. this.$$ChildScope = null;
  12187. };
  12188. this.$$ChildScope.prototype = this;
  12189. }
  12190. child = new this.$$ChildScope();
  12191. }
  12192. child.$parent = parent;
  12193. child.$$prevSibling = parent.$$childTail;
  12194. if (parent.$$childHead) {
  12195. parent.$$childTail.$$nextSibling = child;
  12196. parent.$$childTail = child;
  12197. } else {
  12198. parent.$$childHead = parent.$$childTail = child;
  12199. }
  12200. // When the new scope is not isolated or we inherit from `this`, and
  12201. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12202. // prototypically. In all other cases, this property needs to be set
  12203. // when the parent scope is destroyed.
  12204. // The listener needs to be added after the parent is set
  12205. if (isolate || parent != this) child.$on('$destroy', destroyChild);
  12206. return child;
  12207. function destroyChild() {
  12208. child.$$destroyed = true;
  12209. }
  12210. },
  12211. /**
  12212. * @ngdoc method
  12213. * @name $rootScope.Scope#$watch
  12214. * @kind function
  12215. *
  12216. * @description
  12217. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12218. *
  12219. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12220. * $digest()} and should return the value that will be watched. (Since
  12221. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12222. * `watchExpression` can execute multiple times per
  12223. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12224. * - The `listener` is called only when the value from the current `watchExpression` and the
  12225. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12226. * see below). Inequality is determined according to reference inequality,
  12227. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12228. * via the `!==` Javascript operator, unless `objectEquality == true`
  12229. * (see next point)
  12230. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12231. * according to the {@link angular.equals} function. To save the value of the object for
  12232. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12233. * watching complex objects will have adverse memory and performance implications.
  12234. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12235. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12236. * iteration limit is 10 to prevent an infinite loop deadlock.
  12237. *
  12238. *
  12239. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12240. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12241. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12242. * change is detected, be prepared for multiple calls to your listener.)
  12243. *
  12244. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12245. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12246. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12247. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12248. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12249. * listener was called due to initialization.
  12250. *
  12251. *
  12252. *
  12253. * # Example
  12254. * ```js
  12255. // let's assume that scope was dependency injected as the $rootScope
  12256. var scope = $rootScope;
  12257. scope.name = 'misko';
  12258. scope.counter = 0;
  12259. expect(scope.counter).toEqual(0);
  12260. scope.$watch('name', function(newValue, oldValue) {
  12261. scope.counter = scope.counter + 1;
  12262. });
  12263. expect(scope.counter).toEqual(0);
  12264. scope.$digest();
  12265. // the listener is always called during the first $digest loop after it was registered
  12266. expect(scope.counter).toEqual(1);
  12267. scope.$digest();
  12268. // but now it will not be called unless the value changes
  12269. expect(scope.counter).toEqual(1);
  12270. scope.name = 'adam';
  12271. scope.$digest();
  12272. expect(scope.counter).toEqual(2);
  12273. // Using a function as a watchExpression
  12274. var food;
  12275. scope.foodCounter = 0;
  12276. expect(scope.foodCounter).toEqual(0);
  12277. scope.$watch(
  12278. // This function returns the value being watched. It is called for each turn of the $digest loop
  12279. function() { return food; },
  12280. // This is the change listener, called when the value returned from the above function changes
  12281. function(newValue, oldValue) {
  12282. if ( newValue !== oldValue ) {
  12283. // Only increment the counter if the value changed
  12284. scope.foodCounter = scope.foodCounter + 1;
  12285. }
  12286. }
  12287. );
  12288. // No digest has been run so the counter will be zero
  12289. expect(scope.foodCounter).toEqual(0);
  12290. // Run the digest but since food has not changed count will still be zero
  12291. scope.$digest();
  12292. expect(scope.foodCounter).toEqual(0);
  12293. // Update food and run digest. Now the counter will increment
  12294. food = 'cheeseburger';
  12295. scope.$digest();
  12296. expect(scope.foodCounter).toEqual(1);
  12297. * ```
  12298. *
  12299. *
  12300. *
  12301. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12302. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12303. * a call to the `listener`.
  12304. *
  12305. * - `string`: Evaluated as {@link guide/expression expression}
  12306. * - `function(scope)`: called with current `scope` as a parameter.
  12307. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12308. * of `watchExpression` changes.
  12309. *
  12310. * - `newVal` contains the current value of the `watchExpression`
  12311. * - `oldVal` contains the previous value of the `watchExpression`
  12312. * - `scope` refers to the current scope
  12313. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12314. * comparing for reference equality.
  12315. * @returns {function()} Returns a deregistration function for this listener.
  12316. */
  12317. $watch: function(watchExp, listener, objectEquality) {
  12318. var get = $parse(watchExp);
  12319. if (get.$$watchDelegate) {
  12320. return get.$$watchDelegate(this, listener, objectEquality, get);
  12321. }
  12322. var scope = this,
  12323. array = scope.$$watchers,
  12324. watcher = {
  12325. fn: listener,
  12326. last: initWatchVal,
  12327. get: get,
  12328. exp: watchExp,
  12329. eq: !!objectEquality
  12330. };
  12331. lastDirtyWatch = null;
  12332. if (!isFunction(listener)) {
  12333. watcher.fn = noop;
  12334. }
  12335. if (!array) {
  12336. array = scope.$$watchers = [];
  12337. }
  12338. // we use unshift since we use a while loop in $digest for speed.
  12339. // the while loop reads in reverse order.
  12340. array.unshift(watcher);
  12341. return function deregisterWatch() {
  12342. arrayRemove(array, watcher);
  12343. lastDirtyWatch = null;
  12344. };
  12345. },
  12346. /**
  12347. * @ngdoc method
  12348. * @name $rootScope.Scope#$watchGroup
  12349. * @kind function
  12350. *
  12351. * @description
  12352. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12353. * If any one expression in the collection changes the `listener` is executed.
  12354. *
  12355. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12356. * call to $digest() to see if any items changes.
  12357. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12358. *
  12359. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12360. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12361. *
  12362. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12363. * expression in `watchExpressions` changes
  12364. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12365. * those of `watchExpression`
  12366. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12367. * those of `watchExpression`
  12368. * The `scope` refers to the current scope.
  12369. * @returns {function()} Returns a de-registration function for all listeners.
  12370. */
  12371. $watchGroup: function(watchExpressions, listener) {
  12372. var oldValues = new Array(watchExpressions.length);
  12373. var newValues = new Array(watchExpressions.length);
  12374. var deregisterFns = [];
  12375. var self = this;
  12376. var changeReactionScheduled = false;
  12377. var firstRun = true;
  12378. if (!watchExpressions.length) {
  12379. // No expressions means we call the listener ASAP
  12380. var shouldCall = true;
  12381. self.$evalAsync(function() {
  12382. if (shouldCall) listener(newValues, newValues, self);
  12383. });
  12384. return function deregisterWatchGroup() {
  12385. shouldCall = false;
  12386. };
  12387. }
  12388. if (watchExpressions.length === 1) {
  12389. // Special case size of one
  12390. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12391. newValues[0] = value;
  12392. oldValues[0] = oldValue;
  12393. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12394. });
  12395. }
  12396. forEach(watchExpressions, function(expr, i) {
  12397. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12398. newValues[i] = value;
  12399. oldValues[i] = oldValue;
  12400. if (!changeReactionScheduled) {
  12401. changeReactionScheduled = true;
  12402. self.$evalAsync(watchGroupAction);
  12403. }
  12404. });
  12405. deregisterFns.push(unwatchFn);
  12406. });
  12407. function watchGroupAction() {
  12408. changeReactionScheduled = false;
  12409. if (firstRun) {
  12410. firstRun = false;
  12411. listener(newValues, newValues, self);
  12412. } else {
  12413. listener(newValues, oldValues, self);
  12414. }
  12415. }
  12416. return function deregisterWatchGroup() {
  12417. while (deregisterFns.length) {
  12418. deregisterFns.shift()();
  12419. }
  12420. };
  12421. },
  12422. /**
  12423. * @ngdoc method
  12424. * @name $rootScope.Scope#$watchCollection
  12425. * @kind function
  12426. *
  12427. * @description
  12428. * Shallow watches the properties of an object and fires whenever any of the properties change
  12429. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12430. * the properties). If a change is detected, the `listener` callback is fired.
  12431. *
  12432. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12433. * call to $digest() to see if any items have been added, removed, or moved.
  12434. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12435. * adding, removing, and moving items belonging to an object or array.
  12436. *
  12437. *
  12438. * # Example
  12439. * ```js
  12440. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12441. $scope.dataCount = 4;
  12442. $scope.$watchCollection('names', function(newNames, oldNames) {
  12443. $scope.dataCount = newNames.length;
  12444. });
  12445. expect($scope.dataCount).toEqual(4);
  12446. $scope.$digest();
  12447. //still at 4 ... no changes
  12448. expect($scope.dataCount).toEqual(4);
  12449. $scope.names.pop();
  12450. $scope.$digest();
  12451. //now there's been a change
  12452. expect($scope.dataCount).toEqual(3);
  12453. * ```
  12454. *
  12455. *
  12456. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12457. * expression value should evaluate to an object or an array which is observed on each
  12458. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12459. * collection will trigger a call to the `listener`.
  12460. *
  12461. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12462. * when a change is detected.
  12463. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12464. * - The `oldCollection` object is a copy of the former collection data.
  12465. * Due to performance considerations, the`oldCollection` value is computed only if the
  12466. * `listener` function declares two or more arguments.
  12467. * - The `scope` argument refers to the current scope.
  12468. *
  12469. * @returns {function()} Returns a de-registration function for this listener. When the
  12470. * de-registration function is executed, the internal watch operation is terminated.
  12471. */
  12472. $watchCollection: function(obj, listener) {
  12473. $watchCollectionInterceptor.$stateful = true;
  12474. var self = this;
  12475. // the current value, updated on each dirty-check run
  12476. var newValue;
  12477. // a shallow copy of the newValue from the last dirty-check run,
  12478. // updated to match newValue during dirty-check run
  12479. var oldValue;
  12480. // a shallow copy of the newValue from when the last change happened
  12481. var veryOldValue;
  12482. // only track veryOldValue if the listener is asking for it
  12483. var trackVeryOldValue = (listener.length > 1);
  12484. var changeDetected = 0;
  12485. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12486. var internalArray = [];
  12487. var internalObject = {};
  12488. var initRun = true;
  12489. var oldLength = 0;
  12490. function $watchCollectionInterceptor(_value) {
  12491. newValue = _value;
  12492. var newLength, key, bothNaN, newItem, oldItem;
  12493. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12494. if (isUndefined(newValue)) return;
  12495. if (!isObject(newValue)) { // if primitive
  12496. if (oldValue !== newValue) {
  12497. oldValue = newValue;
  12498. changeDetected++;
  12499. }
  12500. } else if (isArrayLike(newValue)) {
  12501. if (oldValue !== internalArray) {
  12502. // we are transitioning from something which was not an array into array.
  12503. oldValue = internalArray;
  12504. oldLength = oldValue.length = 0;
  12505. changeDetected++;
  12506. }
  12507. newLength = newValue.length;
  12508. if (oldLength !== newLength) {
  12509. // if lengths do not match we need to trigger change notification
  12510. changeDetected++;
  12511. oldValue.length = oldLength = newLength;
  12512. }
  12513. // copy the items to oldValue and look for changes.
  12514. for (var i = 0; i < newLength; i++) {
  12515. oldItem = oldValue[i];
  12516. newItem = newValue[i];
  12517. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12518. if (!bothNaN && (oldItem !== newItem)) {
  12519. changeDetected++;
  12520. oldValue[i] = newItem;
  12521. }
  12522. }
  12523. } else {
  12524. if (oldValue !== internalObject) {
  12525. // we are transitioning from something which was not an object into object.
  12526. oldValue = internalObject = {};
  12527. oldLength = 0;
  12528. changeDetected++;
  12529. }
  12530. // copy the items to oldValue and look for changes.
  12531. newLength = 0;
  12532. for (key in newValue) {
  12533. if (newValue.hasOwnProperty(key)) {
  12534. newLength++;
  12535. newItem = newValue[key];
  12536. oldItem = oldValue[key];
  12537. if (key in oldValue) {
  12538. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12539. if (!bothNaN && (oldItem !== newItem)) {
  12540. changeDetected++;
  12541. oldValue[key] = newItem;
  12542. }
  12543. } else {
  12544. oldLength++;
  12545. oldValue[key] = newItem;
  12546. changeDetected++;
  12547. }
  12548. }
  12549. }
  12550. if (oldLength > newLength) {
  12551. // we used to have more keys, need to find them and destroy them.
  12552. changeDetected++;
  12553. for (key in oldValue) {
  12554. if (!newValue.hasOwnProperty(key)) {
  12555. oldLength--;
  12556. delete oldValue[key];
  12557. }
  12558. }
  12559. }
  12560. }
  12561. return changeDetected;
  12562. }
  12563. function $watchCollectionAction() {
  12564. if (initRun) {
  12565. initRun = false;
  12566. listener(newValue, newValue, self);
  12567. } else {
  12568. listener(newValue, veryOldValue, self);
  12569. }
  12570. // make a copy for the next time a collection is changed
  12571. if (trackVeryOldValue) {
  12572. if (!isObject(newValue)) {
  12573. //primitive
  12574. veryOldValue = newValue;
  12575. } else if (isArrayLike(newValue)) {
  12576. veryOldValue = new Array(newValue.length);
  12577. for (var i = 0; i < newValue.length; i++) {
  12578. veryOldValue[i] = newValue[i];
  12579. }
  12580. } else { // if object
  12581. veryOldValue = {};
  12582. for (var key in newValue) {
  12583. if (hasOwnProperty.call(newValue, key)) {
  12584. veryOldValue[key] = newValue[key];
  12585. }
  12586. }
  12587. }
  12588. }
  12589. }
  12590. return this.$watch(changeDetector, $watchCollectionAction);
  12591. },
  12592. /**
  12593. * @ngdoc method
  12594. * @name $rootScope.Scope#$digest
  12595. * @kind function
  12596. *
  12597. * @description
  12598. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12599. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12600. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12601. * until no more listeners are firing. This means that it is possible to get into an infinite
  12602. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12603. * iterations exceeds 10.
  12604. *
  12605. * Usually, you don't call `$digest()` directly in
  12606. * {@link ng.directive:ngController controllers} or in
  12607. * {@link ng.$compileProvider#directive directives}.
  12608. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12609. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12610. *
  12611. * If you want to be notified whenever `$digest()` is called,
  12612. * you can register a `watchExpression` function with
  12613. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12614. *
  12615. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12616. *
  12617. * # Example
  12618. * ```js
  12619. var scope = ...;
  12620. scope.name = 'misko';
  12621. scope.counter = 0;
  12622. expect(scope.counter).toEqual(0);
  12623. scope.$watch('name', function(newValue, oldValue) {
  12624. scope.counter = scope.counter + 1;
  12625. });
  12626. expect(scope.counter).toEqual(0);
  12627. scope.$digest();
  12628. // the listener is always called during the first $digest loop after it was registered
  12629. expect(scope.counter).toEqual(1);
  12630. scope.$digest();
  12631. // but now it will not be called unless the value changes
  12632. expect(scope.counter).toEqual(1);
  12633. scope.name = 'adam';
  12634. scope.$digest();
  12635. expect(scope.counter).toEqual(2);
  12636. * ```
  12637. *
  12638. */
  12639. $digest: function() {
  12640. var watch, value, last,
  12641. watchers,
  12642. length,
  12643. dirty, ttl = TTL,
  12644. next, current, target = this,
  12645. watchLog = [],
  12646. logIdx, logMsg, asyncTask;
  12647. beginPhase('$digest');
  12648. // Check for changes to browser url that happened in sync before the call to $digest
  12649. $browser.$$checkUrlChange();
  12650. if (this === $rootScope && applyAsyncId !== null) {
  12651. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12652. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12653. $browser.defer.cancel(applyAsyncId);
  12654. flushApplyAsync();
  12655. }
  12656. lastDirtyWatch = null;
  12657. do { // "while dirty" loop
  12658. dirty = false;
  12659. current = target;
  12660. while (asyncQueue.length) {
  12661. try {
  12662. asyncTask = asyncQueue.shift();
  12663. asyncTask.scope.$eval(asyncTask.expression);
  12664. } catch (e) {
  12665. $exceptionHandler(e);
  12666. }
  12667. lastDirtyWatch = null;
  12668. }
  12669. traverseScopesLoop:
  12670. do { // "traverse the scopes" loop
  12671. if ((watchers = current.$$watchers)) {
  12672. // process our watches
  12673. length = watchers.length;
  12674. while (length--) {
  12675. try {
  12676. watch = watchers[length];
  12677. // Most common watches are on primitives, in which case we can short
  12678. // circuit it with === operator, only when === fails do we use .equals
  12679. if (watch) {
  12680. if ((value = watch.get(current)) !== (last = watch.last) &&
  12681. !(watch.eq
  12682. ? equals(value, last)
  12683. : (typeof value === 'number' && typeof last === 'number'
  12684. && isNaN(value) && isNaN(last)))) {
  12685. dirty = true;
  12686. lastDirtyWatch = watch;
  12687. watch.last = watch.eq ? copy(value, null) : value;
  12688. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12689. if (ttl < 5) {
  12690. logIdx = 4 - ttl;
  12691. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12692. watchLog[logIdx].push({
  12693. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  12694. newVal: value,
  12695. oldVal: last
  12696. });
  12697. }
  12698. } else if (watch === lastDirtyWatch) {
  12699. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12700. // have already been tested.
  12701. dirty = false;
  12702. break traverseScopesLoop;
  12703. }
  12704. }
  12705. } catch (e) {
  12706. $exceptionHandler(e);
  12707. }
  12708. }
  12709. }
  12710. // Insanity Warning: scope depth-first traversal
  12711. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12712. // this piece should be kept in sync with the traversal in $broadcast
  12713. if (!(next = (current.$$childHead ||
  12714. (current !== target && current.$$nextSibling)))) {
  12715. while (current !== target && !(next = current.$$nextSibling)) {
  12716. current = current.$parent;
  12717. }
  12718. }
  12719. } while ((current = next));
  12720. // `break traverseScopesLoop;` takes us to here
  12721. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12722. clearPhase();
  12723. throw $rootScopeMinErr('infdig',
  12724. '{0} $digest() iterations reached. Aborting!\n' +
  12725. 'Watchers fired in the last 5 iterations: {1}',
  12726. TTL, watchLog);
  12727. }
  12728. } while (dirty || asyncQueue.length);
  12729. clearPhase();
  12730. while (postDigestQueue.length) {
  12731. try {
  12732. postDigestQueue.shift()();
  12733. } catch (e) {
  12734. $exceptionHandler(e);
  12735. }
  12736. }
  12737. },
  12738. /**
  12739. * @ngdoc event
  12740. * @name $rootScope.Scope#$destroy
  12741. * @eventType broadcast on scope being destroyed
  12742. *
  12743. * @description
  12744. * Broadcasted when a scope and its children are being destroyed.
  12745. *
  12746. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12747. * clean up DOM bindings before an element is removed from the DOM.
  12748. */
  12749. /**
  12750. * @ngdoc method
  12751. * @name $rootScope.Scope#$destroy
  12752. * @kind function
  12753. *
  12754. * @description
  12755. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12756. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12757. * propagate to the current scope and its children. Removal also implies that the current
  12758. * scope is eligible for garbage collection.
  12759. *
  12760. * The `$destroy()` is usually used by directives such as
  12761. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12762. * unrolling of the loop.
  12763. *
  12764. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12765. * Application code can register a `$destroy` event handler that will give it a chance to
  12766. * perform any necessary cleanup.
  12767. *
  12768. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12769. * clean up DOM bindings before an element is removed from the DOM.
  12770. */
  12771. $destroy: function() {
  12772. // we can't destroy the root scope or a scope that has been already destroyed
  12773. if (this.$$destroyed) return;
  12774. var parent = this.$parent;
  12775. this.$broadcast('$destroy');
  12776. this.$$destroyed = true;
  12777. if (this === $rootScope) return;
  12778. for (var eventName in this.$$listenerCount) {
  12779. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12780. }
  12781. // sever all the references to parent scopes (after this cleanup, the current scope should
  12782. // not be retained by any of our references and should be eligible for garbage collection)
  12783. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12784. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12785. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12786. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12787. // Disable listeners, watchers and apply/digest methods
  12788. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12789. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12790. this.$$listeners = {};
  12791. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12792. // and inline caches.
  12793. //
  12794. // see:
  12795. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12796. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12797. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12798. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12799. this.$$childTail = this.$root = this.$$watchers = null;
  12800. },
  12801. /**
  12802. * @ngdoc method
  12803. * @name $rootScope.Scope#$eval
  12804. * @kind function
  12805. *
  12806. * @description
  12807. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12808. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12809. * expressions.
  12810. *
  12811. * # Example
  12812. * ```js
  12813. var scope = ng.$rootScope.Scope();
  12814. scope.a = 1;
  12815. scope.b = 2;
  12816. expect(scope.$eval('a+b')).toEqual(3);
  12817. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12818. * ```
  12819. *
  12820. * @param {(string|function())=} expression An angular expression to be executed.
  12821. *
  12822. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12823. * - `function(scope)`: execute the function with the current `scope` parameter.
  12824. *
  12825. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12826. * @returns {*} The result of evaluating the expression.
  12827. */
  12828. $eval: function(expr, locals) {
  12829. return $parse(expr)(this, locals);
  12830. },
  12831. /**
  12832. * @ngdoc method
  12833. * @name $rootScope.Scope#$evalAsync
  12834. * @kind function
  12835. *
  12836. * @description
  12837. * Executes the expression on the current scope at a later point in time.
  12838. *
  12839. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12840. * that:
  12841. *
  12842. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  12843. * rendering).
  12844. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  12845. * `expression` execution.
  12846. *
  12847. * Any exceptions from the execution of the expression are forwarded to the
  12848. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12849. *
  12850. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  12851. * will be scheduled. However, it is encouraged to always call code that changes the model
  12852. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  12853. *
  12854. * @param {(string|function())=} expression An angular expression to be executed.
  12855. *
  12856. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12857. * - `function(scope)`: execute the function with the current `scope` parameter.
  12858. *
  12859. */
  12860. $evalAsync: function(expr) {
  12861. // if we are outside of an $digest loop and this is the first time we are scheduling async
  12862. // task also schedule async auto-flush
  12863. if (!$rootScope.$$phase && !asyncQueue.length) {
  12864. $browser.defer(function() {
  12865. if (asyncQueue.length) {
  12866. $rootScope.$digest();
  12867. }
  12868. });
  12869. }
  12870. asyncQueue.push({scope: this, expression: expr});
  12871. },
  12872. $$postDigest: function(fn) {
  12873. postDigestQueue.push(fn);
  12874. },
  12875. /**
  12876. * @ngdoc method
  12877. * @name $rootScope.Scope#$apply
  12878. * @kind function
  12879. *
  12880. * @description
  12881. * `$apply()` is used to execute an expression in angular from outside of the angular
  12882. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  12883. * Because we are calling into the angular framework we need to perform proper scope life
  12884. * cycle of {@link ng.$exceptionHandler exception handling},
  12885. * {@link ng.$rootScope.Scope#$digest executing watches}.
  12886. *
  12887. * ## Life cycle
  12888. *
  12889. * # Pseudo-Code of `$apply()`
  12890. * ```js
  12891. function $apply(expr) {
  12892. try {
  12893. return $eval(expr);
  12894. } catch (e) {
  12895. $exceptionHandler(e);
  12896. } finally {
  12897. $root.$digest();
  12898. }
  12899. }
  12900. * ```
  12901. *
  12902. *
  12903. * Scope's `$apply()` method transitions through the following stages:
  12904. *
  12905. * 1. The {@link guide/expression expression} is executed using the
  12906. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  12907. * 2. Any exceptions from the execution of the expression are forwarded to the
  12908. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12909. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  12910. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  12911. *
  12912. *
  12913. * @param {(string|function())=} exp An angular expression to be executed.
  12914. *
  12915. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12916. * - `function(scope)`: execute the function with current `scope` parameter.
  12917. *
  12918. * @returns {*} The result of evaluating the expression.
  12919. */
  12920. $apply: function(expr) {
  12921. try {
  12922. beginPhase('$apply');
  12923. return this.$eval(expr);
  12924. } catch (e) {
  12925. $exceptionHandler(e);
  12926. } finally {
  12927. clearPhase();
  12928. try {
  12929. $rootScope.$digest();
  12930. } catch (e) {
  12931. $exceptionHandler(e);
  12932. throw e;
  12933. }
  12934. }
  12935. },
  12936. /**
  12937. * @ngdoc method
  12938. * @name $rootScope.Scope#$applyAsync
  12939. * @kind function
  12940. *
  12941. * @description
  12942. * Schedule the invokation of $apply to occur at a later time. The actual time difference
  12943. * varies across browsers, but is typically around ~10 milliseconds.
  12944. *
  12945. * This can be used to queue up multiple expressions which need to be evaluated in the same
  12946. * digest.
  12947. *
  12948. * @param {(string|function())=} exp An angular expression to be executed.
  12949. *
  12950. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12951. * - `function(scope)`: execute the function with current `scope` parameter.
  12952. */
  12953. $applyAsync: function(expr) {
  12954. var scope = this;
  12955. expr && applyAsyncQueue.push($applyAsyncExpression);
  12956. scheduleApplyAsync();
  12957. function $applyAsyncExpression() {
  12958. scope.$eval(expr);
  12959. }
  12960. },
  12961. /**
  12962. * @ngdoc method
  12963. * @name $rootScope.Scope#$on
  12964. * @kind function
  12965. *
  12966. * @description
  12967. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  12968. * discussion of event life cycle.
  12969. *
  12970. * The event listener function format is: `function(event, args...)`. The `event` object
  12971. * passed into the listener has the following attributes:
  12972. *
  12973. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  12974. * `$broadcast`-ed.
  12975. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  12976. * event propagates through the scope hierarchy, this property is set to null.
  12977. * - `name` - `{string}`: name of the event.
  12978. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  12979. * further event propagation (available only for events that were `$emit`-ed).
  12980. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  12981. * to true.
  12982. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  12983. *
  12984. * @param {string} name Event name to listen on.
  12985. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  12986. * @returns {function()} Returns a deregistration function for this listener.
  12987. */
  12988. $on: function(name, listener) {
  12989. var namedListeners = this.$$listeners[name];
  12990. if (!namedListeners) {
  12991. this.$$listeners[name] = namedListeners = [];
  12992. }
  12993. namedListeners.push(listener);
  12994. var current = this;
  12995. do {
  12996. if (!current.$$listenerCount[name]) {
  12997. current.$$listenerCount[name] = 0;
  12998. }
  12999. current.$$listenerCount[name]++;
  13000. } while ((current = current.$parent));
  13001. var self = this;
  13002. return function() {
  13003. var indexOfListener = namedListeners.indexOf(listener);
  13004. if (indexOfListener !== -1) {
  13005. namedListeners[indexOfListener] = null;
  13006. decrementListenerCount(self, 1, name);
  13007. }
  13008. };
  13009. },
  13010. /**
  13011. * @ngdoc method
  13012. * @name $rootScope.Scope#$emit
  13013. * @kind function
  13014. *
  13015. * @description
  13016. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  13017. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13018. *
  13019. * The event life cycle starts at the scope on which `$emit` was called. All
  13020. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13021. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  13022. * registered listeners along the way. The event will stop propagating if one of the listeners
  13023. * cancels it.
  13024. *
  13025. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13026. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13027. *
  13028. * @param {string} name Event name to emit.
  13029. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13030. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  13031. */
  13032. $emit: function(name, args) {
  13033. var empty = [],
  13034. namedListeners,
  13035. scope = this,
  13036. stopPropagation = false,
  13037. event = {
  13038. name: name,
  13039. targetScope: scope,
  13040. stopPropagation: function() {stopPropagation = true;},
  13041. preventDefault: function() {
  13042. event.defaultPrevented = true;
  13043. },
  13044. defaultPrevented: false
  13045. },
  13046. listenerArgs = concat([event], arguments, 1),
  13047. i, length;
  13048. do {
  13049. namedListeners = scope.$$listeners[name] || empty;
  13050. event.currentScope = scope;
  13051. for (i = 0, length = namedListeners.length; i < length; i++) {
  13052. // if listeners were deregistered, defragment the array
  13053. if (!namedListeners[i]) {
  13054. namedListeners.splice(i, 1);
  13055. i--;
  13056. length--;
  13057. continue;
  13058. }
  13059. try {
  13060. //allow all listeners attached to the current scope to run
  13061. namedListeners[i].apply(null, listenerArgs);
  13062. } catch (e) {
  13063. $exceptionHandler(e);
  13064. }
  13065. }
  13066. //if any listener on the current scope stops propagation, prevent bubbling
  13067. if (stopPropagation) {
  13068. event.currentScope = null;
  13069. return event;
  13070. }
  13071. //traverse upwards
  13072. scope = scope.$parent;
  13073. } while (scope);
  13074. event.currentScope = null;
  13075. return event;
  13076. },
  13077. /**
  13078. * @ngdoc method
  13079. * @name $rootScope.Scope#$broadcast
  13080. * @kind function
  13081. *
  13082. * @description
  13083. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13084. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13085. *
  13086. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13087. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13088. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13089. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13090. *
  13091. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13092. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13093. *
  13094. * @param {string} name Event name to broadcast.
  13095. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13096. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13097. */
  13098. $broadcast: function(name, args) {
  13099. var target = this,
  13100. current = target,
  13101. next = target,
  13102. event = {
  13103. name: name,
  13104. targetScope: target,
  13105. preventDefault: function() {
  13106. event.defaultPrevented = true;
  13107. },
  13108. defaultPrevented: false
  13109. };
  13110. if (!target.$$listenerCount[name]) return event;
  13111. var listenerArgs = concat([event], arguments, 1),
  13112. listeners, i, length;
  13113. //down while you can, then up and next sibling or up and next sibling until back at root
  13114. while ((current = next)) {
  13115. event.currentScope = current;
  13116. listeners = current.$$listeners[name] || [];
  13117. for (i = 0, length = listeners.length; i < length; i++) {
  13118. // if listeners were deregistered, defragment the array
  13119. if (!listeners[i]) {
  13120. listeners.splice(i, 1);
  13121. i--;
  13122. length--;
  13123. continue;
  13124. }
  13125. try {
  13126. listeners[i].apply(null, listenerArgs);
  13127. } catch (e) {
  13128. $exceptionHandler(e);
  13129. }
  13130. }
  13131. // Insanity Warning: scope depth-first traversal
  13132. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13133. // this piece should be kept in sync with the traversal in $digest
  13134. // (though it differs due to having the extra check for $$listenerCount)
  13135. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13136. (current !== target && current.$$nextSibling)))) {
  13137. while (current !== target && !(next = current.$$nextSibling)) {
  13138. current = current.$parent;
  13139. }
  13140. }
  13141. }
  13142. event.currentScope = null;
  13143. return event;
  13144. }
  13145. };
  13146. var $rootScope = new Scope();
  13147. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13148. var asyncQueue = $rootScope.$$asyncQueue = [];
  13149. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13150. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13151. return $rootScope;
  13152. function beginPhase(phase) {
  13153. if ($rootScope.$$phase) {
  13154. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13155. }
  13156. $rootScope.$$phase = phase;
  13157. }
  13158. function clearPhase() {
  13159. $rootScope.$$phase = null;
  13160. }
  13161. function decrementListenerCount(current, count, name) {
  13162. do {
  13163. current.$$listenerCount[name] -= count;
  13164. if (current.$$listenerCount[name] === 0) {
  13165. delete current.$$listenerCount[name];
  13166. }
  13167. } while ((current = current.$parent));
  13168. }
  13169. /**
  13170. * function used as an initial value for watchers.
  13171. * because it's unique we can easily tell it apart from other values
  13172. */
  13173. function initWatchVal() {}
  13174. function flushApplyAsync() {
  13175. while (applyAsyncQueue.length) {
  13176. try {
  13177. applyAsyncQueue.shift()();
  13178. } catch (e) {
  13179. $exceptionHandler(e);
  13180. }
  13181. }
  13182. applyAsyncId = null;
  13183. }
  13184. function scheduleApplyAsync() {
  13185. if (applyAsyncId === null) {
  13186. applyAsyncId = $browser.defer(function() {
  13187. $rootScope.$apply(flushApplyAsync);
  13188. });
  13189. }
  13190. }
  13191. }];
  13192. }
  13193. /**
  13194. * @description
  13195. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13196. */
  13197. function $$SanitizeUriProvider() {
  13198. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13199. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13200. /**
  13201. * @description
  13202. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13203. * urls during a[href] sanitization.
  13204. *
  13205. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13206. *
  13207. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13208. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13209. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13210. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13211. *
  13212. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13213. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13214. * chaining otherwise.
  13215. */
  13216. this.aHrefSanitizationWhitelist = function(regexp) {
  13217. if (isDefined(regexp)) {
  13218. aHrefSanitizationWhitelist = regexp;
  13219. return this;
  13220. }
  13221. return aHrefSanitizationWhitelist;
  13222. };
  13223. /**
  13224. * @description
  13225. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13226. * urls during img[src] sanitization.
  13227. *
  13228. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13229. *
  13230. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13231. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13232. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13233. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13234. *
  13235. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13236. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13237. * chaining otherwise.
  13238. */
  13239. this.imgSrcSanitizationWhitelist = function(regexp) {
  13240. if (isDefined(regexp)) {
  13241. imgSrcSanitizationWhitelist = regexp;
  13242. return this;
  13243. }
  13244. return imgSrcSanitizationWhitelist;
  13245. };
  13246. this.$get = function() {
  13247. return function sanitizeUri(uri, isImage) {
  13248. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13249. var normalizedVal;
  13250. normalizedVal = urlResolve(uri).href;
  13251. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13252. return 'unsafe:' + normalizedVal;
  13253. }
  13254. return uri;
  13255. };
  13256. };
  13257. }
  13258. var $sceMinErr = minErr('$sce');
  13259. var SCE_CONTEXTS = {
  13260. HTML: 'html',
  13261. CSS: 'css',
  13262. URL: 'url',
  13263. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13264. // url. (e.g. ng-include, script src, templateUrl)
  13265. RESOURCE_URL: 'resourceUrl',
  13266. JS: 'js'
  13267. };
  13268. // Helper functions follow.
  13269. function adjustMatcher(matcher) {
  13270. if (matcher === 'self') {
  13271. return matcher;
  13272. } else if (isString(matcher)) {
  13273. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13274. // '*' matches any character except those from the set ':/.?&'.
  13275. // '**' matches any character (like .* in a RegExp).
  13276. // More than 2 *'s raises an error as it's ill defined.
  13277. if (matcher.indexOf('***') > -1) {
  13278. throw $sceMinErr('iwcard',
  13279. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13280. }
  13281. matcher = escapeForRegexp(matcher).
  13282. replace('\\*\\*', '.*').
  13283. replace('\\*', '[^:/.?&;]*');
  13284. return new RegExp('^' + matcher + '$');
  13285. } else if (isRegExp(matcher)) {
  13286. // The only other type of matcher allowed is a Regexp.
  13287. // Match entire URL / disallow partial matches.
  13288. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13289. return new RegExp('^' + matcher.source + '$');
  13290. } else {
  13291. throw $sceMinErr('imatcher',
  13292. 'Matchers may only be "self", string patterns or RegExp objects');
  13293. }
  13294. }
  13295. function adjustMatchers(matchers) {
  13296. var adjustedMatchers = [];
  13297. if (isDefined(matchers)) {
  13298. forEach(matchers, function(matcher) {
  13299. adjustedMatchers.push(adjustMatcher(matcher));
  13300. });
  13301. }
  13302. return adjustedMatchers;
  13303. }
  13304. /**
  13305. * @ngdoc service
  13306. * @name $sceDelegate
  13307. * @kind function
  13308. *
  13309. * @description
  13310. *
  13311. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13312. * Contextual Escaping (SCE)} services to AngularJS.
  13313. *
  13314. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13315. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13316. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13317. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13318. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13319. *
  13320. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13321. *
  13322. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13323. * can override it completely to change the behavior of `$sce`, the common case would
  13324. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13325. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13326. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13327. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13328. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13329. */
  13330. /**
  13331. * @ngdoc provider
  13332. * @name $sceDelegateProvider
  13333. * @description
  13334. *
  13335. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13336. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13337. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13338. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13339. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13340. *
  13341. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13342. * Strict Contextual Escaping (SCE)}.
  13343. *
  13344. * **Example**: Consider the following case. <a name="example"></a>
  13345. *
  13346. * - your app is hosted at url `http://myapp.example.com/`
  13347. * - but some of your templates are hosted on other domains you control such as
  13348. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13349. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13350. *
  13351. * Here is what a secure configuration for this scenario might look like:
  13352. *
  13353. * ```
  13354. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13355. * $sceDelegateProvider.resourceUrlWhitelist([
  13356. * // Allow same origin resource loads.
  13357. * 'self',
  13358. * // Allow loading from our assets domain. Notice the difference between * and **.
  13359. * 'http://srv*.assets.example.com/**'
  13360. * ]);
  13361. *
  13362. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13363. * $sceDelegateProvider.resourceUrlBlacklist([
  13364. * 'http://myapp.example.com/clickThru**'
  13365. * ]);
  13366. * });
  13367. * ```
  13368. */
  13369. function $SceDelegateProvider() {
  13370. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13371. // Resource URLs can also be trusted by policy.
  13372. var resourceUrlWhitelist = ['self'],
  13373. resourceUrlBlacklist = [];
  13374. /**
  13375. * @ngdoc method
  13376. * @name $sceDelegateProvider#resourceUrlWhitelist
  13377. * @kind function
  13378. *
  13379. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13380. * provided. This must be an array or null. A snapshot of this array is used so further
  13381. * changes to the array are ignored.
  13382. *
  13383. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13384. * allowed in this array.
  13385. *
  13386. * Note: **an empty whitelist array will block all URLs**!
  13387. *
  13388. * @return {Array} the currently set whitelist array.
  13389. *
  13390. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13391. * same origin resource requests.
  13392. *
  13393. * @description
  13394. * Sets/Gets the whitelist of trusted resource URLs.
  13395. */
  13396. this.resourceUrlWhitelist = function(value) {
  13397. if (arguments.length) {
  13398. resourceUrlWhitelist = adjustMatchers(value);
  13399. }
  13400. return resourceUrlWhitelist;
  13401. };
  13402. /**
  13403. * @ngdoc method
  13404. * @name $sceDelegateProvider#resourceUrlBlacklist
  13405. * @kind function
  13406. *
  13407. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13408. * provided. This must be an array or null. A snapshot of this array is used so further
  13409. * changes to the array are ignored.
  13410. *
  13411. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13412. * allowed in this array.
  13413. *
  13414. * The typical usage for the blacklist is to **block
  13415. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13416. * these would otherwise be trusted but actually return content from the redirected domain.
  13417. *
  13418. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13419. *
  13420. * @return {Array} the currently set blacklist array.
  13421. *
  13422. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13423. * is no blacklist.)
  13424. *
  13425. * @description
  13426. * Sets/Gets the blacklist of trusted resource URLs.
  13427. */
  13428. this.resourceUrlBlacklist = function(value) {
  13429. if (arguments.length) {
  13430. resourceUrlBlacklist = adjustMatchers(value);
  13431. }
  13432. return resourceUrlBlacklist;
  13433. };
  13434. this.$get = ['$injector', function($injector) {
  13435. var htmlSanitizer = function htmlSanitizer(html) {
  13436. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13437. };
  13438. if ($injector.has('$sanitize')) {
  13439. htmlSanitizer = $injector.get('$sanitize');
  13440. }
  13441. function matchUrl(matcher, parsedUrl) {
  13442. if (matcher === 'self') {
  13443. return urlIsSameOrigin(parsedUrl);
  13444. } else {
  13445. // definitely a regex. See adjustMatchers()
  13446. return !!matcher.exec(parsedUrl.href);
  13447. }
  13448. }
  13449. function isResourceUrlAllowedByPolicy(url) {
  13450. var parsedUrl = urlResolve(url.toString());
  13451. var i, n, allowed = false;
  13452. // Ensure that at least one item from the whitelist allows this url.
  13453. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13454. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13455. allowed = true;
  13456. break;
  13457. }
  13458. }
  13459. if (allowed) {
  13460. // Ensure that no item from the blacklist blocked this url.
  13461. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13462. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13463. allowed = false;
  13464. break;
  13465. }
  13466. }
  13467. }
  13468. return allowed;
  13469. }
  13470. function generateHolderType(Base) {
  13471. var holderType = function TrustedValueHolderType(trustedValue) {
  13472. this.$$unwrapTrustedValue = function() {
  13473. return trustedValue;
  13474. };
  13475. };
  13476. if (Base) {
  13477. holderType.prototype = new Base();
  13478. }
  13479. holderType.prototype.valueOf = function sceValueOf() {
  13480. return this.$$unwrapTrustedValue();
  13481. };
  13482. holderType.prototype.toString = function sceToString() {
  13483. return this.$$unwrapTrustedValue().toString();
  13484. };
  13485. return holderType;
  13486. }
  13487. var trustedValueHolderBase = generateHolderType(),
  13488. byType = {};
  13489. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13490. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13491. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13492. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13493. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13494. /**
  13495. * @ngdoc method
  13496. * @name $sceDelegate#trustAs
  13497. *
  13498. * @description
  13499. * Returns an object that is trusted by angular for use in specified strict
  13500. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13501. * attribute interpolation, any dom event binding attribute interpolation
  13502. * such as for onclick, etc.) that uses the provided value.
  13503. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13504. *
  13505. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13506. * resourceUrl, html, js and css.
  13507. * @param {*} value The value that that should be considered trusted/safe.
  13508. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13509. * where Angular expects a $sce.trustAs() return value.
  13510. */
  13511. function trustAs(type, trustedValue) {
  13512. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13513. if (!Constructor) {
  13514. throw $sceMinErr('icontext',
  13515. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13516. type, trustedValue);
  13517. }
  13518. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13519. return trustedValue;
  13520. }
  13521. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13522. // mutable objects, we ensure here that the value passed in is actually a string.
  13523. if (typeof trustedValue !== 'string') {
  13524. throw $sceMinErr('itype',
  13525. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13526. type);
  13527. }
  13528. return new Constructor(trustedValue);
  13529. }
  13530. /**
  13531. * @ngdoc method
  13532. * @name $sceDelegate#valueOf
  13533. *
  13534. * @description
  13535. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13536. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13537. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13538. *
  13539. * If the passed parameter is not a value that had been returned by {@link
  13540. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13541. *
  13542. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13543. * call or anything else.
  13544. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13545. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13546. * `value` unchanged.
  13547. */
  13548. function valueOf(maybeTrusted) {
  13549. if (maybeTrusted instanceof trustedValueHolderBase) {
  13550. return maybeTrusted.$$unwrapTrustedValue();
  13551. } else {
  13552. return maybeTrusted;
  13553. }
  13554. }
  13555. /**
  13556. * @ngdoc method
  13557. * @name $sceDelegate#getTrusted
  13558. *
  13559. * @description
  13560. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13561. * returns the originally supplied value if the queried context type is a supertype of the
  13562. * created type. If this condition isn't satisfied, throws an exception.
  13563. *
  13564. * @param {string} type The kind of context in which this value is to be used.
  13565. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13566. * `$sceDelegate.trustAs`} call.
  13567. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13568. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13569. */
  13570. function getTrusted(type, maybeTrusted) {
  13571. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13572. return maybeTrusted;
  13573. }
  13574. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13575. if (constructor && maybeTrusted instanceof constructor) {
  13576. return maybeTrusted.$$unwrapTrustedValue();
  13577. }
  13578. // If we get here, then we may only take one of two actions.
  13579. // 1. sanitize the value for the requested type, or
  13580. // 2. throw an exception.
  13581. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13582. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13583. return maybeTrusted;
  13584. } else {
  13585. throw $sceMinErr('insecurl',
  13586. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13587. maybeTrusted.toString());
  13588. }
  13589. } else if (type === SCE_CONTEXTS.HTML) {
  13590. return htmlSanitizer(maybeTrusted);
  13591. }
  13592. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13593. }
  13594. return { trustAs: trustAs,
  13595. getTrusted: getTrusted,
  13596. valueOf: valueOf };
  13597. }];
  13598. }
  13599. /**
  13600. * @ngdoc provider
  13601. * @name $sceProvider
  13602. * @description
  13603. *
  13604. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13605. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13606. * - override the default implementation with a custom delegate
  13607. *
  13608. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13609. */
  13610. /* jshint maxlen: false*/
  13611. /**
  13612. * @ngdoc service
  13613. * @name $sce
  13614. * @kind function
  13615. *
  13616. * @description
  13617. *
  13618. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13619. *
  13620. * # Strict Contextual Escaping
  13621. *
  13622. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13623. * contexts to result in a value that is marked as safe to use for that context. One example of
  13624. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13625. * to these contexts as privileged or SCE contexts.
  13626. *
  13627. * As of version 1.2, Angular ships with SCE enabled by default.
  13628. *
  13629. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13630. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13631. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13632. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13633. * to the top of your HTML document.
  13634. *
  13635. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13636. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13637. *
  13638. * Here's an example of a binding in a privileged context:
  13639. *
  13640. * ```
  13641. * <input ng-model="userHtml">
  13642. * <div ng-bind-html="userHtml"></div>
  13643. * ```
  13644. *
  13645. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13646. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13647. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13648. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13649. * security vulnerabilities.)
  13650. *
  13651. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13652. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13653. *
  13654. * How would you ensure that every place that used these types of bindings was bound to a value that
  13655. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13656. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13657. * properties/fields and forgot to update the binding to the sanitized value?
  13658. *
  13659. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13660. * determine that something explicitly says it's safe to use a value for binding in that
  13661. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13662. * for those values that you can easily tell are safe - because they were received from your server,
  13663. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13664. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13665. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13666. *
  13667. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13668. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13669. * obtain values that will be accepted by SCE / privileged contexts.
  13670. *
  13671. *
  13672. * ## How does it work?
  13673. *
  13674. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13675. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13676. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13677. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13678. *
  13679. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13680. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13681. * simplified):
  13682. *
  13683. * ```
  13684. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13685. * return function(scope, element, attr) {
  13686. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13687. * element.html(value || '');
  13688. * });
  13689. * };
  13690. * }];
  13691. * ```
  13692. *
  13693. * ## Impact on loading templates
  13694. *
  13695. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13696. * `templateUrl`'s specified by {@link guide/directive directives}.
  13697. *
  13698. * By default, Angular only loads templates from the same domain and protocol as the application
  13699. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13700. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13701. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13702. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13703. *
  13704. * *Please note*:
  13705. * The browser's
  13706. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13707. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13708. * policy apply in addition to this and may further restrict whether the template is successfully
  13709. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13710. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13711. * browsers.
  13712. *
  13713. * ## This feels like too much overhead
  13714. *
  13715. * It's important to remember that SCE only applies to interpolation expressions.
  13716. *
  13717. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13718. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13719. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13720. *
  13721. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13722. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13723. *
  13724. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13725. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13726. * It blocks loading templates from other domains or loading templates over http from an https
  13727. * served document. You can change these by setting your own custom {@link
  13728. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13729. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13730. *
  13731. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13732. * application that's secure and can be audited to verify that with much more ease than bolting
  13733. * security onto an application later.
  13734. *
  13735. * <a name="contexts"></a>
  13736. * ## What trusted context types are supported?
  13737. *
  13738. * | Context | Notes |
  13739. * |---------------------|----------------|
  13740. * | `$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. |
  13741. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13742. * | `$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. |
  13743. * | `$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. |
  13744. * | `$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. |
  13745. *
  13746. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13747. *
  13748. * Each element in these arrays must be one of the following:
  13749. *
  13750. * - **'self'**
  13751. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13752. * domain** as the application document using the **same protocol**.
  13753. * - **String** (except the special value `'self'`)
  13754. * - The string is matched against the full *normalized / absolute URL* of the resource
  13755. * being tested (substring matches are not good enough.)
  13756. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13757. * match themselves.
  13758. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13759. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13760. * in a whitelist.
  13761. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13762. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13763. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13764. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13765. * http://foo.example.com/templates/**).
  13766. * - **RegExp** (*see caveat below*)
  13767. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13768. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13769. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13770. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13771. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13772. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13773. * is highly recommended to use the string patterns and only fall back to regular expressions
  13774. * if they as a last resort.
  13775. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13776. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13777. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13778. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13779. * - If you are generating your JavaScript from some other templating engine (not
  13780. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13781. * remember to escape your regular expression (and be aware that you might need more than
  13782. * one level of escaping depending on your templating engine and the way you interpolated
  13783. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13784. * enough before coding your own. e.g. Ruby has
  13785. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13786. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13787. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13788. * Closure library's [goog.string.regExpEscape(s)](
  13789. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13790. *
  13791. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13792. *
  13793. * ## Show me an example using SCE.
  13794. *
  13795. * <example module="mySceApp" deps="angular-sanitize.js">
  13796. * <file name="index.html">
  13797. * <div ng-controller="AppController as myCtrl">
  13798. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13799. * <b>User comments</b><br>
  13800. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13801. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13802. * exploit.
  13803. * <div class="well">
  13804. * <div ng-repeat="userComment in myCtrl.userComments">
  13805. * <b>{{userComment.name}}</b>:
  13806. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13807. * <br>
  13808. * </div>
  13809. * </div>
  13810. * </div>
  13811. * </file>
  13812. *
  13813. * <file name="script.js">
  13814. * angular.module('mySceApp', ['ngSanitize'])
  13815. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13816. * function($http, $templateCache, $sce) {
  13817. * var self = this;
  13818. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13819. * self.userComments = userComments;
  13820. * });
  13821. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13822. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13823. * 'sanitization.&quot;">Hover over this text.</span>');
  13824. * }]);
  13825. * </file>
  13826. *
  13827. * <file name="test_data.json">
  13828. * [
  13829. * { "name": "Alice",
  13830. * "htmlComment":
  13831. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  13832. * },
  13833. * { "name": "Bob",
  13834. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  13835. * }
  13836. * ]
  13837. * </file>
  13838. *
  13839. * <file name="protractor.js" type="protractor">
  13840. * describe('SCE doc demo', function() {
  13841. * it('should sanitize untrusted values', function() {
  13842. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  13843. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  13844. * });
  13845. *
  13846. * it('should NOT sanitize explicitly trusted values', function() {
  13847. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  13848. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13849. * 'sanitization.&quot;">Hover over this text.</span>');
  13850. * });
  13851. * });
  13852. * </file>
  13853. * </example>
  13854. *
  13855. *
  13856. *
  13857. * ## Can I disable SCE completely?
  13858. *
  13859. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  13860. * for little coding overhead. It will be much harder to take an SCE disabled application and
  13861. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  13862. * for cases where you have a lot of existing code that was written before SCE was introduced and
  13863. * you're migrating them a module at a time.
  13864. *
  13865. * That said, here's how you can completely disable SCE:
  13866. *
  13867. * ```
  13868. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  13869. * // Completely disable SCE. For demonstration purposes only!
  13870. * // Do not use in new projects.
  13871. * $sceProvider.enabled(false);
  13872. * });
  13873. * ```
  13874. *
  13875. */
  13876. /* jshint maxlen: 100 */
  13877. function $SceProvider() {
  13878. var enabled = true;
  13879. /**
  13880. * @ngdoc method
  13881. * @name $sceProvider#enabled
  13882. * @kind function
  13883. *
  13884. * @param {boolean=} value If provided, then enables/disables SCE.
  13885. * @return {boolean} true if SCE is enabled, false otherwise.
  13886. *
  13887. * @description
  13888. * Enables/disables SCE and returns the current value.
  13889. */
  13890. this.enabled = function(value) {
  13891. if (arguments.length) {
  13892. enabled = !!value;
  13893. }
  13894. return enabled;
  13895. };
  13896. /* Design notes on the default implementation for SCE.
  13897. *
  13898. * The API contract for the SCE delegate
  13899. * -------------------------------------
  13900. * The SCE delegate object must provide the following 3 methods:
  13901. *
  13902. * - trustAs(contextEnum, value)
  13903. * This method is used to tell the SCE service that the provided value is OK to use in the
  13904. * contexts specified by contextEnum. It must return an object that will be accepted by
  13905. * getTrusted() for a compatible contextEnum and return this value.
  13906. *
  13907. * - valueOf(value)
  13908. * For values that were not produced by trustAs(), return them as is. For values that were
  13909. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  13910. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  13911. * such a value.
  13912. *
  13913. * - getTrusted(contextEnum, value)
  13914. * This function should return the a value that is safe to use in the context specified by
  13915. * contextEnum or throw and exception otherwise.
  13916. *
  13917. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  13918. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  13919. * instance, an implementation could maintain a registry of all trusted objects by context. In
  13920. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  13921. * return the same object passed in if it was found in the registry under a compatible context or
  13922. * throw an exception otherwise. An implementation might only wrap values some of the time based
  13923. * on some criteria. getTrusted() might return a value and not throw an exception for special
  13924. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  13925. *
  13926. *
  13927. * A note on the inheritance model for SCE contexts
  13928. * ------------------------------------------------
  13929. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  13930. * is purely an implementation details.
  13931. *
  13932. * The contract is simply this:
  13933. *
  13934. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  13935. * will also succeed.
  13936. *
  13937. * Inheritance happens to capture this in a natural way. In some future, we
  13938. * may not use inheritance anymore. That is OK because no code outside of
  13939. * sce.js and sceSpecs.js would need to be aware of this detail.
  13940. */
  13941. this.$get = ['$parse', '$sceDelegate', function(
  13942. $parse, $sceDelegate) {
  13943. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  13944. // the "expression(javascript expression)" syntax which is insecure.
  13945. if (enabled && msie < 8) {
  13946. throw $sceMinErr('iequirks',
  13947. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  13948. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  13949. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  13950. }
  13951. var sce = shallowCopy(SCE_CONTEXTS);
  13952. /**
  13953. * @ngdoc method
  13954. * @name $sce#isEnabled
  13955. * @kind function
  13956. *
  13957. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  13958. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  13959. *
  13960. * @description
  13961. * Returns a boolean indicating if SCE is enabled.
  13962. */
  13963. sce.isEnabled = function() {
  13964. return enabled;
  13965. };
  13966. sce.trustAs = $sceDelegate.trustAs;
  13967. sce.getTrusted = $sceDelegate.getTrusted;
  13968. sce.valueOf = $sceDelegate.valueOf;
  13969. if (!enabled) {
  13970. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  13971. sce.valueOf = identity;
  13972. }
  13973. /**
  13974. * @ngdoc method
  13975. * @name $sce#parseAs
  13976. *
  13977. * @description
  13978. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  13979. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  13980. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  13981. * *result*)}
  13982. *
  13983. * @param {string} type The kind of SCE context in which this result will be used.
  13984. * @param {string} expression String expression to compile.
  13985. * @returns {function(context, locals)} a function which represents the compiled expression:
  13986. *
  13987. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13988. * are evaluated against (typically a scope object).
  13989. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13990. * `context`.
  13991. */
  13992. sce.parseAs = function sceParseAs(type, expr) {
  13993. var parsed = $parse(expr);
  13994. if (parsed.literal && parsed.constant) {
  13995. return parsed;
  13996. } else {
  13997. return $parse(expr, function(value) {
  13998. return sce.getTrusted(type, value);
  13999. });
  14000. }
  14001. };
  14002. /**
  14003. * @ngdoc method
  14004. * @name $sce#trustAs
  14005. *
  14006. * @description
  14007. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  14008. * returns an object that is trusted by angular for use in specified strict contextual
  14009. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  14010. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  14011. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  14012. * escaping.
  14013. *
  14014. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14015. * resource_url, html, js and css.
  14016. * @param {*} value The value that that should be considered trusted/safe.
  14017. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14018. * where Angular expects a $sce.trustAs() return value.
  14019. */
  14020. /**
  14021. * @ngdoc method
  14022. * @name $sce#trustAsHtml
  14023. *
  14024. * @description
  14025. * Shorthand method. `$sce.trustAsHtml(value)` →
  14026. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  14027. *
  14028. * @param {*} value The value to trustAs.
  14029. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  14030. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  14031. * only accept expressions that are either literal constants or are the
  14032. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14033. */
  14034. /**
  14035. * @ngdoc method
  14036. * @name $sce#trustAsUrl
  14037. *
  14038. * @description
  14039. * Shorthand method. `$sce.trustAsUrl(value)` →
  14040. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  14041. *
  14042. * @param {*} value The value to trustAs.
  14043. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  14044. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  14045. * only accept expressions that are either literal constants or are the
  14046. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14047. */
  14048. /**
  14049. * @ngdoc method
  14050. * @name $sce#trustAsResourceUrl
  14051. *
  14052. * @description
  14053. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  14054. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  14055. *
  14056. * @param {*} value The value to trustAs.
  14057. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  14058. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  14059. * only accept expressions that are either literal constants or are the return
  14060. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14061. */
  14062. /**
  14063. * @ngdoc method
  14064. * @name $sce#trustAsJs
  14065. *
  14066. * @description
  14067. * Shorthand method. `$sce.trustAsJs(value)` →
  14068. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  14069. *
  14070. * @param {*} value The value to trustAs.
  14071. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  14072. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  14073. * only accept expressions that are either literal constants or are the
  14074. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  14075. */
  14076. /**
  14077. * @ngdoc method
  14078. * @name $sce#getTrusted
  14079. *
  14080. * @description
  14081. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14082. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14083. * originally supplied value if the queried context type is a supertype of the created type.
  14084. * If this condition isn't satisfied, throws an exception.
  14085. *
  14086. * @param {string} type The kind of context in which this value is to be used.
  14087. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14088. * call.
  14089. * @returns {*} The value the was originally provided to
  14090. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14091. * Otherwise, throws an exception.
  14092. */
  14093. /**
  14094. * @ngdoc method
  14095. * @name $sce#getTrustedHtml
  14096. *
  14097. * @description
  14098. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14099. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14100. *
  14101. * @param {*} value The value to pass to `$sce.getTrusted`.
  14102. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14103. */
  14104. /**
  14105. * @ngdoc method
  14106. * @name $sce#getTrustedCss
  14107. *
  14108. * @description
  14109. * Shorthand method. `$sce.getTrustedCss(value)` →
  14110. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14111. *
  14112. * @param {*} value The value to pass to `$sce.getTrusted`.
  14113. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14114. */
  14115. /**
  14116. * @ngdoc method
  14117. * @name $sce#getTrustedUrl
  14118. *
  14119. * @description
  14120. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14121. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14122. *
  14123. * @param {*} value The value to pass to `$sce.getTrusted`.
  14124. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14125. */
  14126. /**
  14127. * @ngdoc method
  14128. * @name $sce#getTrustedResourceUrl
  14129. *
  14130. * @description
  14131. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14132. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14133. *
  14134. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14135. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14136. */
  14137. /**
  14138. * @ngdoc method
  14139. * @name $sce#getTrustedJs
  14140. *
  14141. * @description
  14142. * Shorthand method. `$sce.getTrustedJs(value)` →
  14143. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14144. *
  14145. * @param {*} value The value to pass to `$sce.getTrusted`.
  14146. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14147. */
  14148. /**
  14149. * @ngdoc method
  14150. * @name $sce#parseAsHtml
  14151. *
  14152. * @description
  14153. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14154. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14155. *
  14156. * @param {string} expression String expression to compile.
  14157. * @returns {function(context, locals)} a function which represents the compiled expression:
  14158. *
  14159. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14160. * are evaluated against (typically a scope object).
  14161. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14162. * `context`.
  14163. */
  14164. /**
  14165. * @ngdoc method
  14166. * @name $sce#parseAsCss
  14167. *
  14168. * @description
  14169. * Shorthand method. `$sce.parseAsCss(value)` →
  14170. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14171. *
  14172. * @param {string} expression String expression to compile.
  14173. * @returns {function(context, locals)} a function which represents the compiled expression:
  14174. *
  14175. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14176. * are evaluated against (typically a scope object).
  14177. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14178. * `context`.
  14179. */
  14180. /**
  14181. * @ngdoc method
  14182. * @name $sce#parseAsUrl
  14183. *
  14184. * @description
  14185. * Shorthand method. `$sce.parseAsUrl(value)` →
  14186. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14187. *
  14188. * @param {string} expression String expression to compile.
  14189. * @returns {function(context, locals)} a function which represents the compiled expression:
  14190. *
  14191. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14192. * are evaluated against (typically a scope object).
  14193. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14194. * `context`.
  14195. */
  14196. /**
  14197. * @ngdoc method
  14198. * @name $sce#parseAsResourceUrl
  14199. *
  14200. * @description
  14201. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14202. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14203. *
  14204. * @param {string} expression String expression to compile.
  14205. * @returns {function(context, locals)} a function which represents the compiled expression:
  14206. *
  14207. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14208. * are evaluated against (typically a scope object).
  14209. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14210. * `context`.
  14211. */
  14212. /**
  14213. * @ngdoc method
  14214. * @name $sce#parseAsJs
  14215. *
  14216. * @description
  14217. * Shorthand method. `$sce.parseAsJs(value)` →
  14218. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14219. *
  14220. * @param {string} expression String expression to compile.
  14221. * @returns {function(context, locals)} a function which represents the compiled expression:
  14222. *
  14223. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14224. * are evaluated against (typically a scope object).
  14225. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14226. * `context`.
  14227. */
  14228. // Shorthand delegations.
  14229. var parse = sce.parseAs,
  14230. getTrusted = sce.getTrusted,
  14231. trustAs = sce.trustAs;
  14232. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14233. var lName = lowercase(name);
  14234. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14235. return parse(enumValue, expr);
  14236. };
  14237. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14238. return getTrusted(enumValue, value);
  14239. };
  14240. sce[camelCase("trust_as_" + lName)] = function(value) {
  14241. return trustAs(enumValue, value);
  14242. };
  14243. });
  14244. return sce;
  14245. }];
  14246. }
  14247. /**
  14248. * !!! This is an undocumented "private" service !!!
  14249. *
  14250. * @name $sniffer
  14251. * @requires $window
  14252. * @requires $document
  14253. *
  14254. * @property {boolean} history Does the browser support html5 history api ?
  14255. * @property {boolean} transitions Does the browser support CSS transition events ?
  14256. * @property {boolean} animations Does the browser support CSS animation events ?
  14257. *
  14258. * @description
  14259. * This is very simple implementation of testing browser's features.
  14260. */
  14261. function $SnifferProvider() {
  14262. this.$get = ['$window', '$document', function($window, $document) {
  14263. var eventSupport = {},
  14264. android =
  14265. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14266. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14267. document = $document[0] || {},
  14268. vendorPrefix,
  14269. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14270. bodyStyle = document.body && document.body.style,
  14271. transitions = false,
  14272. animations = false,
  14273. match;
  14274. if (bodyStyle) {
  14275. for (var prop in bodyStyle) {
  14276. if (match = vendorRegex.exec(prop)) {
  14277. vendorPrefix = match[0];
  14278. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14279. break;
  14280. }
  14281. }
  14282. if (!vendorPrefix) {
  14283. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14284. }
  14285. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14286. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14287. if (android && (!transitions || !animations)) {
  14288. transitions = isString(document.body.style.webkitTransition);
  14289. animations = isString(document.body.style.webkitAnimation);
  14290. }
  14291. }
  14292. return {
  14293. // Android has history.pushState, but it does not update location correctly
  14294. // so let's not use the history API at all.
  14295. // http://code.google.com/p/android/issues/detail?id=17471
  14296. // https://github.com/angular/angular.js/issues/904
  14297. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14298. // so let's not use the history API also
  14299. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14300. // jshint -W018
  14301. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14302. // jshint +W018
  14303. hasEvent: function(event) {
  14304. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14305. // it. In particular the event is not fired when backspace or delete key are pressed or
  14306. // when cut operation is performed.
  14307. if (event == 'input' && msie == 9) return false;
  14308. if (isUndefined(eventSupport[event])) {
  14309. var divElm = document.createElement('div');
  14310. eventSupport[event] = 'on' + event in divElm;
  14311. }
  14312. return eventSupport[event];
  14313. },
  14314. csp: csp(),
  14315. vendorPrefix: vendorPrefix,
  14316. transitions: transitions,
  14317. animations: animations,
  14318. android: android
  14319. };
  14320. }];
  14321. }
  14322. var $compileMinErr = minErr('$compile');
  14323. /**
  14324. * @ngdoc service
  14325. * @name $templateRequest
  14326. *
  14327. * @description
  14328. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14329. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14330. * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted
  14331. * by setting the 2nd parameter of the function to true).
  14332. *
  14333. * @param {string} tpl The HTTP request template URL
  14334. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14335. *
  14336. * @return {Promise} the HTTP Promise for the given.
  14337. *
  14338. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14339. */
  14340. function $TemplateRequestProvider() {
  14341. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14342. function handleRequestFn(tpl, ignoreRequestError) {
  14343. var self = handleRequestFn;
  14344. self.totalPendingRequests++;
  14345. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14346. if (isArray(transformResponse)) {
  14347. var original = transformResponse;
  14348. transformResponse = [];
  14349. for (var i = 0; i < original.length; ++i) {
  14350. var transformer = original[i];
  14351. if (transformer !== defaultHttpResponseTransform) {
  14352. transformResponse.push(transformer);
  14353. }
  14354. }
  14355. } else if (transformResponse === defaultHttpResponseTransform) {
  14356. transformResponse = null;
  14357. }
  14358. var httpOptions = {
  14359. cache: $templateCache,
  14360. transformResponse: transformResponse
  14361. };
  14362. return $http.get(tpl, httpOptions)
  14363. .then(function(response) {
  14364. var html = response.data;
  14365. self.totalPendingRequests--;
  14366. $templateCache.put(tpl, html);
  14367. return html;
  14368. }, handleError);
  14369. function handleError() {
  14370. self.totalPendingRequests--;
  14371. if (!ignoreRequestError) {
  14372. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14373. }
  14374. return $q.reject();
  14375. }
  14376. }
  14377. handleRequestFn.totalPendingRequests = 0;
  14378. return handleRequestFn;
  14379. }];
  14380. }
  14381. function $$TestabilityProvider() {
  14382. this.$get = ['$rootScope', '$browser', '$location',
  14383. function($rootScope, $browser, $location) {
  14384. /**
  14385. * @name $testability
  14386. *
  14387. * @description
  14388. * The private $$testability service provides a collection of methods for use when debugging
  14389. * or by automated test and debugging tools.
  14390. */
  14391. var testability = {};
  14392. /**
  14393. * @name $$testability#findBindings
  14394. *
  14395. * @description
  14396. * Returns an array of elements that are bound (via ng-bind or {{}})
  14397. * to expressions matching the input.
  14398. *
  14399. * @param {Element} element The element root to search from.
  14400. * @param {string} expression The binding expression to match.
  14401. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14402. * for the expression. Filters and whitespace are ignored.
  14403. */
  14404. testability.findBindings = function(element, expression, opt_exactMatch) {
  14405. var bindings = element.getElementsByClassName('ng-binding');
  14406. var matches = [];
  14407. forEach(bindings, function(binding) {
  14408. var dataBinding = angular.element(binding).data('$binding');
  14409. if (dataBinding) {
  14410. forEach(dataBinding, function(bindingName) {
  14411. if (opt_exactMatch) {
  14412. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14413. if (matcher.test(bindingName)) {
  14414. matches.push(binding);
  14415. }
  14416. } else {
  14417. if (bindingName.indexOf(expression) != -1) {
  14418. matches.push(binding);
  14419. }
  14420. }
  14421. });
  14422. }
  14423. });
  14424. return matches;
  14425. };
  14426. /**
  14427. * @name $$testability#findModels
  14428. *
  14429. * @description
  14430. * Returns an array of elements that are two-way found via ng-model to
  14431. * expressions matching the input.
  14432. *
  14433. * @param {Element} element The element root to search from.
  14434. * @param {string} expression The model expression to match.
  14435. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14436. * for the expression.
  14437. */
  14438. testability.findModels = function(element, expression, opt_exactMatch) {
  14439. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14440. for (var p = 0; p < prefixes.length; ++p) {
  14441. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14442. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14443. var elements = element.querySelectorAll(selector);
  14444. if (elements.length) {
  14445. return elements;
  14446. }
  14447. }
  14448. };
  14449. /**
  14450. * @name $$testability#getLocation
  14451. *
  14452. * @description
  14453. * Shortcut for getting the location in a browser agnostic way. Returns
  14454. * the path, search, and hash. (e.g. /path?a=b#hash)
  14455. */
  14456. testability.getLocation = function() {
  14457. return $location.url();
  14458. };
  14459. /**
  14460. * @name $$testability#setLocation
  14461. *
  14462. * @description
  14463. * Shortcut for navigating to a location without doing a full page reload.
  14464. *
  14465. * @param {string} url The location url (path, search and hash,
  14466. * e.g. /path?a=b#hash) to go to.
  14467. */
  14468. testability.setLocation = function(url) {
  14469. if (url !== $location.url()) {
  14470. $location.url(url);
  14471. $rootScope.$digest();
  14472. }
  14473. };
  14474. /**
  14475. * @name $$testability#whenStable
  14476. *
  14477. * @description
  14478. * Calls the callback when $timeout and $http requests are completed.
  14479. *
  14480. * @param {function} callback
  14481. */
  14482. testability.whenStable = function(callback) {
  14483. $browser.notifyWhenNoOutstandingRequests(callback);
  14484. };
  14485. return testability;
  14486. }];
  14487. }
  14488. function $TimeoutProvider() {
  14489. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14490. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14491. var deferreds = {};
  14492. /**
  14493. * @ngdoc service
  14494. * @name $timeout
  14495. *
  14496. * @description
  14497. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14498. * block and delegates any exceptions to
  14499. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14500. *
  14501. * The return value of registering a timeout function is a promise, which will be resolved when
  14502. * the timeout is reached and the timeout function is executed.
  14503. *
  14504. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14505. *
  14506. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14507. * synchronously flush the queue of deferred functions.
  14508. *
  14509. * @param {function()} fn A function, whose execution should be delayed.
  14510. * @param {number=} [delay=0] Delay in milliseconds.
  14511. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14512. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14513. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14514. * promise will be resolved with is the return value of the `fn` function.
  14515. *
  14516. */
  14517. function timeout(fn, delay, invokeApply) {
  14518. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14519. deferred = (skipApply ? $$q : $q).defer(),
  14520. promise = deferred.promise,
  14521. timeoutId;
  14522. timeoutId = $browser.defer(function() {
  14523. try {
  14524. deferred.resolve(fn());
  14525. } catch (e) {
  14526. deferred.reject(e);
  14527. $exceptionHandler(e);
  14528. }
  14529. finally {
  14530. delete deferreds[promise.$$timeoutId];
  14531. }
  14532. if (!skipApply) $rootScope.$apply();
  14533. }, delay);
  14534. promise.$$timeoutId = timeoutId;
  14535. deferreds[timeoutId] = deferred;
  14536. return promise;
  14537. }
  14538. /**
  14539. * @ngdoc method
  14540. * @name $timeout#cancel
  14541. *
  14542. * @description
  14543. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14544. * resolved with a rejection.
  14545. *
  14546. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14547. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14548. * canceled.
  14549. */
  14550. timeout.cancel = function(promise) {
  14551. if (promise && promise.$$timeoutId in deferreds) {
  14552. deferreds[promise.$$timeoutId].reject('canceled');
  14553. delete deferreds[promise.$$timeoutId];
  14554. return $browser.defer.cancel(promise.$$timeoutId);
  14555. }
  14556. return false;
  14557. };
  14558. return timeout;
  14559. }];
  14560. }
  14561. // NOTE: The usage of window and document instead of $window and $document here is
  14562. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14563. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14564. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14565. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14566. // exactly the behavior needed here. There is little value is mocking these out for this
  14567. // service.
  14568. var urlParsingNode = document.createElement("a");
  14569. var originUrl = urlResolve(window.location.href);
  14570. /**
  14571. *
  14572. * Implementation Notes for non-IE browsers
  14573. * ----------------------------------------
  14574. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14575. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14576. * URL will be resolved into an absolute URL in the context of the application document.
  14577. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14578. * properties are all populated to reflect the normalized URL. This approach has wide
  14579. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14580. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14581. *
  14582. * Implementation Notes for IE
  14583. * ---------------------------
  14584. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14585. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14586. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14587. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14588. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14589. * properties such as protocol, hostname, port, etc.
  14590. *
  14591. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14592. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14593. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14594. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14595. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14596. * method and IE < 8 is unsupported.
  14597. *
  14598. * References:
  14599. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14600. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14601. * http://url.spec.whatwg.org/#urlutils
  14602. * https://github.com/angular/angular.js/pull/2902
  14603. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14604. *
  14605. * @kind function
  14606. * @param {string} url The URL to be parsed.
  14607. * @description Normalizes and parses a URL.
  14608. * @returns {object} Returns the normalized URL as a dictionary.
  14609. *
  14610. * | member name | Description |
  14611. * |---------------|----------------|
  14612. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14613. * | protocol | The protocol including the trailing colon |
  14614. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14615. * | search | The search params, minus the question mark |
  14616. * | hash | The hash string, minus the hash symbol
  14617. * | hostname | The hostname
  14618. * | port | The port, without ":"
  14619. * | pathname | The pathname, beginning with "/"
  14620. *
  14621. */
  14622. function urlResolve(url) {
  14623. var href = url;
  14624. if (msie) {
  14625. // Normalize before parse. Refer Implementation Notes on why this is
  14626. // done in two steps on IE.
  14627. urlParsingNode.setAttribute("href", href);
  14628. href = urlParsingNode.href;
  14629. }
  14630. urlParsingNode.setAttribute('href', href);
  14631. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14632. return {
  14633. href: urlParsingNode.href,
  14634. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14635. host: urlParsingNode.host,
  14636. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14637. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14638. hostname: urlParsingNode.hostname,
  14639. port: urlParsingNode.port,
  14640. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14641. ? urlParsingNode.pathname
  14642. : '/' + urlParsingNode.pathname
  14643. };
  14644. }
  14645. /**
  14646. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14647. *
  14648. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14649. * or a parsed URL object.
  14650. * @returns {boolean} Whether the request is for the same origin as the application document.
  14651. */
  14652. function urlIsSameOrigin(requestUrl) {
  14653. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14654. return (parsed.protocol === originUrl.protocol &&
  14655. parsed.host === originUrl.host);
  14656. }
  14657. /**
  14658. * @ngdoc service
  14659. * @name $window
  14660. *
  14661. * @description
  14662. * A reference to the browser's `window` object. While `window`
  14663. * is globally available in JavaScript, it causes testability problems, because
  14664. * it is a global variable. In angular we always refer to it through the
  14665. * `$window` service, so it may be overridden, removed or mocked for testing.
  14666. *
  14667. * Expressions, like the one defined for the `ngClick` directive in the example
  14668. * below, are evaluated with respect to the current scope. Therefore, there is
  14669. * no risk of inadvertently coding in a dependency on a global value in such an
  14670. * expression.
  14671. *
  14672. * @example
  14673. <example module="windowExample">
  14674. <file name="index.html">
  14675. <script>
  14676. angular.module('windowExample', [])
  14677. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14678. $scope.greeting = 'Hello, World!';
  14679. $scope.doGreeting = function(greeting) {
  14680. $window.alert(greeting);
  14681. };
  14682. }]);
  14683. </script>
  14684. <div ng-controller="ExampleController">
  14685. <input type="text" ng-model="greeting" />
  14686. <button ng-click="doGreeting(greeting)">ALERT</button>
  14687. </div>
  14688. </file>
  14689. <file name="protractor.js" type="protractor">
  14690. it('should display the greeting in the input box', function() {
  14691. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14692. // If we click the button it will block the test runner
  14693. // element(':button').click();
  14694. });
  14695. </file>
  14696. </example>
  14697. */
  14698. function $WindowProvider() {
  14699. this.$get = valueFn(window);
  14700. }
  14701. /* global currencyFilter: true,
  14702. dateFilter: true,
  14703. filterFilter: true,
  14704. jsonFilter: true,
  14705. limitToFilter: true,
  14706. lowercaseFilter: true,
  14707. numberFilter: true,
  14708. orderByFilter: true,
  14709. uppercaseFilter: true,
  14710. */
  14711. /**
  14712. * @ngdoc provider
  14713. * @name $filterProvider
  14714. * @description
  14715. *
  14716. * Filters are just functions which transform input to an output. However filters need to be
  14717. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14718. * annotated with dependencies and is responsible for creating a filter function.
  14719. *
  14720. * ```js
  14721. * // Filter registration
  14722. * function MyModule($provide, $filterProvider) {
  14723. * // create a service to demonstrate injection (not always needed)
  14724. * $provide.value('greet', function(name){
  14725. * return 'Hello ' + name + '!';
  14726. * });
  14727. *
  14728. * // register a filter factory which uses the
  14729. * // greet service to demonstrate DI.
  14730. * $filterProvider.register('greet', function(greet){
  14731. * // return the filter function which uses the greet service
  14732. * // to generate salutation
  14733. * return function(text) {
  14734. * // filters need to be forgiving so check input validity
  14735. * return text && greet(text) || text;
  14736. * };
  14737. * });
  14738. * }
  14739. * ```
  14740. *
  14741. * The filter function is registered with the `$injector` under the filter name suffix with
  14742. * `Filter`.
  14743. *
  14744. * ```js
  14745. * it('should be the same instance', inject(
  14746. * function($filterProvider) {
  14747. * $filterProvider.register('reverse', function(){
  14748. * return ...;
  14749. * });
  14750. * },
  14751. * function($filter, reverseFilter) {
  14752. * expect($filter('reverse')).toBe(reverseFilter);
  14753. * });
  14754. * ```
  14755. *
  14756. *
  14757. * For more information about how angular filters work, and how to create your own filters, see
  14758. * {@link guide/filter Filters} in the Angular Developer Guide.
  14759. */
  14760. /**
  14761. * @ngdoc service
  14762. * @name $filter
  14763. * @kind function
  14764. * @description
  14765. * Filters are used for formatting data displayed to the user.
  14766. *
  14767. * The general syntax in templates is as follows:
  14768. *
  14769. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14770. *
  14771. * @param {String} name Name of the filter function to retrieve
  14772. * @return {Function} the filter function
  14773. * @example
  14774. <example name="$filter" module="filterExample">
  14775. <file name="index.html">
  14776. <div ng-controller="MainCtrl">
  14777. <h3>{{ originalText }}</h3>
  14778. <h3>{{ filteredText }}</h3>
  14779. </div>
  14780. </file>
  14781. <file name="script.js">
  14782. angular.module('filterExample', [])
  14783. .controller('MainCtrl', function($scope, $filter) {
  14784. $scope.originalText = 'hello';
  14785. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14786. });
  14787. </file>
  14788. </example>
  14789. */
  14790. $FilterProvider.$inject = ['$provide'];
  14791. function $FilterProvider($provide) {
  14792. var suffix = 'Filter';
  14793. /**
  14794. * @ngdoc method
  14795. * @name $filterProvider#register
  14796. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14797. * the keys are the filter names and the values are the filter factories.
  14798. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14799. * of the registered filter instances.
  14800. */
  14801. function register(name, factory) {
  14802. if (isObject(name)) {
  14803. var filters = {};
  14804. forEach(name, function(filter, key) {
  14805. filters[key] = register(key, filter);
  14806. });
  14807. return filters;
  14808. } else {
  14809. return $provide.factory(name + suffix, factory);
  14810. }
  14811. }
  14812. this.register = register;
  14813. this.$get = ['$injector', function($injector) {
  14814. return function(name) {
  14815. return $injector.get(name + suffix);
  14816. };
  14817. }];
  14818. ////////////////////////////////////////
  14819. /* global
  14820. currencyFilter: false,
  14821. dateFilter: false,
  14822. filterFilter: false,
  14823. jsonFilter: false,
  14824. limitToFilter: false,
  14825. lowercaseFilter: false,
  14826. numberFilter: false,
  14827. orderByFilter: false,
  14828. uppercaseFilter: false,
  14829. */
  14830. register('currency', currencyFilter);
  14831. register('date', dateFilter);
  14832. register('filter', filterFilter);
  14833. register('json', jsonFilter);
  14834. register('limitTo', limitToFilter);
  14835. register('lowercase', lowercaseFilter);
  14836. register('number', numberFilter);
  14837. register('orderBy', orderByFilter);
  14838. register('uppercase', uppercaseFilter);
  14839. }
  14840. /**
  14841. * @ngdoc filter
  14842. * @name filter
  14843. * @kind function
  14844. *
  14845. * @description
  14846. * Selects a subset of items from `array` and returns it as a new array.
  14847. *
  14848. * @param {Array} array The source array.
  14849. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  14850. * `array`.
  14851. *
  14852. * Can be one of:
  14853. *
  14854. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  14855. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  14856. * will be returned. The predicate can be negated by prefixing the string with `!`.
  14857. *
  14858. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  14859. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  14860. * which have property `name` containing "M" and property `phone` containing "1". A special
  14861. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  14862. * property of the object. That's equivalent to the simple substring match with a `string`
  14863. * as described above. The predicate can be negated by prefixing the string with `!`.
  14864. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  14865. * not containing "M".
  14866. *
  14867. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  14868. * function is called for each element of `array`. The final result is an array of those
  14869. * elements that the predicate returned true for.
  14870. *
  14871. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  14872. * determining if the expected value (from the filter expression) and actual value (from
  14873. * the object in the array) should be considered a match.
  14874. *
  14875. * Can be one of:
  14876. *
  14877. * - `function(actual, expected)`:
  14878. * The function will be given the object value and the predicate value to compare and
  14879. * should return true if the item should be included in filtered result.
  14880. *
  14881. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  14882. * this is essentially strict comparison of expected and actual.
  14883. *
  14884. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  14885. * insensitive way.
  14886. *
  14887. * @example
  14888. <example>
  14889. <file name="index.html">
  14890. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  14891. {name:'Mary', phone:'800-BIG-MARY'},
  14892. {name:'Mike', phone:'555-4321'},
  14893. {name:'Adam', phone:'555-5678'},
  14894. {name:'Julie', phone:'555-8765'},
  14895. {name:'Juliette', phone:'555-5678'}]"></div>
  14896. Search: <input ng-model="searchText">
  14897. <table id="searchTextResults">
  14898. <tr><th>Name</th><th>Phone</th></tr>
  14899. <tr ng-repeat="friend in friends | filter:searchText">
  14900. <td>{{friend.name}}</td>
  14901. <td>{{friend.phone}}</td>
  14902. </tr>
  14903. </table>
  14904. <hr>
  14905. Any: <input ng-model="search.$"> <br>
  14906. Name only <input ng-model="search.name"><br>
  14907. Phone only <input ng-model="search.phone"><br>
  14908. Equality <input type="checkbox" ng-model="strict"><br>
  14909. <table id="searchObjResults">
  14910. <tr><th>Name</th><th>Phone</th></tr>
  14911. <tr ng-repeat="friendObj in friends | filter:search:strict">
  14912. <td>{{friendObj.name}}</td>
  14913. <td>{{friendObj.phone}}</td>
  14914. </tr>
  14915. </table>
  14916. </file>
  14917. <file name="protractor.js" type="protractor">
  14918. var expectFriendNames = function(expectedNames, key) {
  14919. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  14920. arr.forEach(function(wd, i) {
  14921. expect(wd.getText()).toMatch(expectedNames[i]);
  14922. });
  14923. });
  14924. };
  14925. it('should search across all fields when filtering with a string', function() {
  14926. var searchText = element(by.model('searchText'));
  14927. searchText.clear();
  14928. searchText.sendKeys('m');
  14929. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  14930. searchText.clear();
  14931. searchText.sendKeys('76');
  14932. expectFriendNames(['John', 'Julie'], 'friend');
  14933. });
  14934. it('should search in specific fields when filtering with a predicate object', function() {
  14935. var searchAny = element(by.model('search.$'));
  14936. searchAny.clear();
  14937. searchAny.sendKeys('i');
  14938. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  14939. });
  14940. it('should use a equal comparison when comparator is true', function() {
  14941. var searchName = element(by.model('search.name'));
  14942. var strict = element(by.model('strict'));
  14943. searchName.clear();
  14944. searchName.sendKeys('Julie');
  14945. strict.click();
  14946. expectFriendNames(['Julie'], 'friendObj');
  14947. });
  14948. </file>
  14949. </example>
  14950. */
  14951. function filterFilter() {
  14952. return function(array, expression, comparator) {
  14953. if (!isArray(array)) return array;
  14954. var comparatorType = typeof(comparator),
  14955. predicates = [];
  14956. predicates.check = function(value, index) {
  14957. for (var j = 0; j < predicates.length; j++) {
  14958. if (!predicates[j](value, index)) {
  14959. return false;
  14960. }
  14961. }
  14962. return true;
  14963. };
  14964. if (comparatorType !== 'function') {
  14965. if (comparatorType === 'boolean' && comparator) {
  14966. comparator = function(obj, text) {
  14967. return angular.equals(obj, text);
  14968. };
  14969. } else {
  14970. comparator = function(obj, text) {
  14971. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  14972. for (var objKey in obj) {
  14973. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  14974. comparator(obj[objKey], text[objKey])) {
  14975. return true;
  14976. }
  14977. }
  14978. return false;
  14979. }
  14980. text = ('' + text).toLowerCase();
  14981. return ('' + obj).toLowerCase().indexOf(text) > -1;
  14982. };
  14983. }
  14984. }
  14985. var search = function(obj, text) {
  14986. if (typeof text === 'string' && text.charAt(0) === '!') {
  14987. return !search(obj, text.substr(1));
  14988. }
  14989. switch (typeof obj) {
  14990. case 'boolean':
  14991. case 'number':
  14992. case 'string':
  14993. return comparator(obj, text);
  14994. case 'object':
  14995. switch (typeof text) {
  14996. case 'object':
  14997. return comparator(obj, text);
  14998. default:
  14999. for (var objKey in obj) {
  15000. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  15001. return true;
  15002. }
  15003. }
  15004. break;
  15005. }
  15006. return false;
  15007. case 'array':
  15008. for (var i = 0; i < obj.length; i++) {
  15009. if (search(obj[i], text)) {
  15010. return true;
  15011. }
  15012. }
  15013. return false;
  15014. default:
  15015. return false;
  15016. }
  15017. };
  15018. switch (typeof expression) {
  15019. case 'boolean':
  15020. case 'number':
  15021. case 'string':
  15022. // Set up expression object and fall through
  15023. expression = {$:expression};
  15024. // jshint -W086
  15025. case 'object':
  15026. // jshint +W086
  15027. for (var key in expression) {
  15028. (function(path) {
  15029. if (typeof expression[path] === 'undefined') return;
  15030. predicates.push(function(value) {
  15031. return search(path == '$' ? value : (value && value[path]), expression[path]);
  15032. });
  15033. })(key);
  15034. }
  15035. break;
  15036. case 'function':
  15037. predicates.push(expression);
  15038. break;
  15039. default:
  15040. return array;
  15041. }
  15042. var filtered = [];
  15043. for (var j = 0; j < array.length; j++) {
  15044. var value = array[j];
  15045. if (predicates.check(value, j)) {
  15046. filtered.push(value);
  15047. }
  15048. }
  15049. return filtered;
  15050. };
  15051. }
  15052. /**
  15053. * @ngdoc filter
  15054. * @name currency
  15055. * @kind function
  15056. *
  15057. * @description
  15058. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  15059. * symbol for current locale is used.
  15060. *
  15061. * @param {number} amount Input to filter.
  15062. * @param {string=} symbol Currency symbol or identifier to be displayed.
  15063. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  15064. * @returns {string} Formatted number.
  15065. *
  15066. *
  15067. * @example
  15068. <example module="currencyExample">
  15069. <file name="index.html">
  15070. <script>
  15071. angular.module('currencyExample', [])
  15072. .controller('ExampleController', ['$scope', function($scope) {
  15073. $scope.amount = 1234.56;
  15074. }]);
  15075. </script>
  15076. <div ng-controller="ExampleController">
  15077. <input type="number" ng-model="amount"> <br>
  15078. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15079. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15080. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15081. </div>
  15082. </file>
  15083. <file name="protractor.js" type="protractor">
  15084. it('should init with 1234.56', function() {
  15085. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15086. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15087. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15088. });
  15089. it('should update', function() {
  15090. if (browser.params.browser == 'safari') {
  15091. // Safari does not understand the minus key. See
  15092. // https://github.com/angular/protractor/issues/481
  15093. return;
  15094. }
  15095. element(by.model('amount')).clear();
  15096. element(by.model('amount')).sendKeys('-1234');
  15097. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15098. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15099. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15100. });
  15101. </file>
  15102. </example>
  15103. */
  15104. currencyFilter.$inject = ['$locale'];
  15105. function currencyFilter($locale) {
  15106. var formats = $locale.NUMBER_FORMATS;
  15107. return function(amount, currencySymbol, fractionSize) {
  15108. if (isUndefined(currencySymbol)) {
  15109. currencySymbol = formats.CURRENCY_SYM;
  15110. }
  15111. if (isUndefined(fractionSize)) {
  15112. fractionSize = formats.PATTERNS[1].maxFrac;
  15113. }
  15114. // if null or undefined pass it through
  15115. return (amount == null)
  15116. ? amount
  15117. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15118. replace(/\u00A4/g, currencySymbol);
  15119. };
  15120. }
  15121. /**
  15122. * @ngdoc filter
  15123. * @name number
  15124. * @kind function
  15125. *
  15126. * @description
  15127. * Formats a number as text.
  15128. *
  15129. * If the input is not a number an empty string is returned.
  15130. *
  15131. * @param {number|string} number Number to format.
  15132. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15133. * If this is not provided then the fraction size is computed from the current locale's number
  15134. * formatting pattern. In the case of the default locale, it will be 3.
  15135. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15136. *
  15137. * @example
  15138. <example module="numberFilterExample">
  15139. <file name="index.html">
  15140. <script>
  15141. angular.module('numberFilterExample', [])
  15142. .controller('ExampleController', ['$scope', function($scope) {
  15143. $scope.val = 1234.56789;
  15144. }]);
  15145. </script>
  15146. <div ng-controller="ExampleController">
  15147. Enter number: <input ng-model='val'><br>
  15148. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15149. No fractions: <span>{{val | number:0}}</span><br>
  15150. Negative number: <span>{{-val | number:4}}</span>
  15151. </div>
  15152. </file>
  15153. <file name="protractor.js" type="protractor">
  15154. it('should format numbers', function() {
  15155. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15156. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15157. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15158. });
  15159. it('should update', function() {
  15160. element(by.model('val')).clear();
  15161. element(by.model('val')).sendKeys('3374.333');
  15162. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15163. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15164. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15165. });
  15166. </file>
  15167. </example>
  15168. */
  15169. numberFilter.$inject = ['$locale'];
  15170. function numberFilter($locale) {
  15171. var formats = $locale.NUMBER_FORMATS;
  15172. return function(number, fractionSize) {
  15173. // if null or undefined pass it through
  15174. return (number == null)
  15175. ? number
  15176. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15177. fractionSize);
  15178. };
  15179. }
  15180. var DECIMAL_SEP = '.';
  15181. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15182. if (!isFinite(number) || isObject(number)) return '';
  15183. var isNegative = number < 0;
  15184. number = Math.abs(number);
  15185. var numStr = number + '',
  15186. formatedText = '',
  15187. parts = [];
  15188. var hasExponent = false;
  15189. if (numStr.indexOf('e') !== -1) {
  15190. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15191. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15192. numStr = '0';
  15193. number = 0;
  15194. } else {
  15195. formatedText = numStr;
  15196. hasExponent = true;
  15197. }
  15198. }
  15199. if (!hasExponent) {
  15200. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15201. // determine fractionSize if it is not specified
  15202. if (isUndefined(fractionSize)) {
  15203. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15204. }
  15205. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15206. // inspired by:
  15207. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15208. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15209. if (number === 0) {
  15210. isNegative = false;
  15211. }
  15212. var fraction = ('' + number).split(DECIMAL_SEP);
  15213. var whole = fraction[0];
  15214. fraction = fraction[1] || '';
  15215. var i, pos = 0,
  15216. lgroup = pattern.lgSize,
  15217. group = pattern.gSize;
  15218. if (whole.length >= (lgroup + group)) {
  15219. pos = whole.length - lgroup;
  15220. for (i = 0; i < pos; i++) {
  15221. if ((pos - i) % group === 0 && i !== 0) {
  15222. formatedText += groupSep;
  15223. }
  15224. formatedText += whole.charAt(i);
  15225. }
  15226. }
  15227. for (i = pos; i < whole.length; i++) {
  15228. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  15229. formatedText += groupSep;
  15230. }
  15231. formatedText += whole.charAt(i);
  15232. }
  15233. // format fraction part.
  15234. while (fraction.length < fractionSize) {
  15235. fraction += '0';
  15236. }
  15237. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15238. } else {
  15239. if (fractionSize > 0 && number > -1 && number < 1) {
  15240. formatedText = number.toFixed(fractionSize);
  15241. }
  15242. }
  15243. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  15244. formatedText,
  15245. isNegative ? pattern.negSuf : pattern.posSuf);
  15246. return parts.join('');
  15247. }
  15248. function padNumber(num, digits, trim) {
  15249. var neg = '';
  15250. if (num < 0) {
  15251. neg = '-';
  15252. num = -num;
  15253. }
  15254. num = '' + num;
  15255. while (num.length < digits) num = '0' + num;
  15256. if (trim)
  15257. num = num.substr(num.length - digits);
  15258. return neg + num;
  15259. }
  15260. function dateGetter(name, size, offset, trim) {
  15261. offset = offset || 0;
  15262. return function(date) {
  15263. var value = date['get' + name]();
  15264. if (offset > 0 || value > -offset)
  15265. value += offset;
  15266. if (value === 0 && offset == -12) value = 12;
  15267. return padNumber(value, size, trim);
  15268. };
  15269. }
  15270. function dateStrGetter(name, shortForm) {
  15271. return function(date, formats) {
  15272. var value = date['get' + name]();
  15273. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15274. return formats[get][value];
  15275. };
  15276. }
  15277. function timeZoneGetter(date) {
  15278. var zone = -1 * date.getTimezoneOffset();
  15279. var paddedZone = (zone >= 0) ? "+" : "";
  15280. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15281. padNumber(Math.abs(zone % 60), 2);
  15282. return paddedZone;
  15283. }
  15284. function getFirstThursdayOfYear(year) {
  15285. // 0 = index of January
  15286. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15287. // 4 = index of Thursday (+1 to account for 1st = 5)
  15288. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15289. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15290. }
  15291. function getThursdayThisWeek(datetime) {
  15292. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15293. // 4 = index of Thursday
  15294. datetime.getDate() + (4 - datetime.getDay()));
  15295. }
  15296. function weekGetter(size) {
  15297. return function(date) {
  15298. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15299. thisThurs = getThursdayThisWeek(date);
  15300. var diff = +thisThurs - +firstThurs,
  15301. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15302. return padNumber(result, size);
  15303. };
  15304. }
  15305. function ampmGetter(date, formats) {
  15306. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15307. }
  15308. var DATE_FORMATS = {
  15309. yyyy: dateGetter('FullYear', 4),
  15310. yy: dateGetter('FullYear', 2, 0, true),
  15311. y: dateGetter('FullYear', 1),
  15312. MMMM: dateStrGetter('Month'),
  15313. MMM: dateStrGetter('Month', true),
  15314. MM: dateGetter('Month', 2, 1),
  15315. M: dateGetter('Month', 1, 1),
  15316. dd: dateGetter('Date', 2),
  15317. d: dateGetter('Date', 1),
  15318. HH: dateGetter('Hours', 2),
  15319. H: dateGetter('Hours', 1),
  15320. hh: dateGetter('Hours', 2, -12),
  15321. h: dateGetter('Hours', 1, -12),
  15322. mm: dateGetter('Minutes', 2),
  15323. m: dateGetter('Minutes', 1),
  15324. ss: dateGetter('Seconds', 2),
  15325. s: dateGetter('Seconds', 1),
  15326. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15327. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15328. sss: dateGetter('Milliseconds', 3),
  15329. EEEE: dateStrGetter('Day'),
  15330. EEE: dateStrGetter('Day', true),
  15331. a: ampmGetter,
  15332. Z: timeZoneGetter,
  15333. ww: weekGetter(2),
  15334. w: weekGetter(1)
  15335. };
  15336. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
  15337. NUMBER_STRING = /^\-?\d+$/;
  15338. /**
  15339. * @ngdoc filter
  15340. * @name date
  15341. * @kind function
  15342. *
  15343. * @description
  15344. * Formats `date` to a string based on the requested `format`.
  15345. *
  15346. * `format` string can be composed of the following elements:
  15347. *
  15348. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15349. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15350. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15351. * * `'MMMM'`: Month in year (January-December)
  15352. * * `'MMM'`: Month in year (Jan-Dec)
  15353. * * `'MM'`: Month in year, padded (01-12)
  15354. * * `'M'`: Month in year (1-12)
  15355. * * `'dd'`: Day in month, padded (01-31)
  15356. * * `'d'`: Day in month (1-31)
  15357. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15358. * * `'EEE'`: Day in Week, (Sun-Sat)
  15359. * * `'HH'`: Hour in day, padded (00-23)
  15360. * * `'H'`: Hour in day (0-23)
  15361. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15362. * * `'h'`: Hour in AM/PM, (1-12)
  15363. * * `'mm'`: Minute in hour, padded (00-59)
  15364. * * `'m'`: Minute in hour (0-59)
  15365. * * `'ss'`: Second in minute, padded (00-59)
  15366. * * `'s'`: Second in minute (0-59)
  15367. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  15368. * * `'a'`: AM/PM marker
  15369. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15370. * * `'ww'`: ISO-8601 week of year (00-53)
  15371. * * `'w'`: ISO-8601 week of year (0-53)
  15372. *
  15373. * `format` string can also be one of the following predefined
  15374. * {@link guide/i18n localizable formats}:
  15375. *
  15376. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15377. * (e.g. Sep 3, 2010 12:05:08 PM)
  15378. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15379. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15380. * (e.g. Friday, September 3, 2010)
  15381. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15382. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15383. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15384. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15385. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15386. *
  15387. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15388. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15389. * (e.g. `"h 'o''clock'"`).
  15390. *
  15391. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15392. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15393. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15394. * specified in the string input, the time is considered to be in the local timezone.
  15395. * @param {string=} format Formatting rules (see Description). If not specified,
  15396. * `mediumDate` is used.
  15397. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15398. * If not specified, the timezone of the browser will be used.
  15399. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15400. *
  15401. * @example
  15402. <example>
  15403. <file name="index.html">
  15404. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15405. <span>{{1288323623006 | date:'medium'}}</span><br>
  15406. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15407. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15408. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15409. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15410. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15411. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15412. </file>
  15413. <file name="protractor.js" type="protractor">
  15414. it('should format date', function() {
  15415. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15416. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15417. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15418. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15419. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15420. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15421. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15422. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15423. });
  15424. </file>
  15425. </example>
  15426. */
  15427. dateFilter.$inject = ['$locale'];
  15428. function dateFilter($locale) {
  15429. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15430. // 1 2 3 4 5 6 7 8 9 10 11
  15431. function jsonStringToDate(string) {
  15432. var match;
  15433. if (match = string.match(R_ISO8601_STR)) {
  15434. var date = new Date(0),
  15435. tzHour = 0,
  15436. tzMin = 0,
  15437. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15438. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15439. if (match[9]) {
  15440. tzHour = int(match[9] + match[10]);
  15441. tzMin = int(match[9] + match[11]);
  15442. }
  15443. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15444. var h = int(match[4] || 0) - tzHour;
  15445. var m = int(match[5] || 0) - tzMin;
  15446. var s = int(match[6] || 0);
  15447. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  15448. timeSetter.call(date, h, m, s, ms);
  15449. return date;
  15450. }
  15451. return string;
  15452. }
  15453. return function(date, format, timezone) {
  15454. var text = '',
  15455. parts = [],
  15456. fn, match;
  15457. format = format || 'mediumDate';
  15458. format = $locale.DATETIME_FORMATS[format] || format;
  15459. if (isString(date)) {
  15460. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15461. }
  15462. if (isNumber(date)) {
  15463. date = new Date(date);
  15464. }
  15465. if (!isDate(date)) {
  15466. return date;
  15467. }
  15468. while (format) {
  15469. match = DATE_FORMATS_SPLIT.exec(format);
  15470. if (match) {
  15471. parts = concat(parts, match, 1);
  15472. format = parts.pop();
  15473. } else {
  15474. parts.push(format);
  15475. format = null;
  15476. }
  15477. }
  15478. if (timezone && timezone === 'UTC') {
  15479. date = new Date(date.getTime());
  15480. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15481. }
  15482. forEach(parts, function(value) {
  15483. fn = DATE_FORMATS[value];
  15484. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15485. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15486. });
  15487. return text;
  15488. };
  15489. }
  15490. /**
  15491. * @ngdoc filter
  15492. * @name json
  15493. * @kind function
  15494. *
  15495. * @description
  15496. * Allows you to convert a JavaScript object into JSON string.
  15497. *
  15498. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15499. * the binding is automatically converted to JSON.
  15500. *
  15501. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15502. * @returns {string} JSON string.
  15503. *
  15504. *
  15505. * @example
  15506. <example>
  15507. <file name="index.html">
  15508. <pre>{{ {'name':'value'} | json }}</pre>
  15509. </file>
  15510. <file name="protractor.js" type="protractor">
  15511. it('should jsonify filtered objects', function() {
  15512. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15513. });
  15514. </file>
  15515. </example>
  15516. *
  15517. */
  15518. function jsonFilter() {
  15519. return function(object) {
  15520. return toJson(object, true);
  15521. };
  15522. }
  15523. /**
  15524. * @ngdoc filter
  15525. * @name lowercase
  15526. * @kind function
  15527. * @description
  15528. * Converts string to lowercase.
  15529. * @see angular.lowercase
  15530. */
  15531. var lowercaseFilter = valueFn(lowercase);
  15532. /**
  15533. * @ngdoc filter
  15534. * @name uppercase
  15535. * @kind function
  15536. * @description
  15537. * Converts string to uppercase.
  15538. * @see angular.uppercase
  15539. */
  15540. var uppercaseFilter = valueFn(uppercase);
  15541. /**
  15542. * @ngdoc filter
  15543. * @name limitTo
  15544. * @kind function
  15545. *
  15546. * @description
  15547. * Creates a new array or string containing only a specified number of elements. The elements
  15548. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15549. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15550. * converted to a string.
  15551. *
  15552. * @param {Array|string|number} input Source array, string or number to be limited.
  15553. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15554. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15555. * If the number is negative, `limit` number of items from the end of the source array/string
  15556. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15557. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15558. * had less than `limit` elements.
  15559. *
  15560. * @example
  15561. <example module="limitToExample">
  15562. <file name="index.html">
  15563. <script>
  15564. angular.module('limitToExample', [])
  15565. .controller('ExampleController', ['$scope', function($scope) {
  15566. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15567. $scope.letters = "abcdefghi";
  15568. $scope.longNumber = 2345432342;
  15569. $scope.numLimit = 3;
  15570. $scope.letterLimit = 3;
  15571. $scope.longNumberLimit = 3;
  15572. }]);
  15573. </script>
  15574. <div ng-controller="ExampleController">
  15575. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15576. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15577. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15578. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15579. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15580. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15581. </div>
  15582. </file>
  15583. <file name="protractor.js" type="protractor">
  15584. var numLimitInput = element(by.model('numLimit'));
  15585. var letterLimitInput = element(by.model('letterLimit'));
  15586. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15587. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15588. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15589. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15590. it('should limit the number array to first three items', function() {
  15591. expect(numLimitInput.getAttribute('value')).toBe('3');
  15592. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15593. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15594. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15595. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15596. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15597. });
  15598. // There is a bug in safari and protractor that doesn't like the minus key
  15599. // it('should update the output when -3 is entered', function() {
  15600. // numLimitInput.clear();
  15601. // numLimitInput.sendKeys('-3');
  15602. // letterLimitInput.clear();
  15603. // letterLimitInput.sendKeys('-3');
  15604. // longNumberLimitInput.clear();
  15605. // longNumberLimitInput.sendKeys('-3');
  15606. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15607. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15608. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15609. // });
  15610. it('should not exceed the maximum size of input array', function() {
  15611. numLimitInput.clear();
  15612. numLimitInput.sendKeys('100');
  15613. letterLimitInput.clear();
  15614. letterLimitInput.sendKeys('100');
  15615. longNumberLimitInput.clear();
  15616. longNumberLimitInput.sendKeys('100');
  15617. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15618. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15619. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15620. });
  15621. </file>
  15622. </example>
  15623. */
  15624. function limitToFilter() {
  15625. return function(input, limit) {
  15626. if (isNumber(input)) input = input.toString();
  15627. if (!isArray(input) && !isString(input)) return input;
  15628. if (Math.abs(Number(limit)) === Infinity) {
  15629. limit = Number(limit);
  15630. } else {
  15631. limit = int(limit);
  15632. }
  15633. if (isString(input)) {
  15634. //NaN check on limit
  15635. if (limit) {
  15636. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  15637. } else {
  15638. return "";
  15639. }
  15640. }
  15641. var out = [],
  15642. i, n;
  15643. // if abs(limit) exceeds maximum length, trim it
  15644. if (limit > input.length)
  15645. limit = input.length;
  15646. else if (limit < -input.length)
  15647. limit = -input.length;
  15648. if (limit > 0) {
  15649. i = 0;
  15650. n = limit;
  15651. } else {
  15652. i = input.length + limit;
  15653. n = input.length;
  15654. }
  15655. for (; i < n; i++) {
  15656. out.push(input[i]);
  15657. }
  15658. return out;
  15659. };
  15660. }
  15661. /**
  15662. * @ngdoc filter
  15663. * @name orderBy
  15664. * @kind function
  15665. *
  15666. * @description
  15667. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15668. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15669. * correctly, make sure they are actually being saved as numbers and not strings.
  15670. *
  15671. * @param {Array} array The array to sort.
  15672. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15673. * used by the comparator to determine the order of elements.
  15674. *
  15675. * Can be one of:
  15676. *
  15677. * - `function`: Getter function. The result of this function will be sorted using the
  15678. * `<`, `=`, `>` operator.
  15679. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15680. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15681. * 3 first characters of a property called `name`). The result of a constant expression
  15682. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15683. * to sort object by the value of their `special name` property). An expression can be
  15684. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15685. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15686. * element itself is used to compare where sorting.
  15687. * - `Array`: An array of function or string predicates. The first predicate in the array
  15688. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15689. *
  15690. * If the predicate is missing or empty then it defaults to `'+'`.
  15691. *
  15692. * @param {boolean=} reverse Reverse the order of the array.
  15693. * @returns {Array} Sorted copy of the source array.
  15694. *
  15695. * @example
  15696. <example module="orderByExample">
  15697. <file name="index.html">
  15698. <script>
  15699. angular.module('orderByExample', [])
  15700. .controller('ExampleController', ['$scope', function($scope) {
  15701. $scope.friends =
  15702. [{name:'John', phone:'555-1212', age:10},
  15703. {name:'Mary', phone:'555-9876', age:19},
  15704. {name:'Mike', phone:'555-4321', age:21},
  15705. {name:'Adam', phone:'555-5678', age:35},
  15706. {name:'Julie', phone:'555-8765', age:29}];
  15707. $scope.predicate = '-age';
  15708. }]);
  15709. </script>
  15710. <div ng-controller="ExampleController">
  15711. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15712. <hr/>
  15713. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15714. <table class="friend">
  15715. <tr>
  15716. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15717. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15718. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15719. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15720. </tr>
  15721. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15722. <td>{{friend.name}}</td>
  15723. <td>{{friend.phone}}</td>
  15724. <td>{{friend.age}}</td>
  15725. </tr>
  15726. </table>
  15727. </div>
  15728. </file>
  15729. </example>
  15730. *
  15731. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15732. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15733. * desired parameters.
  15734. *
  15735. * Example:
  15736. *
  15737. * @example
  15738. <example module="orderByExample">
  15739. <file name="index.html">
  15740. <div ng-controller="ExampleController">
  15741. <table class="friend">
  15742. <tr>
  15743. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15744. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15745. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15746. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15747. </tr>
  15748. <tr ng-repeat="friend in friends">
  15749. <td>{{friend.name}}</td>
  15750. <td>{{friend.phone}}</td>
  15751. <td>{{friend.age}}</td>
  15752. </tr>
  15753. </table>
  15754. </div>
  15755. </file>
  15756. <file name="script.js">
  15757. angular.module('orderByExample', [])
  15758. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15759. var orderBy = $filter('orderBy');
  15760. $scope.friends = [
  15761. { name: 'John', phone: '555-1212', age: 10 },
  15762. { name: 'Mary', phone: '555-9876', age: 19 },
  15763. { name: 'Mike', phone: '555-4321', age: 21 },
  15764. { name: 'Adam', phone: '555-5678', age: 35 },
  15765. { name: 'Julie', phone: '555-8765', age: 29 }
  15766. ];
  15767. $scope.order = function(predicate, reverse) {
  15768. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15769. };
  15770. $scope.order('-age',false);
  15771. }]);
  15772. </file>
  15773. </example>
  15774. */
  15775. orderByFilter.$inject = ['$parse'];
  15776. function orderByFilter($parse) {
  15777. return function(array, sortPredicate, reverseOrder) {
  15778. if (!(isArrayLike(array))) return array;
  15779. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  15780. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15781. sortPredicate = sortPredicate.map(function(predicate) {
  15782. var descending = false, get = predicate || identity;
  15783. if (isString(predicate)) {
  15784. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15785. descending = predicate.charAt(0) == '-';
  15786. predicate = predicate.substring(1);
  15787. }
  15788. if (predicate === '') {
  15789. // Effectively no predicate was passed so we compare identity
  15790. return reverseComparator(function(a, b) {
  15791. return compare(a, b);
  15792. }, descending);
  15793. }
  15794. get = $parse(predicate);
  15795. if (get.constant) {
  15796. var key = get();
  15797. return reverseComparator(function(a, b) {
  15798. return compare(a[key], b[key]);
  15799. }, descending);
  15800. }
  15801. }
  15802. return reverseComparator(function(a, b) {
  15803. return compare(get(a),get(b));
  15804. }, descending);
  15805. });
  15806. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  15807. function comparator(o1, o2) {
  15808. for (var i = 0; i < sortPredicate.length; i++) {
  15809. var comp = sortPredicate[i](o1, o2);
  15810. if (comp !== 0) return comp;
  15811. }
  15812. return 0;
  15813. }
  15814. function reverseComparator(comp, descending) {
  15815. return descending
  15816. ? function(a, b) {return comp(b,a);}
  15817. : comp;
  15818. }
  15819. function compare(v1, v2) {
  15820. var t1 = typeof v1;
  15821. var t2 = typeof v2;
  15822. if (t1 == t2) {
  15823. if (isDate(v1) && isDate(v2)) {
  15824. v1 = v1.valueOf();
  15825. v2 = v2.valueOf();
  15826. }
  15827. if (t1 == "string") {
  15828. v1 = v1.toLowerCase();
  15829. v2 = v2.toLowerCase();
  15830. }
  15831. if (v1 === v2) return 0;
  15832. return v1 < v2 ? -1 : 1;
  15833. } else {
  15834. return t1 < t2 ? -1 : 1;
  15835. }
  15836. }
  15837. };
  15838. }
  15839. function ngDirective(directive) {
  15840. if (isFunction(directive)) {
  15841. directive = {
  15842. link: directive
  15843. };
  15844. }
  15845. directive.restrict = directive.restrict || 'AC';
  15846. return valueFn(directive);
  15847. }
  15848. /**
  15849. * @ngdoc directive
  15850. * @name a
  15851. * @restrict E
  15852. *
  15853. * @description
  15854. * Modifies the default behavior of the html A tag so that the default action is prevented when
  15855. * the href attribute is empty.
  15856. *
  15857. * This change permits the easy creation of action links with the `ngClick` directive
  15858. * without changing the location or causing page reloads, e.g.:
  15859. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  15860. */
  15861. var htmlAnchorDirective = valueFn({
  15862. restrict: 'E',
  15863. compile: function(element, attr) {
  15864. if (!attr.href && !attr.xlinkHref && !attr.name) {
  15865. return function(scope, element) {
  15866. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  15867. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  15868. 'xlink:href' : 'href';
  15869. element.on('click', function(event) {
  15870. // if we have no href url, then don't navigate anywhere.
  15871. if (!element.attr(href)) {
  15872. event.preventDefault();
  15873. }
  15874. });
  15875. };
  15876. }
  15877. }
  15878. });
  15879. /**
  15880. * @ngdoc directive
  15881. * @name ngHref
  15882. * @restrict A
  15883. * @priority 99
  15884. *
  15885. * @description
  15886. * Using Angular markup like `{{hash}}` in an href attribute will
  15887. * make the link go to the wrong URL if the user clicks it before
  15888. * Angular has a chance to replace the `{{hash}}` markup with its
  15889. * value. Until Angular replaces the markup the link will be broken
  15890. * and will most likely return a 404 error.
  15891. *
  15892. * The `ngHref` directive solves this problem.
  15893. *
  15894. * The wrong way to write it:
  15895. * ```html
  15896. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15897. * ```
  15898. *
  15899. * The correct way to write it:
  15900. * ```html
  15901. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15902. * ```
  15903. *
  15904. * @element A
  15905. * @param {template} ngHref any string which can contain `{{}}` markup.
  15906. *
  15907. * @example
  15908. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  15909. * in links and their different behaviors:
  15910. <example>
  15911. <file name="index.html">
  15912. <input ng-model="value" /><br />
  15913. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  15914. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  15915. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  15916. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  15917. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  15918. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  15919. </file>
  15920. <file name="protractor.js" type="protractor">
  15921. it('should execute ng-click but not reload when href without value', function() {
  15922. element(by.id('link-1')).click();
  15923. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  15924. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  15925. });
  15926. it('should execute ng-click but not reload when href empty string', function() {
  15927. element(by.id('link-2')).click();
  15928. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  15929. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  15930. });
  15931. it('should execute ng-click and change url when ng-href specified', function() {
  15932. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  15933. element(by.id('link-3')).click();
  15934. // At this point, we navigate away from an Angular page, so we need
  15935. // to use browser.driver to get the base webdriver.
  15936. browser.wait(function() {
  15937. return browser.driver.getCurrentUrl().then(function(url) {
  15938. return url.match(/\/123$/);
  15939. });
  15940. }, 5000, 'page should navigate to /123');
  15941. });
  15942. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  15943. element(by.id('link-4')).click();
  15944. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  15945. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  15946. });
  15947. it('should execute ng-click but not reload when no href but name specified', function() {
  15948. element(by.id('link-5')).click();
  15949. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  15950. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  15951. });
  15952. it('should only change url when only ng-href', function() {
  15953. element(by.model('value')).clear();
  15954. element(by.model('value')).sendKeys('6');
  15955. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  15956. element(by.id('link-6')).click();
  15957. // At this point, we navigate away from an Angular page, so we need
  15958. // to use browser.driver to get the base webdriver.
  15959. browser.wait(function() {
  15960. return browser.driver.getCurrentUrl().then(function(url) {
  15961. return url.match(/\/6$/);
  15962. });
  15963. }, 5000, 'page should navigate to /6');
  15964. });
  15965. </file>
  15966. </example>
  15967. */
  15968. /**
  15969. * @ngdoc directive
  15970. * @name ngSrc
  15971. * @restrict A
  15972. * @priority 99
  15973. *
  15974. * @description
  15975. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  15976. * work right: The browser will fetch from the URL with the literal
  15977. * text `{{hash}}` until Angular replaces the expression inside
  15978. * `{{hash}}`. The `ngSrc` directive solves this problem.
  15979. *
  15980. * The buggy way to write it:
  15981. * ```html
  15982. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  15983. * ```
  15984. *
  15985. * The correct way to write it:
  15986. * ```html
  15987. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  15988. * ```
  15989. *
  15990. * @element IMG
  15991. * @param {template} ngSrc any string which can contain `{{}}` markup.
  15992. */
  15993. /**
  15994. * @ngdoc directive
  15995. * @name ngSrcset
  15996. * @restrict A
  15997. * @priority 99
  15998. *
  15999. * @description
  16000. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  16001. * work right: The browser will fetch from the URL with the literal
  16002. * text `{{hash}}` until Angular replaces the expression inside
  16003. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  16004. *
  16005. * The buggy way to write it:
  16006. * ```html
  16007. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16008. * ```
  16009. *
  16010. * The correct way to write it:
  16011. * ```html
  16012. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  16013. * ```
  16014. *
  16015. * @element IMG
  16016. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  16017. */
  16018. /**
  16019. * @ngdoc directive
  16020. * @name ngDisabled
  16021. * @restrict A
  16022. * @priority 100
  16023. *
  16024. * @description
  16025. *
  16026. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  16027. * ```html
  16028. * <div ng-init="scope = { isDisabled: false }">
  16029. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  16030. * </div>
  16031. * ```
  16032. *
  16033. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16034. * such as disabled. (Their presence means true and their absence means false.)
  16035. * If we put an Angular interpolation expression into such an attribute then the
  16036. * binding information would be lost when the browser removes the attribute.
  16037. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  16038. * This complementary directive is not removed by the browser and so provides
  16039. * a permanent reliable place to store the binding information.
  16040. *
  16041. * @example
  16042. <example>
  16043. <file name="index.html">
  16044. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  16045. <button ng-model="button" ng-disabled="checked">Button</button>
  16046. </file>
  16047. <file name="protractor.js" type="protractor">
  16048. it('should toggle button', function() {
  16049. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  16050. element(by.model('checked')).click();
  16051. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  16052. });
  16053. </file>
  16054. </example>
  16055. *
  16056. * @element INPUT
  16057. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  16058. * then special attribute "disabled" will be set on the element
  16059. */
  16060. /**
  16061. * @ngdoc directive
  16062. * @name ngChecked
  16063. * @restrict A
  16064. * @priority 100
  16065. *
  16066. * @description
  16067. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16068. * such as checked. (Their presence means true and their absence means false.)
  16069. * If we put an Angular interpolation expression into such an attribute then the
  16070. * binding information would be lost when the browser removes the attribute.
  16071. * The `ngChecked` directive solves this problem for the `checked` attribute.
  16072. * This complementary directive is not removed by the browser and so provides
  16073. * a permanent reliable place to store the binding information.
  16074. * @example
  16075. <example>
  16076. <file name="index.html">
  16077. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16078. <input id="checkSlave" type="checkbox" ng-checked="master">
  16079. </file>
  16080. <file name="protractor.js" type="protractor">
  16081. it('should check both checkBoxes', function() {
  16082. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16083. element(by.model('master')).click();
  16084. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16085. });
  16086. </file>
  16087. </example>
  16088. *
  16089. * @element INPUT
  16090. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16091. * then special attribute "checked" will be set on the element
  16092. */
  16093. /**
  16094. * @ngdoc directive
  16095. * @name ngReadonly
  16096. * @restrict A
  16097. * @priority 100
  16098. *
  16099. * @description
  16100. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16101. * such as readonly. (Their presence means true and their absence means false.)
  16102. * If we put an Angular interpolation expression into such an attribute then the
  16103. * binding information would be lost when the browser removes the attribute.
  16104. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16105. * This complementary directive is not removed by the browser and so provides
  16106. * a permanent reliable place to store the binding information.
  16107. * @example
  16108. <example>
  16109. <file name="index.html">
  16110. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16111. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16112. </file>
  16113. <file name="protractor.js" type="protractor">
  16114. it('should toggle readonly attr', function() {
  16115. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16116. element(by.model('checked')).click();
  16117. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16118. });
  16119. </file>
  16120. </example>
  16121. *
  16122. * @element INPUT
  16123. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16124. * then special attribute "readonly" will be set on the element
  16125. */
  16126. /**
  16127. * @ngdoc directive
  16128. * @name ngSelected
  16129. * @restrict A
  16130. * @priority 100
  16131. *
  16132. * @description
  16133. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16134. * such as selected. (Their presence means true and their absence means false.)
  16135. * If we put an Angular interpolation expression into such an attribute then the
  16136. * binding information would be lost when the browser removes the attribute.
  16137. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16138. * This complementary directive is not removed by the browser and so provides
  16139. * a permanent reliable place to store the binding information.
  16140. *
  16141. * @example
  16142. <example>
  16143. <file name="index.html">
  16144. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16145. <select>
  16146. <option>Hello!</option>
  16147. <option id="greet" ng-selected="selected">Greetings!</option>
  16148. </select>
  16149. </file>
  16150. <file name="protractor.js" type="protractor">
  16151. it('should select Greetings!', function() {
  16152. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16153. element(by.model('selected')).click();
  16154. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16155. });
  16156. </file>
  16157. </example>
  16158. *
  16159. * @element OPTION
  16160. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16161. * then special attribute "selected" will be set on the element
  16162. */
  16163. /**
  16164. * @ngdoc directive
  16165. * @name ngOpen
  16166. * @restrict A
  16167. * @priority 100
  16168. *
  16169. * @description
  16170. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16171. * such as open. (Their presence means true and their absence means false.)
  16172. * If we put an Angular interpolation expression into such an attribute then the
  16173. * binding information would be lost when the browser removes the attribute.
  16174. * The `ngOpen` directive solves this problem for the `open` attribute.
  16175. * This complementary directive is not removed by the browser and so provides
  16176. * a permanent reliable place to store the binding information.
  16177. * @example
  16178. <example>
  16179. <file name="index.html">
  16180. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16181. <details id="details" ng-open="open">
  16182. <summary>Show/Hide me</summary>
  16183. </details>
  16184. </file>
  16185. <file name="protractor.js" type="protractor">
  16186. it('should toggle open', function() {
  16187. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16188. element(by.model('open')).click();
  16189. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16190. });
  16191. </file>
  16192. </example>
  16193. *
  16194. * @element DETAILS
  16195. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16196. * then special attribute "open" will be set on the element
  16197. */
  16198. var ngAttributeAliasDirectives = {};
  16199. // boolean attrs are evaluated
  16200. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16201. // binding to multiple is not supported
  16202. if (propName == "multiple") return;
  16203. var normalized = directiveNormalize('ng-' + attrName);
  16204. ngAttributeAliasDirectives[normalized] = function() {
  16205. return {
  16206. restrict: 'A',
  16207. priority: 100,
  16208. link: function(scope, element, attr) {
  16209. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16210. attr.$set(attrName, !!value);
  16211. });
  16212. }
  16213. };
  16214. };
  16215. });
  16216. // aliased input attrs are evaluated
  16217. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16218. ngAttributeAliasDirectives[ngAttr] = function() {
  16219. return {
  16220. priority: 100,
  16221. link: function(scope, element, attr) {
  16222. //special case ngPattern when a literal regular expression value
  16223. //is used as the expression (this way we don't have to watch anything).
  16224. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16225. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16226. if (match) {
  16227. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16228. return;
  16229. }
  16230. }
  16231. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16232. attr.$set(ngAttr, value);
  16233. });
  16234. }
  16235. };
  16236. };
  16237. });
  16238. // ng-src, ng-srcset, ng-href are interpolated
  16239. forEach(['src', 'srcset', 'href'], function(attrName) {
  16240. var normalized = directiveNormalize('ng-' + attrName);
  16241. ngAttributeAliasDirectives[normalized] = function() {
  16242. return {
  16243. priority: 99, // it needs to run after the attributes are interpolated
  16244. link: function(scope, element, attr) {
  16245. var propName = attrName,
  16246. name = attrName;
  16247. if (attrName === 'href' &&
  16248. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16249. name = 'xlinkHref';
  16250. attr.$attr[name] = 'xlink:href';
  16251. propName = null;
  16252. }
  16253. attr.$observe(normalized, function(value) {
  16254. if (!value) {
  16255. if (attrName === 'href') {
  16256. attr.$set(name, null);
  16257. }
  16258. return;
  16259. }
  16260. attr.$set(name, value);
  16261. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16262. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16263. // to set the property as well to achieve the desired effect.
  16264. // we use attr[attrName] value since $set can sanitize the url.
  16265. if (msie && propName) element.prop(propName, attr[name]);
  16266. });
  16267. }
  16268. };
  16269. };
  16270. });
  16271. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16272. */
  16273. var nullFormCtrl = {
  16274. $addControl: noop,
  16275. $$renameControl: nullFormRenameControl,
  16276. $removeControl: noop,
  16277. $setValidity: noop,
  16278. $setDirty: noop,
  16279. $setPristine: noop,
  16280. $setSubmitted: noop
  16281. },
  16282. SUBMITTED_CLASS = 'ng-submitted';
  16283. function nullFormRenameControl(control, name) {
  16284. control.$name = name;
  16285. }
  16286. /**
  16287. * @ngdoc type
  16288. * @name form.FormController
  16289. *
  16290. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16291. * @property {boolean} $dirty True if user has already interacted with the form.
  16292. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16293. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16294. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16295. *
  16296. * @property {Object} $error Is an object hash, containing references to controls or
  16297. * forms with failing validators, where:
  16298. *
  16299. * - keys are validation tokens (error names),
  16300. * - values are arrays of controls or forms that have a failing validator for given error name.
  16301. *
  16302. * Built-in validation tokens:
  16303. *
  16304. * - `email`
  16305. * - `max`
  16306. * - `maxlength`
  16307. * - `min`
  16308. * - `minlength`
  16309. * - `number`
  16310. * - `pattern`
  16311. * - `required`
  16312. * - `url`
  16313. * - `date`
  16314. * - `datetimelocal`
  16315. * - `time`
  16316. * - `week`
  16317. * - `month`
  16318. *
  16319. * @description
  16320. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16321. * such as being valid/invalid or dirty/pristine.
  16322. *
  16323. * Each {@link ng.directive:form form} directive creates an instance
  16324. * of `FormController`.
  16325. *
  16326. */
  16327. //asks for $scope to fool the BC controller module
  16328. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16329. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16330. var form = this,
  16331. controls = [];
  16332. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16333. // init state
  16334. form.$error = {};
  16335. form.$$success = {};
  16336. form.$pending = undefined;
  16337. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16338. form.$dirty = false;
  16339. form.$pristine = true;
  16340. form.$valid = true;
  16341. form.$invalid = false;
  16342. form.$submitted = false;
  16343. parentForm.$addControl(form);
  16344. /**
  16345. * @ngdoc method
  16346. * @name form.FormController#$rollbackViewValue
  16347. *
  16348. * @description
  16349. * Rollback all form controls pending updates to the `$modelValue`.
  16350. *
  16351. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16352. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16353. * a form that uses `ng-model-options` to pend updates.
  16354. */
  16355. form.$rollbackViewValue = function() {
  16356. forEach(controls, function(control) {
  16357. control.$rollbackViewValue();
  16358. });
  16359. };
  16360. /**
  16361. * @ngdoc method
  16362. * @name form.FormController#$commitViewValue
  16363. *
  16364. * @description
  16365. * Commit all form controls pending updates to the `$modelValue`.
  16366. *
  16367. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16368. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16369. * usually handles calling this in response to input events.
  16370. */
  16371. form.$commitViewValue = function() {
  16372. forEach(controls, function(control) {
  16373. control.$commitViewValue();
  16374. });
  16375. };
  16376. /**
  16377. * @ngdoc method
  16378. * @name form.FormController#$addControl
  16379. *
  16380. * @description
  16381. * Register a control with the form.
  16382. *
  16383. * Input elements using ngModelController do this automatically when they are linked.
  16384. */
  16385. form.$addControl = function(control) {
  16386. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16387. // and not added to the scope. Now we throw an error.
  16388. assertNotHasOwnProperty(control.$name, 'input');
  16389. controls.push(control);
  16390. if (control.$name) {
  16391. form[control.$name] = control;
  16392. }
  16393. };
  16394. // Private API: rename a form control
  16395. form.$$renameControl = function(control, newName) {
  16396. var oldName = control.$name;
  16397. if (form[oldName] === control) {
  16398. delete form[oldName];
  16399. }
  16400. form[newName] = control;
  16401. control.$name = newName;
  16402. };
  16403. /**
  16404. * @ngdoc method
  16405. * @name form.FormController#$removeControl
  16406. *
  16407. * @description
  16408. * Deregister a control from the form.
  16409. *
  16410. * Input elements using ngModelController do this automatically when they are destroyed.
  16411. */
  16412. form.$removeControl = function(control) {
  16413. if (control.$name && form[control.$name] === control) {
  16414. delete form[control.$name];
  16415. }
  16416. forEach(form.$pending, function(value, name) {
  16417. form.$setValidity(name, null, control);
  16418. });
  16419. forEach(form.$error, function(value, name) {
  16420. form.$setValidity(name, null, control);
  16421. });
  16422. arrayRemove(controls, control);
  16423. };
  16424. /**
  16425. * @ngdoc method
  16426. * @name form.FormController#$setValidity
  16427. *
  16428. * @description
  16429. * Sets the validity of a form control.
  16430. *
  16431. * This method will also propagate to parent forms.
  16432. */
  16433. addSetValidityMethod({
  16434. ctrl: this,
  16435. $element: element,
  16436. set: function(object, property, control) {
  16437. var list = object[property];
  16438. if (!list) {
  16439. object[property] = [control];
  16440. } else {
  16441. var index = list.indexOf(control);
  16442. if (index === -1) {
  16443. list.push(control);
  16444. }
  16445. }
  16446. },
  16447. unset: function(object, property, control) {
  16448. var list = object[property];
  16449. if (!list) {
  16450. return;
  16451. }
  16452. arrayRemove(list, control);
  16453. if (list.length === 0) {
  16454. delete object[property];
  16455. }
  16456. },
  16457. parentForm: parentForm,
  16458. $animate: $animate
  16459. });
  16460. /**
  16461. * @ngdoc method
  16462. * @name form.FormController#$setDirty
  16463. *
  16464. * @description
  16465. * Sets the form to a dirty state.
  16466. *
  16467. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16468. * state (ng-dirty class). This method will also propagate to parent forms.
  16469. */
  16470. form.$setDirty = function() {
  16471. $animate.removeClass(element, PRISTINE_CLASS);
  16472. $animate.addClass(element, DIRTY_CLASS);
  16473. form.$dirty = true;
  16474. form.$pristine = false;
  16475. parentForm.$setDirty();
  16476. };
  16477. /**
  16478. * @ngdoc method
  16479. * @name form.FormController#$setPristine
  16480. *
  16481. * @description
  16482. * Sets the form to its pristine state.
  16483. *
  16484. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16485. * state (ng-pristine class). This method will also propagate to all the controls contained
  16486. * in this form.
  16487. *
  16488. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16489. * saving or resetting it.
  16490. */
  16491. form.$setPristine = function() {
  16492. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16493. form.$dirty = false;
  16494. form.$pristine = true;
  16495. form.$submitted = false;
  16496. forEach(controls, function(control) {
  16497. control.$setPristine();
  16498. });
  16499. };
  16500. /**
  16501. * @ngdoc method
  16502. * @name form.FormController#$setUntouched
  16503. *
  16504. * @description
  16505. * Sets the form to its untouched state.
  16506. *
  16507. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16508. * untouched state (ng-untouched class).
  16509. *
  16510. * Setting a form controls back to their untouched state is often useful when setting the form
  16511. * back to its pristine state.
  16512. */
  16513. form.$setUntouched = function() {
  16514. forEach(controls, function(control) {
  16515. control.$setUntouched();
  16516. });
  16517. };
  16518. /**
  16519. * @ngdoc method
  16520. * @name form.FormController#$setSubmitted
  16521. *
  16522. * @description
  16523. * Sets the form to its submitted state.
  16524. */
  16525. form.$setSubmitted = function() {
  16526. $animate.addClass(element, SUBMITTED_CLASS);
  16527. form.$submitted = true;
  16528. parentForm.$setSubmitted();
  16529. };
  16530. }
  16531. /**
  16532. * @ngdoc directive
  16533. * @name ngForm
  16534. * @restrict EAC
  16535. *
  16536. * @description
  16537. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16538. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16539. * sub-group of controls needs to be determined.
  16540. *
  16541. * Note: the purpose of `ngForm` is to group controls,
  16542. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16543. * (e.g. posting to the server, ...).
  16544. *
  16545. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16546. * related scope, under this name.
  16547. *
  16548. */
  16549. /**
  16550. * @ngdoc directive
  16551. * @name form
  16552. * @restrict E
  16553. *
  16554. * @description
  16555. * Directive that instantiates
  16556. * {@link form.FormController FormController}.
  16557. *
  16558. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16559. * this name.
  16560. *
  16561. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16562. *
  16563. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  16564. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16565. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16566. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16567. * using Angular validation directives in forms that are dynamically generated using the
  16568. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16569. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16570. * `ngForm` directive and nest these in an outer `form` element.
  16571. *
  16572. *
  16573. * # CSS classes
  16574. * - `ng-valid` is set if the form is valid.
  16575. * - `ng-invalid` is set if the form is invalid.
  16576. * - `ng-pristine` is set if the form is pristine.
  16577. * - `ng-dirty` is set if the form is dirty.
  16578. * - `ng-submitted` is set if the form was submitted.
  16579. *
  16580. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16581. *
  16582. *
  16583. * # Submitting a form and preventing the default action
  16584. *
  16585. * Since the role of forms in client-side Angular applications is different than in classical
  16586. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16587. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16588. * to handle the form submission in an application-specific way.
  16589. *
  16590. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16591. * `<form>` element has an `action` attribute specified.
  16592. *
  16593. * You can use one of the following two ways to specify what javascript method should be called when
  16594. * a form is submitted:
  16595. *
  16596. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16597. * - {@link ng.directive:ngClick ngClick} directive on the first
  16598. * button or input field of type submit (input[type=submit])
  16599. *
  16600. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16601. * or {@link ng.directive:ngClick ngClick} directives.
  16602. * This is because of the following form submission rules in the HTML specification:
  16603. *
  16604. * - If a form has only one input field then hitting enter in this field triggers form submit
  16605. * (`ngSubmit`)
  16606. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16607. * doesn't trigger submit
  16608. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16609. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16610. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16611. *
  16612. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16613. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16614. * to have access to the updated model.
  16615. *
  16616. * ## Animation Hooks
  16617. *
  16618. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16619. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16620. * other validations that are performed within the form. Animations in ngForm are similar to how
  16621. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16622. * as JS animations.
  16623. *
  16624. * The following example shows a simple way to utilize CSS transitions to style a form element
  16625. * that has been rendered as invalid after it has been validated:
  16626. *
  16627. * <pre>
  16628. * //be sure to include ngAnimate as a module to hook into more
  16629. * //advanced animations
  16630. * .my-form {
  16631. * transition:0.5s linear all;
  16632. * background: white;
  16633. * }
  16634. * .my-form.ng-invalid {
  16635. * background: red;
  16636. * color:white;
  16637. * }
  16638. * </pre>
  16639. *
  16640. * @example
  16641. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16642. <file name="index.html">
  16643. <script>
  16644. angular.module('formExample', [])
  16645. .controller('FormController', ['$scope', function($scope) {
  16646. $scope.userType = 'guest';
  16647. }]);
  16648. </script>
  16649. <style>
  16650. .my-form {
  16651. -webkit-transition:all linear 0.5s;
  16652. transition:all linear 0.5s;
  16653. background: transparent;
  16654. }
  16655. .my-form.ng-invalid {
  16656. background: red;
  16657. }
  16658. </style>
  16659. <form name="myForm" ng-controller="FormController" class="my-form">
  16660. userType: <input name="input" ng-model="userType" required>
  16661. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16662. <tt>userType = {{userType}}</tt><br>
  16663. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16664. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16665. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16666. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16667. </form>
  16668. </file>
  16669. <file name="protractor.js" type="protractor">
  16670. it('should initialize to model', function() {
  16671. var userType = element(by.binding('userType'));
  16672. var valid = element(by.binding('myForm.input.$valid'));
  16673. expect(userType.getText()).toContain('guest');
  16674. expect(valid.getText()).toContain('true');
  16675. });
  16676. it('should be invalid if empty', function() {
  16677. var userType = element(by.binding('userType'));
  16678. var valid = element(by.binding('myForm.input.$valid'));
  16679. var userInput = element(by.model('userType'));
  16680. userInput.clear();
  16681. userInput.sendKeys('');
  16682. expect(userType.getText()).toEqual('userType =');
  16683. expect(valid.getText()).toContain('false');
  16684. });
  16685. </file>
  16686. </example>
  16687. *
  16688. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16689. * related scope, under this name.
  16690. */
  16691. var formDirectiveFactory = function(isNgForm) {
  16692. return ['$timeout', function($timeout) {
  16693. var formDirective = {
  16694. name: 'form',
  16695. restrict: isNgForm ? 'EAC' : 'E',
  16696. controller: FormController,
  16697. compile: function ngFormCompile(formElement) {
  16698. // Setup initial state of the control
  16699. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16700. return {
  16701. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16702. // if `action` attr is not present on the form, prevent the default action (submission)
  16703. if (!('action' in attr)) {
  16704. // we can't use jq events because if a form is destroyed during submission the default
  16705. // action is not prevented. see #1238
  16706. //
  16707. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16708. // page reload if the form was destroyed by submission of the form via a click handler
  16709. // on a button in the form. Looks like an IE9 specific bug.
  16710. var handleFormSubmission = function(event) {
  16711. scope.$apply(function() {
  16712. controller.$commitViewValue();
  16713. controller.$setSubmitted();
  16714. });
  16715. event.preventDefault();
  16716. };
  16717. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16718. // unregister the preventDefault listener so that we don't not leak memory but in a
  16719. // way that will achieve the prevention of the default action.
  16720. formElement.on('$destroy', function() {
  16721. $timeout(function() {
  16722. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16723. }, 0, false);
  16724. });
  16725. }
  16726. var parentFormCtrl = controller.$$parentForm,
  16727. alias = controller.$name;
  16728. if (alias) {
  16729. setter(scope, alias, controller, alias);
  16730. attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
  16731. if (alias === newValue) return;
  16732. setter(scope, alias, undefined, alias);
  16733. alias = newValue;
  16734. setter(scope, alias, controller, alias);
  16735. parentFormCtrl.$$renameControl(controller, alias);
  16736. });
  16737. }
  16738. formElement.on('$destroy', function() {
  16739. parentFormCtrl.$removeControl(controller);
  16740. if (alias) {
  16741. setter(scope, alias, undefined, alias);
  16742. }
  16743. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16744. });
  16745. }
  16746. };
  16747. }
  16748. };
  16749. return formDirective;
  16750. }];
  16751. };
  16752. var formDirective = formDirectiveFactory();
  16753. var ngFormDirective = formDirectiveFactory(true);
  16754. /* global VALID_CLASS: true,
  16755. INVALID_CLASS: true,
  16756. PRISTINE_CLASS: true,
  16757. DIRTY_CLASS: true,
  16758. UNTOUCHED_CLASS: true,
  16759. TOUCHED_CLASS: true,
  16760. */
  16761. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16762. 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)/;
  16763. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16764. 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;
  16765. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16766. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16767. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16768. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16769. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16770. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16771. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  16772. var $ngModelMinErr = new minErr('ngModel');
  16773. var inputType = {
  16774. /**
  16775. * @ngdoc input
  16776. * @name input[text]
  16777. *
  16778. * @description
  16779. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  16780. *
  16781. *
  16782. * @param {string} ngModel Assignable angular expression to data-bind to.
  16783. * @param {string=} name Property name of the form under which the control is published.
  16784. * @param {string=} required Adds `required` validation error key if the value is not entered.
  16785. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16786. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16787. * `required` when you want to data-bind to the `required` attribute.
  16788. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  16789. * minlength.
  16790. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  16791. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  16792. * any length.
  16793. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  16794. * that contains the regular expression body that will be converted to a regular expression
  16795. * as in the ngPattern directive.
  16796. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  16797. * a RegExp found by evaluating the Angular expression given in the attribute value.
  16798. * If the expression evaluates to a RegExp object then this is used directly.
  16799. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  16800. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  16801. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16802. * interaction with the input element.
  16803. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  16804. * This parameter is ignored for input[type=password] controls, which will never trim the
  16805. * input.
  16806. *
  16807. * @example
  16808. <example name="text-input-directive" module="textInputExample">
  16809. <file name="index.html">
  16810. <script>
  16811. angular.module('textInputExample', [])
  16812. .controller('ExampleController', ['$scope', function($scope) {
  16813. $scope.text = 'guest';
  16814. $scope.word = /^\s*\w*\s*$/;
  16815. }]);
  16816. </script>
  16817. <form name="myForm" ng-controller="ExampleController">
  16818. Single word: <input type="text" name="input" ng-model="text"
  16819. ng-pattern="word" required ng-trim="false">
  16820. <span class="error" ng-show="myForm.input.$error.required">
  16821. Required!</span>
  16822. <span class="error" ng-show="myForm.input.$error.pattern">
  16823. Single word only!</span>
  16824. <tt>text = {{text}}</tt><br/>
  16825. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16826. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16827. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16828. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16829. </form>
  16830. </file>
  16831. <file name="protractor.js" type="protractor">
  16832. var text = element(by.binding('text'));
  16833. var valid = element(by.binding('myForm.input.$valid'));
  16834. var input = element(by.model('text'));
  16835. it('should initialize to model', function() {
  16836. expect(text.getText()).toContain('guest');
  16837. expect(valid.getText()).toContain('true');
  16838. });
  16839. it('should be invalid if empty', function() {
  16840. input.clear();
  16841. input.sendKeys('');
  16842. expect(text.getText()).toEqual('text =');
  16843. expect(valid.getText()).toContain('false');
  16844. });
  16845. it('should be invalid if multi word', function() {
  16846. input.clear();
  16847. input.sendKeys('hello world');
  16848. expect(valid.getText()).toContain('false');
  16849. });
  16850. </file>
  16851. </example>
  16852. */
  16853. 'text': textInputType,
  16854. /**
  16855. * @ngdoc input
  16856. * @name input[date]
  16857. *
  16858. * @description
  16859. * Input with date validation and transformation. In browsers that do not yet support
  16860. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  16861. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  16862. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  16863. * expected input format via a placeholder or label.
  16864. *
  16865. * The model must always be a Date object, otherwise Angular will throw an error.
  16866. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16867. *
  16868. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16869. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16870. *
  16871. * @param {string} ngModel Assignable angular expression to data-bind to.
  16872. * @param {string=} name Property name of the form under which the control is published.
  16873. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16874. * valid ISO date string (yyyy-MM-dd).
  16875. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16876. * a valid ISO date string (yyyy-MM-dd).
  16877. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16878. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16879. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16880. * `required` when you want to data-bind to the `required` attribute.
  16881. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16882. * interaction with the input element.
  16883. *
  16884. * @example
  16885. <example name="date-input-directive" module="dateInputExample">
  16886. <file name="index.html">
  16887. <script>
  16888. angular.module('dateInputExample', [])
  16889. .controller('DateController', ['$scope', function($scope) {
  16890. $scope.value = new Date(2013, 9, 22);
  16891. }]);
  16892. </script>
  16893. <form name="myForm" ng-controller="DateController as dateCtrl">
  16894. Pick a date in 2013:
  16895. <input type="date" id="exampleInput" name="input" ng-model="value"
  16896. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  16897. <span class="error" ng-show="myForm.input.$error.required">
  16898. Required!</span>
  16899. <span class="error" ng-show="myForm.input.$error.date">
  16900. Not a valid date!</span>
  16901. <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
  16902. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16903. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16904. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16905. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16906. </form>
  16907. </file>
  16908. <file name="protractor.js" type="protractor">
  16909. var value = element(by.binding('value | date: "yyyy-MM-dd"'));
  16910. var valid = element(by.binding('myForm.input.$valid'));
  16911. var input = element(by.model('value'));
  16912. // currently protractor/webdriver does not support
  16913. // sending keys to all known HTML5 input controls
  16914. // for various browsers (see https://github.com/angular/protractor/issues/562).
  16915. function setInput(val) {
  16916. // set the value of the element and force validation.
  16917. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16918. "ipt.value = '" + val + "';" +
  16919. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16920. browser.executeScript(scr);
  16921. }
  16922. it('should initialize to model', function() {
  16923. expect(value.getText()).toContain('2013-10-22');
  16924. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16925. });
  16926. it('should be invalid if empty', function() {
  16927. setInput('');
  16928. expect(value.getText()).toEqual('value =');
  16929. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16930. });
  16931. it('should be invalid if over max', function() {
  16932. setInput('2015-01-01');
  16933. expect(value.getText()).toContain('');
  16934. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16935. });
  16936. </file>
  16937. </example>
  16938. */
  16939. 'date': createDateInputType('date', DATE_REGEXP,
  16940. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  16941. 'yyyy-MM-dd'),
  16942. /**
  16943. * @ngdoc input
  16944. * @name input[datetime-local]
  16945. *
  16946. * @description
  16947. * Input with datetime validation and transformation. In browsers that do not yet support
  16948. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16949. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  16950. *
  16951. * The model must always be a Date object, otherwise Angular will throw an error.
  16952. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16953. *
  16954. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16955. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16956. *
  16957. * @param {string} ngModel Assignable angular expression to data-bind to.
  16958. * @param {string=} name Property name of the form under which the control is published.
  16959. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16960. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16961. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16962. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16963. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16964. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16965. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16966. * `required` when you want to data-bind to the `required` attribute.
  16967. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16968. * interaction with the input element.
  16969. *
  16970. * @example
  16971. <example name="datetimelocal-input-directive" module="dateExample">
  16972. <file name="index.html">
  16973. <script>
  16974. angular.module('dateExample', [])
  16975. .controller('DateController', ['$scope', function($scope) {
  16976. $scope.value = new Date(2010, 11, 28, 14, 57);
  16977. }]);
  16978. </script>
  16979. <form name="myForm" ng-controller="DateController as dateCtrl">
  16980. Pick a date between in 2013:
  16981. <input type="datetime-local" id="exampleInput" name="input" ng-model="value"
  16982. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  16983. <span class="error" ng-show="myForm.input.$error.required">
  16984. Required!</span>
  16985. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  16986. Not a valid date!</span>
  16987. <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  16988. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16989. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16990. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16991. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16992. </form>
  16993. </file>
  16994. <file name="protractor.js" type="protractor">
  16995. var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
  16996. var valid = element(by.binding('myForm.input.$valid'));
  16997. var input = element(by.model('value'));
  16998. // currently protractor/webdriver does not support
  16999. // sending keys to all known HTML5 input controls
  17000. // for various browsers (https://github.com/angular/protractor/issues/562).
  17001. function setInput(val) {
  17002. // set the value of the element and force validation.
  17003. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17004. "ipt.value = '" + val + "';" +
  17005. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17006. browser.executeScript(scr);
  17007. }
  17008. it('should initialize to model', function() {
  17009. expect(value.getText()).toContain('2010-12-28T14:57:00');
  17010. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17011. });
  17012. it('should be invalid if empty', function() {
  17013. setInput('');
  17014. expect(value.getText()).toEqual('value =');
  17015. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17016. });
  17017. it('should be invalid if over max', function() {
  17018. setInput('2015-01-01T23:59:00');
  17019. expect(value.getText()).toContain('');
  17020. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17021. });
  17022. </file>
  17023. </example>
  17024. */
  17025. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  17026. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  17027. 'yyyy-MM-ddTHH:mm:ss.sss'),
  17028. /**
  17029. * @ngdoc input
  17030. * @name input[time]
  17031. *
  17032. * @description
  17033. * Input with time validation and transformation. In browsers that do not yet support
  17034. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17035. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  17036. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  17037. *
  17038. * The model must always be a Date object, otherwise Angular will throw an error.
  17039. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17040. *
  17041. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17042. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17043. *
  17044. * @param {string} ngModel Assignable angular expression to data-bind to.
  17045. * @param {string=} name Property name of the form under which the control is published.
  17046. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17047. * valid ISO time format (HH:mm:ss).
  17048. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  17049. * valid ISO time format (HH:mm:ss).
  17050. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17051. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17052. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17053. * `required` when you want to data-bind to the `required` attribute.
  17054. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17055. * interaction with the input element.
  17056. *
  17057. * @example
  17058. <example name="time-input-directive" module="timeExample">
  17059. <file name="index.html">
  17060. <script>
  17061. angular.module('timeExample', [])
  17062. .controller('DateController', ['$scope', function($scope) {
  17063. $scope.value = new Date(1970, 0, 1, 14, 57, 0);
  17064. }]);
  17065. </script>
  17066. <form name="myForm" ng-controller="DateController as dateCtrl">
  17067. Pick a between 8am and 5pm:
  17068. <input type="time" id="exampleInput" name="input" ng-model="value"
  17069. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  17070. <span class="error" ng-show="myForm.input.$error.required">
  17071. Required!</span>
  17072. <span class="error" ng-show="myForm.input.$error.time">
  17073. Not a valid date!</span>
  17074. <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
  17075. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17076. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17077. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17078. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17079. </form>
  17080. </file>
  17081. <file name="protractor.js" type="protractor">
  17082. var value = element(by.binding('value | date: "HH:mm:ss"'));
  17083. var valid = element(by.binding('myForm.input.$valid'));
  17084. var input = element(by.model('value'));
  17085. // currently protractor/webdriver does not support
  17086. // sending keys to all known HTML5 input controls
  17087. // for various browsers (https://github.com/angular/protractor/issues/562).
  17088. function setInput(val) {
  17089. // set the value of the element and force validation.
  17090. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17091. "ipt.value = '" + val + "';" +
  17092. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17093. browser.executeScript(scr);
  17094. }
  17095. it('should initialize to model', function() {
  17096. expect(value.getText()).toContain('14:57:00');
  17097. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17098. });
  17099. it('should be invalid if empty', function() {
  17100. setInput('');
  17101. expect(value.getText()).toEqual('value =');
  17102. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17103. });
  17104. it('should be invalid if over max', function() {
  17105. setInput('23:59:00');
  17106. expect(value.getText()).toContain('');
  17107. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17108. });
  17109. </file>
  17110. </example>
  17111. */
  17112. 'time': createDateInputType('time', TIME_REGEXP,
  17113. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17114. 'HH:mm:ss.sss'),
  17115. /**
  17116. * @ngdoc input
  17117. * @name input[week]
  17118. *
  17119. * @description
  17120. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17121. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17122. * week format (yyyy-W##), for example: `2013-W02`.
  17123. *
  17124. * The model must always be a Date object, otherwise Angular will throw an error.
  17125. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17126. *
  17127. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17128. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17129. *
  17130. * @param {string} ngModel Assignable angular expression to data-bind to.
  17131. * @param {string=} name Property name of the form under which the control is published.
  17132. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17133. * valid ISO week format (yyyy-W##).
  17134. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17135. * a valid ISO week format (yyyy-W##).
  17136. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17137. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17138. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17139. * `required` when you want to data-bind to the `required` attribute.
  17140. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17141. * interaction with the input element.
  17142. *
  17143. * @example
  17144. <example name="week-input-directive" module="weekExample">
  17145. <file name="index.html">
  17146. <script>
  17147. angular.module('weekExample', [])
  17148. .controller('DateController', ['$scope', function($scope) {
  17149. $scope.value = new Date(2013, 0, 3);
  17150. }]);
  17151. </script>
  17152. <form name="myForm" ng-controller="DateController as dateCtrl">
  17153. Pick a date between in 2013:
  17154. <input id="exampleInput" type="week" name="input" ng-model="value"
  17155. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17156. <span class="error" ng-show="myForm.input.$error.required">
  17157. Required!</span>
  17158. <span class="error" ng-show="myForm.input.$error.week">
  17159. Not a valid date!</span>
  17160. <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
  17161. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17162. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17163. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17164. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17165. </form>
  17166. </file>
  17167. <file name="protractor.js" type="protractor">
  17168. var value = element(by.binding('value | date: "yyyy-Www"'));
  17169. var valid = element(by.binding('myForm.input.$valid'));
  17170. var input = element(by.model('value'));
  17171. // currently protractor/webdriver does not support
  17172. // sending keys to all known HTML5 input controls
  17173. // for various browsers (https://github.com/angular/protractor/issues/562).
  17174. function setInput(val) {
  17175. // set the value of the element and force validation.
  17176. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17177. "ipt.value = '" + val + "';" +
  17178. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17179. browser.executeScript(scr);
  17180. }
  17181. it('should initialize to model', function() {
  17182. expect(value.getText()).toContain('2013-W01');
  17183. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17184. });
  17185. it('should be invalid if empty', function() {
  17186. setInput('');
  17187. expect(value.getText()).toEqual('value =');
  17188. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17189. });
  17190. it('should be invalid if over max', function() {
  17191. setInput('2015-W01');
  17192. expect(value.getText()).toContain('');
  17193. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17194. });
  17195. </file>
  17196. </example>
  17197. */
  17198. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17199. /**
  17200. * @ngdoc input
  17201. * @name input[month]
  17202. *
  17203. * @description
  17204. * Input with month validation and transformation. In browsers that do not yet support
  17205. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17206. * month format (yyyy-MM), for example: `2009-01`.
  17207. *
  17208. * The model must always be a Date object, otherwise Angular will throw an error.
  17209. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17210. * If the model is not set to the first of the month, the next view to model update will set it
  17211. * to the first of the month.
  17212. *
  17213. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17214. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17215. *
  17216. * @param {string} ngModel Assignable angular expression to data-bind to.
  17217. * @param {string=} name Property name of the form under which the control is published.
  17218. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17219. * a valid ISO month format (yyyy-MM).
  17220. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17221. * be a valid ISO month format (yyyy-MM).
  17222. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17223. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17224. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17225. * `required` when you want to data-bind to the `required` attribute.
  17226. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17227. * interaction with the input element.
  17228. *
  17229. * @example
  17230. <example name="month-input-directive" module="monthExample">
  17231. <file name="index.html">
  17232. <script>
  17233. angular.module('monthExample', [])
  17234. .controller('DateController', ['$scope', function($scope) {
  17235. $scope.value = new Date(2013, 9, 1);
  17236. }]);
  17237. </script>
  17238. <form name="myForm" ng-controller="DateController as dateCtrl">
  17239. Pick a month int 2013:
  17240. <input id="exampleInput" type="month" name="input" ng-model="value"
  17241. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17242. <span class="error" ng-show="myForm.input.$error.required">
  17243. Required!</span>
  17244. <span class="error" ng-show="myForm.input.$error.month">
  17245. Not a valid month!</span>
  17246. <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
  17247. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17248. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17249. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17250. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17251. </form>
  17252. </file>
  17253. <file name="protractor.js" type="protractor">
  17254. var value = element(by.binding('value | date: "yyyy-MM"'));
  17255. var valid = element(by.binding('myForm.input.$valid'));
  17256. var input = element(by.model('value'));
  17257. // currently protractor/webdriver does not support
  17258. // sending keys to all known HTML5 input controls
  17259. // for various browsers (https://github.com/angular/protractor/issues/562).
  17260. function setInput(val) {
  17261. // set the value of the element and force validation.
  17262. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17263. "ipt.value = '" + val + "';" +
  17264. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17265. browser.executeScript(scr);
  17266. }
  17267. it('should initialize to model', function() {
  17268. expect(value.getText()).toContain('2013-10');
  17269. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17270. });
  17271. it('should be invalid if empty', function() {
  17272. setInput('');
  17273. expect(value.getText()).toEqual('value =');
  17274. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17275. });
  17276. it('should be invalid if over max', function() {
  17277. setInput('2015-01');
  17278. expect(value.getText()).toContain('');
  17279. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17280. });
  17281. </file>
  17282. </example>
  17283. */
  17284. 'month': createDateInputType('month', MONTH_REGEXP,
  17285. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17286. 'yyyy-MM'),
  17287. /**
  17288. * @ngdoc input
  17289. * @name input[number]
  17290. *
  17291. * @description
  17292. * Text input with number validation and transformation. Sets the `number` validation
  17293. * error if not a valid number.
  17294. *
  17295. * The model must always be a number, otherwise Angular will throw an error.
  17296. *
  17297. * @param {string} ngModel Assignable angular expression to data-bind to.
  17298. * @param {string=} name Property name of the form under which the control is published.
  17299. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17300. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17301. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17302. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17303. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17304. * `required` when you want to data-bind to the `required` attribute.
  17305. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17306. * minlength.
  17307. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17308. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17309. * any length.
  17310. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17311. * that contains the regular expression body that will be converted to a regular expression
  17312. * as in the ngPattern directive.
  17313. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17314. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17315. * If the expression evaluates to a RegExp object then this is used directly.
  17316. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17317. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17318. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17319. * interaction with the input element.
  17320. *
  17321. * @example
  17322. <example name="number-input-directive" module="numberExample">
  17323. <file name="index.html">
  17324. <script>
  17325. angular.module('numberExample', [])
  17326. .controller('ExampleController', ['$scope', function($scope) {
  17327. $scope.value = 12;
  17328. }]);
  17329. </script>
  17330. <form name="myForm" ng-controller="ExampleController">
  17331. Number: <input type="number" name="input" ng-model="value"
  17332. min="0" max="99" required>
  17333. <span class="error" ng-show="myForm.input.$error.required">
  17334. Required!</span>
  17335. <span class="error" ng-show="myForm.input.$error.number">
  17336. Not valid number!</span>
  17337. <tt>value = {{value}}</tt><br/>
  17338. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17339. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17340. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17341. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17342. </form>
  17343. </file>
  17344. <file name="protractor.js" type="protractor">
  17345. var value = element(by.binding('value'));
  17346. var valid = element(by.binding('myForm.input.$valid'));
  17347. var input = element(by.model('value'));
  17348. it('should initialize to model', function() {
  17349. expect(value.getText()).toContain('12');
  17350. expect(valid.getText()).toContain('true');
  17351. });
  17352. it('should be invalid if empty', function() {
  17353. input.clear();
  17354. input.sendKeys('');
  17355. expect(value.getText()).toEqual('value =');
  17356. expect(valid.getText()).toContain('false');
  17357. });
  17358. it('should be invalid if over max', function() {
  17359. input.clear();
  17360. input.sendKeys('123');
  17361. expect(value.getText()).toEqual('value =');
  17362. expect(valid.getText()).toContain('false');
  17363. });
  17364. </file>
  17365. </example>
  17366. */
  17367. 'number': numberInputType,
  17368. /**
  17369. * @ngdoc input
  17370. * @name input[url]
  17371. *
  17372. * @description
  17373. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17374. * valid URL.
  17375. *
  17376. * <div class="alert alert-warning">
  17377. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17378. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17379. * the built-in validators (see the {@link guide/forms Forms guide})
  17380. * </div>
  17381. *
  17382. * @param {string} ngModel Assignable angular expression to data-bind to.
  17383. * @param {string=} name Property name of the form under which the control is published.
  17384. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17385. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17386. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17387. * `required` when you want to data-bind to the `required` attribute.
  17388. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17389. * minlength.
  17390. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17391. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17392. * any length.
  17393. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17394. * that contains the regular expression body that will be converted to a regular expression
  17395. * as in the ngPattern directive.
  17396. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17397. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17398. * If the expression evaluates to a RegExp object then this is used directly.
  17399. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17400. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17401. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17402. * interaction with the input element.
  17403. *
  17404. * @example
  17405. <example name="url-input-directive" module="urlExample">
  17406. <file name="index.html">
  17407. <script>
  17408. angular.module('urlExample', [])
  17409. .controller('ExampleController', ['$scope', function($scope) {
  17410. $scope.text = 'http://google.com';
  17411. }]);
  17412. </script>
  17413. <form name="myForm" ng-controller="ExampleController">
  17414. URL: <input type="url" name="input" ng-model="text" required>
  17415. <span class="error" ng-show="myForm.input.$error.required">
  17416. Required!</span>
  17417. <span class="error" ng-show="myForm.input.$error.url">
  17418. Not valid url!</span>
  17419. <tt>text = {{text}}</tt><br/>
  17420. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17421. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17422. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17423. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17424. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17425. </form>
  17426. </file>
  17427. <file name="protractor.js" type="protractor">
  17428. var text = element(by.binding('text'));
  17429. var valid = element(by.binding('myForm.input.$valid'));
  17430. var input = element(by.model('text'));
  17431. it('should initialize to model', function() {
  17432. expect(text.getText()).toContain('http://google.com');
  17433. expect(valid.getText()).toContain('true');
  17434. });
  17435. it('should be invalid if empty', function() {
  17436. input.clear();
  17437. input.sendKeys('');
  17438. expect(text.getText()).toEqual('text =');
  17439. expect(valid.getText()).toContain('false');
  17440. });
  17441. it('should be invalid if not url', function() {
  17442. input.clear();
  17443. input.sendKeys('box');
  17444. expect(valid.getText()).toContain('false');
  17445. });
  17446. </file>
  17447. </example>
  17448. */
  17449. 'url': urlInputType,
  17450. /**
  17451. * @ngdoc input
  17452. * @name input[email]
  17453. *
  17454. * @description
  17455. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17456. * address.
  17457. *
  17458. * <div class="alert alert-warning">
  17459. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17460. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17461. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17462. * </div>
  17463. *
  17464. * @param {string} ngModel Assignable angular expression to data-bind to.
  17465. * @param {string=} name Property name of the form under which the control is published.
  17466. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17467. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17468. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17469. * `required` when you want to data-bind to the `required` attribute.
  17470. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17471. * minlength.
  17472. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17473. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  17474. * any length.
  17475. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  17476. * that contains the regular expression body that will be converted to a regular expression
  17477. * as in the ngPattern directive.
  17478. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  17479. * a RegExp found by evaluating the Angular expression given in the attribute value.
  17480. * If the expression evaluates to a RegExp object then this is used directly.
  17481. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
  17482. * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  17483. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17484. * interaction with the input element.
  17485. *
  17486. * @example
  17487. <example name="email-input-directive" module="emailExample">
  17488. <file name="index.html">
  17489. <script>
  17490. angular.module('emailExample', [])
  17491. .controller('ExampleController', ['$scope', function($scope) {
  17492. $scope.text = 'me@example.com';
  17493. }]);
  17494. </script>
  17495. <form name="myForm" ng-controller="ExampleController">
  17496. Email: <input type="email" name="input" ng-model="text" required>
  17497. <span class="error" ng-show="myForm.input.$error.required">
  17498. Required!</span>
  17499. <span class="error" ng-show="myForm.input.$error.email">
  17500. Not valid email!</span>
  17501. <tt>text = {{text}}</tt><br/>
  17502. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17503. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17504. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17505. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17506. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17507. </form>
  17508. </file>
  17509. <file name="protractor.js" type="protractor">
  17510. var text = element(by.binding('text'));
  17511. var valid = element(by.binding('myForm.input.$valid'));
  17512. var input = element(by.model('text'));
  17513. it('should initialize to model', function() {
  17514. expect(text.getText()).toContain('me@example.com');
  17515. expect(valid.getText()).toContain('true');
  17516. });
  17517. it('should be invalid if empty', function() {
  17518. input.clear();
  17519. input.sendKeys('');
  17520. expect(text.getText()).toEqual('text =');
  17521. expect(valid.getText()).toContain('false');
  17522. });
  17523. it('should be invalid if not email', function() {
  17524. input.clear();
  17525. input.sendKeys('xxx');
  17526. expect(valid.getText()).toContain('false');
  17527. });
  17528. </file>
  17529. </example>
  17530. */
  17531. 'email': emailInputType,
  17532. /**
  17533. * @ngdoc input
  17534. * @name input[radio]
  17535. *
  17536. * @description
  17537. * HTML radio button.
  17538. *
  17539. * @param {string} ngModel Assignable angular expression to data-bind to.
  17540. * @param {string} value The value to which the expression should be set when selected.
  17541. * @param {string=} name Property name of the form under which the control is published.
  17542. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17543. * interaction with the input element.
  17544. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17545. * be set when selected.
  17546. *
  17547. * @example
  17548. <example name="radio-input-directive" module="radioExample">
  17549. <file name="index.html">
  17550. <script>
  17551. angular.module('radioExample', [])
  17552. .controller('ExampleController', ['$scope', function($scope) {
  17553. $scope.color = 'blue';
  17554. $scope.specialValue = {
  17555. "id": "12345",
  17556. "value": "green"
  17557. };
  17558. }]);
  17559. </script>
  17560. <form name="myForm" ng-controller="ExampleController">
  17561. <input type="radio" ng-model="color" value="red"> Red <br/>
  17562. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  17563. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  17564. <tt>color = {{color | json}}</tt><br/>
  17565. </form>
  17566. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17567. </file>
  17568. <file name="protractor.js" type="protractor">
  17569. it('should change state', function() {
  17570. var color = element(by.binding('color'));
  17571. expect(color.getText()).toContain('blue');
  17572. element.all(by.model('color')).get(0).click();
  17573. expect(color.getText()).toContain('red');
  17574. });
  17575. </file>
  17576. </example>
  17577. */
  17578. 'radio': radioInputType,
  17579. /**
  17580. * @ngdoc input
  17581. * @name input[checkbox]
  17582. *
  17583. * @description
  17584. * HTML checkbox.
  17585. *
  17586. * @param {string} ngModel Assignable angular expression to data-bind to.
  17587. * @param {string=} name Property name of the form under which the control is published.
  17588. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17589. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17590. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17591. * interaction with the input element.
  17592. *
  17593. * @example
  17594. <example name="checkbox-input-directive" module="checkboxExample">
  17595. <file name="index.html">
  17596. <script>
  17597. angular.module('checkboxExample', [])
  17598. .controller('ExampleController', ['$scope', function($scope) {
  17599. $scope.value1 = true;
  17600. $scope.value2 = 'YES'
  17601. }]);
  17602. </script>
  17603. <form name="myForm" ng-controller="ExampleController">
  17604. Value1: <input type="checkbox" ng-model="value1"> <br/>
  17605. Value2: <input type="checkbox" ng-model="value2"
  17606. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17607. <tt>value1 = {{value1}}</tt><br/>
  17608. <tt>value2 = {{value2}}</tt><br/>
  17609. </form>
  17610. </file>
  17611. <file name="protractor.js" type="protractor">
  17612. it('should change state', function() {
  17613. var value1 = element(by.binding('value1'));
  17614. var value2 = element(by.binding('value2'));
  17615. expect(value1.getText()).toContain('true');
  17616. expect(value2.getText()).toContain('YES');
  17617. element(by.model('value1')).click();
  17618. element(by.model('value2')).click();
  17619. expect(value1.getText()).toContain('false');
  17620. expect(value2.getText()).toContain('NO');
  17621. });
  17622. </file>
  17623. </example>
  17624. */
  17625. 'checkbox': checkboxInputType,
  17626. 'hidden': noop,
  17627. 'button': noop,
  17628. 'submit': noop,
  17629. 'reset': noop,
  17630. 'file': noop
  17631. };
  17632. function stringBasedInputType(ctrl) {
  17633. ctrl.$formatters.push(function(value) {
  17634. return ctrl.$isEmpty(value) ? value : value.toString();
  17635. });
  17636. }
  17637. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17638. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17639. stringBasedInputType(ctrl);
  17640. }
  17641. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17642. var placeholder = element[0].placeholder, noevent = {};
  17643. var type = lowercase(element[0].type);
  17644. // In composition mode, users are still inputing intermediate text buffer,
  17645. // hold the listener until composition is done.
  17646. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17647. if (!$sniffer.android) {
  17648. var composing = false;
  17649. element.on('compositionstart', function(data) {
  17650. composing = true;
  17651. });
  17652. element.on('compositionend', function() {
  17653. composing = false;
  17654. listener();
  17655. });
  17656. }
  17657. var listener = function(ev) {
  17658. if (composing) return;
  17659. var value = element.val(),
  17660. event = ev && ev.type;
  17661. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  17662. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  17663. // IE also sends input events for other non-input-related things, (such as focusing on a
  17664. // form control), so this change is not entirely enough to solve this.
  17665. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  17666. placeholder = element[0].placeholder;
  17667. return;
  17668. }
  17669. // By default we will trim the value
  17670. // If the attribute ng-trim exists we will avoid trimming
  17671. // If input type is 'password', the value is never trimmed
  17672. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17673. value = trim(value);
  17674. }
  17675. // If a control is suffering from bad input (due to native validators), browsers discard its
  17676. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17677. // control's value is the same empty value twice in a row.
  17678. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17679. ctrl.$setViewValue(value, event);
  17680. }
  17681. };
  17682. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17683. // input event on backspace, delete or cut
  17684. if ($sniffer.hasEvent('input')) {
  17685. element.on('input', listener);
  17686. } else {
  17687. var timeout;
  17688. var deferListener = function(ev) {
  17689. if (!timeout) {
  17690. timeout = $browser.defer(function() {
  17691. listener(ev);
  17692. timeout = null;
  17693. });
  17694. }
  17695. };
  17696. element.on('keydown', function(event) {
  17697. var key = event.keyCode;
  17698. // ignore
  17699. // command modifiers arrows
  17700. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17701. deferListener(event);
  17702. });
  17703. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17704. if ($sniffer.hasEvent('paste')) {
  17705. element.on('paste cut', deferListener);
  17706. }
  17707. }
  17708. // if user paste into input using mouse on older browser
  17709. // or form autocomplete on newer browser, we need "change" event to catch it
  17710. element.on('change', listener);
  17711. ctrl.$render = function() {
  17712. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  17713. };
  17714. }
  17715. function weekParser(isoWeek, existingDate) {
  17716. if (isDate(isoWeek)) {
  17717. return isoWeek;
  17718. }
  17719. if (isString(isoWeek)) {
  17720. WEEK_REGEXP.lastIndex = 0;
  17721. var parts = WEEK_REGEXP.exec(isoWeek);
  17722. if (parts) {
  17723. var year = +parts[1],
  17724. week = +parts[2],
  17725. hours = 0,
  17726. minutes = 0,
  17727. seconds = 0,
  17728. milliseconds = 0,
  17729. firstThurs = getFirstThursdayOfYear(year),
  17730. addDays = (week - 1) * 7;
  17731. if (existingDate) {
  17732. hours = existingDate.getHours();
  17733. minutes = existingDate.getMinutes();
  17734. seconds = existingDate.getSeconds();
  17735. milliseconds = existingDate.getMilliseconds();
  17736. }
  17737. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17738. }
  17739. }
  17740. return NaN;
  17741. }
  17742. function createDateParser(regexp, mapping) {
  17743. return function(iso, date) {
  17744. var parts, map;
  17745. if (isDate(iso)) {
  17746. return iso;
  17747. }
  17748. if (isString(iso)) {
  17749. // When a date is JSON'ified to wraps itself inside of an extra
  17750. // set of double quotes. This makes the date parsing code unable
  17751. // to match the date string and parse it as a date.
  17752. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  17753. iso = iso.substring(1, iso.length - 1);
  17754. }
  17755. if (ISO_DATE_REGEXP.test(iso)) {
  17756. return new Date(iso);
  17757. }
  17758. regexp.lastIndex = 0;
  17759. parts = regexp.exec(iso);
  17760. if (parts) {
  17761. parts.shift();
  17762. if (date) {
  17763. map = {
  17764. yyyy: date.getFullYear(),
  17765. MM: date.getMonth() + 1,
  17766. dd: date.getDate(),
  17767. HH: date.getHours(),
  17768. mm: date.getMinutes(),
  17769. ss: date.getSeconds(),
  17770. sss: date.getMilliseconds() / 1000
  17771. };
  17772. } else {
  17773. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  17774. }
  17775. forEach(parts, function(part, index) {
  17776. if (index < mapping.length) {
  17777. map[mapping[index]] = +part;
  17778. }
  17779. });
  17780. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  17781. }
  17782. }
  17783. return NaN;
  17784. };
  17785. }
  17786. function createDateInputType(type, regexp, parseDate, format) {
  17787. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  17788. badInputChecker(scope, element, attr, ctrl);
  17789. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17790. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  17791. var previousDate;
  17792. ctrl.$$parserName = type;
  17793. ctrl.$parsers.push(function(value) {
  17794. if (ctrl.$isEmpty(value)) return null;
  17795. if (regexp.test(value)) {
  17796. // Note: We cannot read ctrl.$modelValue, as there might be a different
  17797. // parser/formatter in the processing chain so that the model
  17798. // contains some different data format!
  17799. var parsedDate = parseDate(value, previousDate);
  17800. if (timezone === 'UTC') {
  17801. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  17802. }
  17803. return parsedDate;
  17804. }
  17805. return undefined;
  17806. });
  17807. ctrl.$formatters.push(function(value) {
  17808. if (value && !isDate(value)) {
  17809. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  17810. }
  17811. if (isValidDate(value)) {
  17812. previousDate = value;
  17813. if (previousDate && timezone === 'UTC') {
  17814. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  17815. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  17816. }
  17817. return $filter('date')(value, format, timezone);
  17818. } else {
  17819. previousDate = null;
  17820. return '';
  17821. }
  17822. });
  17823. if (isDefined(attr.min) || attr.ngMin) {
  17824. var minVal;
  17825. ctrl.$validators.min = function(value) {
  17826. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  17827. };
  17828. attr.$observe('min', function(val) {
  17829. minVal = parseObservedDateValue(val);
  17830. ctrl.$validate();
  17831. });
  17832. }
  17833. if (isDefined(attr.max) || attr.ngMax) {
  17834. var maxVal;
  17835. ctrl.$validators.max = function(value) {
  17836. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  17837. };
  17838. attr.$observe('max', function(val) {
  17839. maxVal = parseObservedDateValue(val);
  17840. ctrl.$validate();
  17841. });
  17842. }
  17843. function isValidDate(value) {
  17844. // Invalid Date: getTime() returns NaN
  17845. return value && !(value.getTime && value.getTime() !== value.getTime());
  17846. }
  17847. function parseObservedDateValue(val) {
  17848. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  17849. }
  17850. };
  17851. }
  17852. function badInputChecker(scope, element, attr, ctrl) {
  17853. var node = element[0];
  17854. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  17855. if (nativeValidation) {
  17856. ctrl.$parsers.push(function(value) {
  17857. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  17858. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  17859. // - also sets validity.badInput (should only be validity.typeMismatch).
  17860. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  17861. // - can ignore this case as we can still read out the erroneous email...
  17862. return validity.badInput && !validity.typeMismatch ? undefined : value;
  17863. });
  17864. }
  17865. }
  17866. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17867. badInputChecker(scope, element, attr, ctrl);
  17868. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17869. ctrl.$$parserName = 'number';
  17870. ctrl.$parsers.push(function(value) {
  17871. if (ctrl.$isEmpty(value)) return null;
  17872. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  17873. return undefined;
  17874. });
  17875. ctrl.$formatters.push(function(value) {
  17876. if (!ctrl.$isEmpty(value)) {
  17877. if (!isNumber(value)) {
  17878. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  17879. }
  17880. value = value.toString();
  17881. }
  17882. return value;
  17883. });
  17884. if (attr.min || attr.ngMin) {
  17885. var minVal;
  17886. ctrl.$validators.min = function(value) {
  17887. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  17888. };
  17889. attr.$observe('min', function(val) {
  17890. if (isDefined(val) && !isNumber(val)) {
  17891. val = parseFloat(val, 10);
  17892. }
  17893. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17894. // TODO(matsko): implement validateLater to reduce number of validations
  17895. ctrl.$validate();
  17896. });
  17897. }
  17898. if (attr.max || attr.ngMax) {
  17899. var maxVal;
  17900. ctrl.$validators.max = function(value) {
  17901. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  17902. };
  17903. attr.$observe('max', function(val) {
  17904. if (isDefined(val) && !isNumber(val)) {
  17905. val = parseFloat(val, 10);
  17906. }
  17907. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17908. // TODO(matsko): implement validateLater to reduce number of validations
  17909. ctrl.$validate();
  17910. });
  17911. }
  17912. }
  17913. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17914. // Note: no badInputChecker here by purpose as `url` is only a validation
  17915. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17916. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17917. stringBasedInputType(ctrl);
  17918. ctrl.$$parserName = 'url';
  17919. ctrl.$validators.url = function(modelValue, viewValue) {
  17920. var value = modelValue || viewValue;
  17921. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  17922. };
  17923. }
  17924. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17925. // Note: no badInputChecker here by purpose as `url` is only a validation
  17926. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17927. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17928. stringBasedInputType(ctrl);
  17929. ctrl.$$parserName = 'email';
  17930. ctrl.$validators.email = function(modelValue, viewValue) {
  17931. var value = modelValue || viewValue;
  17932. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  17933. };
  17934. }
  17935. function radioInputType(scope, element, attr, ctrl) {
  17936. // make the name unique, if not defined
  17937. if (isUndefined(attr.name)) {
  17938. element.attr('name', nextUid());
  17939. }
  17940. var listener = function(ev) {
  17941. if (element[0].checked) {
  17942. ctrl.$setViewValue(attr.value, ev && ev.type);
  17943. }
  17944. };
  17945. element.on('click', listener);
  17946. ctrl.$render = function() {
  17947. var value = attr.value;
  17948. element[0].checked = (value == ctrl.$viewValue);
  17949. };
  17950. attr.$observe('value', ctrl.$render);
  17951. }
  17952. function parseConstantExpr($parse, context, name, expression, fallback) {
  17953. var parseFn;
  17954. if (isDefined(expression)) {
  17955. parseFn = $parse(expression);
  17956. if (!parseFn.constant) {
  17957. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  17958. '`{1}`.', name, expression);
  17959. }
  17960. return parseFn(context);
  17961. }
  17962. return fallback;
  17963. }
  17964. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  17965. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  17966. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  17967. var listener = function(ev) {
  17968. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  17969. };
  17970. element.on('click', listener);
  17971. ctrl.$render = function() {
  17972. element[0].checked = ctrl.$viewValue;
  17973. };
  17974. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  17975. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  17976. // it to a boolean.
  17977. ctrl.$isEmpty = function(value) {
  17978. return value === false;
  17979. };
  17980. ctrl.$formatters.push(function(value) {
  17981. return equals(value, trueValue);
  17982. });
  17983. ctrl.$parsers.push(function(value) {
  17984. return value ? trueValue : falseValue;
  17985. });
  17986. }
  17987. /**
  17988. * @ngdoc directive
  17989. * @name textarea
  17990. * @restrict E
  17991. *
  17992. * @description
  17993. * HTML textarea element control with angular data-binding. The data-binding and validation
  17994. * properties of this element are exactly the same as those of the
  17995. * {@link ng.directive:input input element}.
  17996. *
  17997. * @param {string} ngModel Assignable angular expression to data-bind to.
  17998. * @param {string=} name Property name of the form under which the control is published.
  17999. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18000. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18001. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18002. * `required` when you want to data-bind to the `required` attribute.
  18003. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18004. * minlength.
  18005. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18006. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18007. * length.
  18008. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18009. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18010. * patterns defined as scope expressions.
  18011. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18012. * interaction with the input element.
  18013. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18014. */
  18015. /**
  18016. * @ngdoc directive
  18017. * @name input
  18018. * @restrict E
  18019. *
  18020. * @description
  18021. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  18022. * input state control, and validation.
  18023. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  18024. *
  18025. * <div class="alert alert-warning">
  18026. * **Note:** Not every feature offered is available for all input types.
  18027. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  18028. * </div>
  18029. *
  18030. * @param {string} ngModel Assignable angular expression to data-bind to.
  18031. * @param {string=} name Property name of the form under which the control is published.
  18032. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18033. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  18034. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18035. * minlength.
  18036. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18037. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  18038. * length.
  18039. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  18040. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  18041. * patterns defined as scope expressions.
  18042. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18043. * interaction with the input element.
  18044. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18045. * This parameter is ignored for input[type=password] controls, which will never trim the
  18046. * input.
  18047. *
  18048. * @example
  18049. <example name="input-directive" module="inputExample">
  18050. <file name="index.html">
  18051. <script>
  18052. angular.module('inputExample', [])
  18053. .controller('ExampleController', ['$scope', function($scope) {
  18054. $scope.user = {name: 'guest', last: 'visitor'};
  18055. }]);
  18056. </script>
  18057. <div ng-controller="ExampleController">
  18058. <form name="myForm">
  18059. User name: <input type="text" name="userName" ng-model="user.name" required>
  18060. <span class="error" ng-show="myForm.userName.$error.required">
  18061. Required!</span><br>
  18062. Last name: <input type="text" name="lastName" ng-model="user.last"
  18063. ng-minlength="3" ng-maxlength="10">
  18064. <span class="error" ng-show="myForm.lastName.$error.minlength">
  18065. Too short!</span>
  18066. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  18067. Too long!</span><br>
  18068. </form>
  18069. <hr>
  18070. <tt>user = {{user}}</tt><br/>
  18071. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  18072. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  18073. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  18074. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  18075. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  18076. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  18077. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  18078. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  18079. </div>
  18080. </file>
  18081. <file name="protractor.js" type="protractor">
  18082. var user = element(by.exactBinding('user'));
  18083. var userNameValid = element(by.binding('myForm.userName.$valid'));
  18084. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  18085. var lastNameError = element(by.binding('myForm.lastName.$error'));
  18086. var formValid = element(by.binding('myForm.$valid'));
  18087. var userNameInput = element(by.model('user.name'));
  18088. var userLastInput = element(by.model('user.last'));
  18089. it('should initialize to model', function() {
  18090. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  18091. expect(userNameValid.getText()).toContain('true');
  18092. expect(formValid.getText()).toContain('true');
  18093. });
  18094. it('should be invalid if empty when required', function() {
  18095. userNameInput.clear();
  18096. userNameInput.sendKeys('');
  18097. expect(user.getText()).toContain('{"last":"visitor"}');
  18098. expect(userNameValid.getText()).toContain('false');
  18099. expect(formValid.getText()).toContain('false');
  18100. });
  18101. it('should be valid if empty when min length is set', function() {
  18102. userLastInput.clear();
  18103. userLastInput.sendKeys('');
  18104. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18105. expect(lastNameValid.getText()).toContain('true');
  18106. expect(formValid.getText()).toContain('true');
  18107. });
  18108. it('should be invalid if less than required min length', function() {
  18109. userLastInput.clear();
  18110. userLastInput.sendKeys('xx');
  18111. expect(user.getText()).toContain('{"name":"guest"}');
  18112. expect(lastNameValid.getText()).toContain('false');
  18113. expect(lastNameError.getText()).toContain('minlength');
  18114. expect(formValid.getText()).toContain('false');
  18115. });
  18116. it('should be invalid if longer than max length', function() {
  18117. userLastInput.clear();
  18118. userLastInput.sendKeys('some ridiculously long name');
  18119. expect(user.getText()).toContain('{"name":"guest"}');
  18120. expect(lastNameValid.getText()).toContain('false');
  18121. expect(lastNameError.getText()).toContain('maxlength');
  18122. expect(formValid.getText()).toContain('false');
  18123. });
  18124. </file>
  18125. </example>
  18126. */
  18127. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18128. function($browser, $sniffer, $filter, $parse) {
  18129. return {
  18130. restrict: 'E',
  18131. require: ['?ngModel'],
  18132. link: {
  18133. pre: function(scope, element, attr, ctrls) {
  18134. if (ctrls[0]) {
  18135. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18136. $browser, $filter, $parse);
  18137. }
  18138. }
  18139. }
  18140. };
  18141. }];
  18142. var VALID_CLASS = 'ng-valid',
  18143. INVALID_CLASS = 'ng-invalid',
  18144. PRISTINE_CLASS = 'ng-pristine',
  18145. DIRTY_CLASS = 'ng-dirty',
  18146. UNTOUCHED_CLASS = 'ng-untouched',
  18147. TOUCHED_CLASS = 'ng-touched',
  18148. PENDING_CLASS = 'ng-pending';
  18149. /**
  18150. * @ngdoc type
  18151. * @name ngModel.NgModelController
  18152. *
  18153. * @property {string} $viewValue Actual string value in the view.
  18154. * @property {*} $modelValue The value in the model that the control is bound to.
  18155. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  18156. the control reads value from the DOM. The functions are called in array order, each passing
  18157. its return value through to the next. The last return value is forwarded to the
  18158. {@link ngModel.NgModelController#$validators `$validators`} collection.
  18159. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  18160. `$viewValue`}.
  18161. Returning `undefined` from a parser means a parse error occurred. In that case,
  18162. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  18163. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  18164. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  18165. *
  18166. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  18167. the model value changes. The functions are called in reverse array order, each passing the value through to the
  18168. next. The last return value is used as the actual DOM value.
  18169. Used to format / convert values for display in the control.
  18170. * ```js
  18171. * function formatter(value) {
  18172. * if (value) {
  18173. * return value.toUpperCase();
  18174. * }
  18175. * }
  18176. * ngModel.$formatters.push(formatter);
  18177. * ```
  18178. *
  18179. * @property {Object.<string, function>} $validators A collection of validators that are applied
  18180. * whenever the model value changes. The key value within the object refers to the name of the
  18181. * validator while the function refers to the validation operation. The validation operation is
  18182. * provided with the model value as an argument and must return a true or false value depending
  18183. * on the response of that validation.
  18184. *
  18185. * ```js
  18186. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  18187. * var value = modelValue || viewValue;
  18188. * return /[0-9]+/.test(value) &&
  18189. * /[a-z]+/.test(value) &&
  18190. * /[A-Z]+/.test(value) &&
  18191. * /\W+/.test(value);
  18192. * };
  18193. * ```
  18194. *
  18195. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  18196. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  18197. * is expected to return a promise when it is run during the model validation process. Once the promise
  18198. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  18199. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  18200. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  18201. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  18202. * will only run once all synchronous validators have passed.
  18203. *
  18204. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  18205. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  18206. *
  18207. * ```js
  18208. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  18209. * var value = modelValue || viewValue;
  18210. *
  18211. * // Lookup user by username
  18212. * return $http.get('/api/users/' + value).
  18213. * then(function resolved() {
  18214. * //username exists, this means validation fails
  18215. * return $q.reject('exists');
  18216. * }, function rejected() {
  18217. * //username does not exist, therefore this validation passes
  18218. * return true;
  18219. * });
  18220. * };
  18221. * ```
  18222. *
  18223. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  18224. * view value has changed. It is called with no arguments, and its return value is ignored.
  18225. * This can be used in place of additional $watches against the model value.
  18226. *
  18227. * @property {Object} $error An object hash with all failing validator ids as keys.
  18228. * @property {Object} $pending An object hash with all pending validator ids as keys.
  18229. *
  18230. * @property {boolean} $untouched True if control has not lost focus yet.
  18231. * @property {boolean} $touched True if control has lost focus.
  18232. * @property {boolean} $pristine True if user has not interacted with the control yet.
  18233. * @property {boolean} $dirty True if user has already interacted with the control.
  18234. * @property {boolean} $valid True if there is no error.
  18235. * @property {boolean} $invalid True if at least one error on the control.
  18236. * @property {string} $name The name attribute of the control.
  18237. *
  18238. * @description
  18239. *
  18240. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  18241. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  18242. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  18243. * listening to DOM events.
  18244. * Such DOM related logic should be provided by other directives which make use of
  18245. * `NgModelController` for data-binding to control elements.
  18246. * Angular provides this DOM logic for most {@link input `input`} elements.
  18247. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  18248. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  18249. *
  18250. * @example
  18251. * ### Custom Control Example
  18252. * This example shows how to use `NgModelController` with a custom control to achieve
  18253. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  18254. * collaborate together to achieve the desired result.
  18255. *
  18256. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  18257. * contents be edited in place by the user. This will not work on older browsers.
  18258. *
  18259. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  18260. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  18261. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  18262. * that content using the `$sce` service.
  18263. *
  18264. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  18265. <file name="style.css">
  18266. [contenteditable] {
  18267. border: 1px solid black;
  18268. background-color: white;
  18269. min-height: 20px;
  18270. }
  18271. .ng-invalid {
  18272. border: 1px solid red;
  18273. }
  18274. </file>
  18275. <file name="script.js">
  18276. angular.module('customControl', ['ngSanitize']).
  18277. directive('contenteditable', ['$sce', function($sce) {
  18278. return {
  18279. restrict: 'A', // only activate on element attribute
  18280. require: '?ngModel', // get a hold of NgModelController
  18281. link: function(scope, element, attrs, ngModel) {
  18282. if (!ngModel) return; // do nothing if no ng-model
  18283. // Specify how UI should be updated
  18284. ngModel.$render = function() {
  18285. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  18286. };
  18287. // Listen for change events to enable binding
  18288. element.on('blur keyup change', function() {
  18289. scope.$evalAsync(read);
  18290. });
  18291. read(); // initialize
  18292. // Write data to the model
  18293. function read() {
  18294. var html = element.html();
  18295. // When we clear the content editable the browser leaves a <br> behind
  18296. // If strip-br attribute is provided then we strip this out
  18297. if ( attrs.stripBr && html == '<br>' ) {
  18298. html = '';
  18299. }
  18300. ngModel.$setViewValue(html);
  18301. }
  18302. }
  18303. };
  18304. }]);
  18305. </file>
  18306. <file name="index.html">
  18307. <form name="myForm">
  18308. <div contenteditable
  18309. name="myWidget" ng-model="userContent"
  18310. strip-br="true"
  18311. required>Change me!</div>
  18312. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  18313. <hr>
  18314. <textarea ng-model="userContent"></textarea>
  18315. </form>
  18316. </file>
  18317. <file name="protractor.js" type="protractor">
  18318. it('should data-bind and become invalid', function() {
  18319. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  18320. // SafariDriver can't handle contenteditable
  18321. // and Firefox driver can't clear contenteditables very well
  18322. return;
  18323. }
  18324. var contentEditable = element(by.css('[contenteditable]'));
  18325. var content = 'Change me!';
  18326. expect(contentEditable.getText()).toEqual(content);
  18327. contentEditable.clear();
  18328. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  18329. expect(contentEditable.getText()).toEqual('');
  18330. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  18331. });
  18332. </file>
  18333. * </example>
  18334. *
  18335. *
  18336. */
  18337. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  18338. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  18339. this.$viewValue = Number.NaN;
  18340. this.$modelValue = Number.NaN;
  18341. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  18342. this.$validators = {};
  18343. this.$asyncValidators = {};
  18344. this.$parsers = [];
  18345. this.$formatters = [];
  18346. this.$viewChangeListeners = [];
  18347. this.$untouched = true;
  18348. this.$touched = false;
  18349. this.$pristine = true;
  18350. this.$dirty = false;
  18351. this.$valid = true;
  18352. this.$invalid = false;
  18353. this.$error = {}; // keep invalid keys here
  18354. this.$$success = {}; // keep valid keys here
  18355. this.$pending = undefined; // keep pending keys here
  18356. this.$name = $interpolate($attr.name || '', false)($scope);
  18357. var parsedNgModel = $parse($attr.ngModel),
  18358. parsedNgModelAssign = parsedNgModel.assign,
  18359. ngModelGet = parsedNgModel,
  18360. ngModelSet = parsedNgModelAssign,
  18361. pendingDebounce = null,
  18362. ctrl = this;
  18363. this.$$setOptions = function(options) {
  18364. ctrl.$options = options;
  18365. if (options && options.getterSetter) {
  18366. var invokeModelGetter = $parse($attr.ngModel + '()'),
  18367. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  18368. ngModelGet = function($scope) {
  18369. var modelValue = parsedNgModel($scope);
  18370. if (isFunction(modelValue)) {
  18371. modelValue = invokeModelGetter($scope);
  18372. }
  18373. return modelValue;
  18374. };
  18375. ngModelSet = function($scope, newValue) {
  18376. if (isFunction(parsedNgModel($scope))) {
  18377. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  18378. } else {
  18379. parsedNgModelAssign($scope, ctrl.$modelValue);
  18380. }
  18381. };
  18382. } else if (!parsedNgModel.assign) {
  18383. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  18384. $attr.ngModel, startingTag($element));
  18385. }
  18386. };
  18387. /**
  18388. * @ngdoc method
  18389. * @name ngModel.NgModelController#$render
  18390. *
  18391. * @description
  18392. * Called when the view needs to be updated. It is expected that the user of the ng-model
  18393. * directive will implement this method.
  18394. *
  18395. * The `$render()` method is invoked in the following situations:
  18396. *
  18397. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  18398. * committed value then `$render()` is called to update the input control.
  18399. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  18400. * the `$viewValue` are different to last time.
  18401. *
  18402. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  18403. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  18404. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  18405. * invoked if you only change a property on the objects.
  18406. */
  18407. this.$render = noop;
  18408. /**
  18409. * @ngdoc method
  18410. * @name ngModel.NgModelController#$isEmpty
  18411. *
  18412. * @description
  18413. * This is called when we need to determine if the value of an input is empty.
  18414. *
  18415. * For instance, the required directive does this to work out if the input has data or not.
  18416. *
  18417. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  18418. *
  18419. * You can override this for input directives whose concept of being empty is different to the
  18420. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  18421. * implies empty.
  18422. *
  18423. * @param {*} value The value of the input to check for emptiness.
  18424. * @returns {boolean} True if `value` is "empty".
  18425. */
  18426. this.$isEmpty = function(value) {
  18427. return isUndefined(value) || value === '' || value === null || value !== value;
  18428. };
  18429. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  18430. currentValidationRunId = 0;
  18431. /**
  18432. * @ngdoc method
  18433. * @name ngModel.NgModelController#$setValidity
  18434. *
  18435. * @description
  18436. * Change the validity state, and notify the form.
  18437. *
  18438. * This method can be called within $parsers/$formatters or a custom validation implementation.
  18439. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  18440. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  18441. *
  18442. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  18443. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  18444. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  18445. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  18446. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  18447. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  18448. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  18449. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  18450. * Skipped is used by Angular when validators do not run because of parse errors and
  18451. * when `$asyncValidators` do not run because any of the `$validators` failed.
  18452. */
  18453. addSetValidityMethod({
  18454. ctrl: this,
  18455. $element: $element,
  18456. set: function(object, property) {
  18457. object[property] = true;
  18458. },
  18459. unset: function(object, property) {
  18460. delete object[property];
  18461. },
  18462. parentForm: parentForm,
  18463. $animate: $animate
  18464. });
  18465. /**
  18466. * @ngdoc method
  18467. * @name ngModel.NgModelController#$setPristine
  18468. *
  18469. * @description
  18470. * Sets the control to its pristine state.
  18471. *
  18472. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  18473. * state (`ng-pristine` class). A model is considered to be pristine when the control
  18474. * has not been changed from when first compiled.
  18475. */
  18476. this.$setPristine = function() {
  18477. ctrl.$dirty = false;
  18478. ctrl.$pristine = true;
  18479. $animate.removeClass($element, DIRTY_CLASS);
  18480. $animate.addClass($element, PRISTINE_CLASS);
  18481. };
  18482. /**
  18483. * @ngdoc method
  18484. * @name ngModel.NgModelController#$setDirty
  18485. *
  18486. * @description
  18487. * Sets the control to its dirty state.
  18488. *
  18489. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  18490. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  18491. * from when first compiled.
  18492. */
  18493. this.$setDirty = function() {
  18494. ctrl.$dirty = true;
  18495. ctrl.$pristine = false;
  18496. $animate.removeClass($element, PRISTINE_CLASS);
  18497. $animate.addClass($element, DIRTY_CLASS);
  18498. parentForm.$setDirty();
  18499. };
  18500. /**
  18501. * @ngdoc method
  18502. * @name ngModel.NgModelController#$setUntouched
  18503. *
  18504. * @description
  18505. * Sets the control to its untouched state.
  18506. *
  18507. * This method can be called to remove the `ng-touched` class and set the control to its
  18508. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  18509. * by default, however this function can be used to restore that state if the model has
  18510. * already been touched by the user.
  18511. */
  18512. this.$setUntouched = function() {
  18513. ctrl.$touched = false;
  18514. ctrl.$untouched = true;
  18515. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  18516. };
  18517. /**
  18518. * @ngdoc method
  18519. * @name ngModel.NgModelController#$setTouched
  18520. *
  18521. * @description
  18522. * Sets the control to its touched state.
  18523. *
  18524. * This method can be called to remove the `ng-untouched` class and set the control to its
  18525. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  18526. * first focused the control element and then shifted focus away from the control (blur event).
  18527. */
  18528. this.$setTouched = function() {
  18529. ctrl.$touched = true;
  18530. ctrl.$untouched = false;
  18531. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  18532. };
  18533. /**
  18534. * @ngdoc method
  18535. * @name ngModel.NgModelController#$rollbackViewValue
  18536. *
  18537. * @description
  18538. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  18539. * which may be caused by a pending debounced event or because the input is waiting for a some
  18540. * future event.
  18541. *
  18542. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  18543. * as blur you can have a situation where there is a period when the `$viewValue`
  18544. * is out of synch with the ngModel's `$modelValue`.
  18545. *
  18546. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  18547. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  18548. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  18549. *
  18550. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  18551. * input which may have such events pending. This is important in order to make sure that the
  18552. * input field will be updated with the new model value and any pending operations are cancelled.
  18553. *
  18554. * <example name="ng-model-cancel-update" module="cancel-update-example">
  18555. * <file name="app.js">
  18556. * angular.module('cancel-update-example', [])
  18557. *
  18558. * .controller('CancelUpdateController', ['$scope', function($scope) {
  18559. * $scope.resetWithCancel = function(e) {
  18560. * if (e.keyCode == 27) {
  18561. * $scope.myForm.myInput1.$rollbackViewValue();
  18562. * $scope.myValue = '';
  18563. * }
  18564. * };
  18565. * $scope.resetWithoutCancel = function(e) {
  18566. * if (e.keyCode == 27) {
  18567. * $scope.myValue = '';
  18568. * }
  18569. * };
  18570. * }]);
  18571. * </file>
  18572. * <file name="index.html">
  18573. * <div ng-controller="CancelUpdateController">
  18574. * <p>Try typing something in each input. See that the model only updates when you
  18575. * blur off the input.
  18576. * </p>
  18577. * <p>Now see what happens if you start typing then press the Escape key</p>
  18578. *
  18579. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  18580. * <p>With $rollbackViewValue()</p>
  18581. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  18582. * myValue: "{{ myValue }}"
  18583. *
  18584. * <p>Without $rollbackViewValue()</p>
  18585. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  18586. * myValue: "{{ myValue }}"
  18587. * </form>
  18588. * </div>
  18589. * </file>
  18590. * </example>
  18591. */
  18592. this.$rollbackViewValue = function() {
  18593. $timeout.cancel(pendingDebounce);
  18594. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  18595. ctrl.$render();
  18596. };
  18597. /**
  18598. * @ngdoc method
  18599. * @name ngModel.NgModelController#$validate
  18600. *
  18601. * @description
  18602. * Runs each of the registered validators (first synchronous validators and then
  18603. * asynchronous validators).
  18604. * If the validity changes to invalid, the model will be set to `undefined`,
  18605. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  18606. * If the validity changes to valid, it will set the model to the last available valid
  18607. * modelValue, i.e. either the last parsed value or the last value set from the scope.
  18608. */
  18609. this.$validate = function() {
  18610. // ignore $validate before model is initialized
  18611. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18612. return;
  18613. }
  18614. var viewValue = ctrl.$$lastCommittedViewValue;
  18615. // Note: we use the $$rawModelValue as $modelValue might have been
  18616. // set to undefined during a view -> model update that found validation
  18617. // errors. We can't parse the view here, since that could change
  18618. // the model although neither viewValue nor the model on the scope changed
  18619. var modelValue = ctrl.$$rawModelValue;
  18620. // Check if the there's a parse error, so we don't unset it accidentially
  18621. var parserName = ctrl.$$parserName || 'parse';
  18622. var parserValid = ctrl.$error[parserName] ? false : undefined;
  18623. var prevValid = ctrl.$valid;
  18624. var prevModelValue = ctrl.$modelValue;
  18625. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18626. ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
  18627. // If there was no change in validity, don't update the model
  18628. // This prevents changing an invalid modelValue to undefined
  18629. if (!allowInvalid && prevValid !== allValid) {
  18630. // Note: Don't check ctrl.$valid here, as we could have
  18631. // external validators (e.g. calculated on the server),
  18632. // that just call $setValidity and need the model value
  18633. // to calculate their validity.
  18634. ctrl.$modelValue = allValid ? modelValue : undefined;
  18635. if (ctrl.$modelValue !== prevModelValue) {
  18636. ctrl.$$writeModelToScope();
  18637. }
  18638. }
  18639. });
  18640. };
  18641. this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
  18642. currentValidationRunId++;
  18643. var localValidationRunId = currentValidationRunId;
  18644. // check parser error
  18645. if (!processParseErrors(parseValid)) {
  18646. validationDone(false);
  18647. return;
  18648. }
  18649. if (!processSyncValidators()) {
  18650. validationDone(false);
  18651. return;
  18652. }
  18653. processAsyncValidators();
  18654. function processParseErrors(parseValid) {
  18655. var errorKey = ctrl.$$parserName || 'parse';
  18656. if (parseValid === undefined) {
  18657. setValidity(errorKey, null);
  18658. } else {
  18659. setValidity(errorKey, parseValid);
  18660. if (!parseValid) {
  18661. forEach(ctrl.$validators, function(v, name) {
  18662. setValidity(name, null);
  18663. });
  18664. forEach(ctrl.$asyncValidators, function(v, name) {
  18665. setValidity(name, null);
  18666. });
  18667. return false;
  18668. }
  18669. }
  18670. return true;
  18671. }
  18672. function processSyncValidators() {
  18673. var syncValidatorsValid = true;
  18674. forEach(ctrl.$validators, function(validator, name) {
  18675. var result = validator(modelValue, viewValue);
  18676. syncValidatorsValid = syncValidatorsValid && result;
  18677. setValidity(name, result);
  18678. });
  18679. if (!syncValidatorsValid) {
  18680. forEach(ctrl.$asyncValidators, function(v, name) {
  18681. setValidity(name, null);
  18682. });
  18683. return false;
  18684. }
  18685. return true;
  18686. }
  18687. function processAsyncValidators() {
  18688. var validatorPromises = [];
  18689. var allValid = true;
  18690. forEach(ctrl.$asyncValidators, function(validator, name) {
  18691. var promise = validator(modelValue, viewValue);
  18692. if (!isPromiseLike(promise)) {
  18693. throw $ngModelMinErr("$asyncValidators",
  18694. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  18695. }
  18696. setValidity(name, undefined);
  18697. validatorPromises.push(promise.then(function() {
  18698. setValidity(name, true);
  18699. }, function(error) {
  18700. allValid = false;
  18701. setValidity(name, false);
  18702. }));
  18703. });
  18704. if (!validatorPromises.length) {
  18705. validationDone(true);
  18706. } else {
  18707. $q.all(validatorPromises).then(function() {
  18708. validationDone(allValid);
  18709. }, noop);
  18710. }
  18711. }
  18712. function setValidity(name, isValid) {
  18713. if (localValidationRunId === currentValidationRunId) {
  18714. ctrl.$setValidity(name, isValid);
  18715. }
  18716. }
  18717. function validationDone(allValid) {
  18718. if (localValidationRunId === currentValidationRunId) {
  18719. doneCallback(allValid);
  18720. }
  18721. }
  18722. };
  18723. /**
  18724. * @ngdoc method
  18725. * @name ngModel.NgModelController#$commitViewValue
  18726. *
  18727. * @description
  18728. * Commit a pending update to the `$modelValue`.
  18729. *
  18730. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18731. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  18732. * usually handles calling this in response to input events.
  18733. */
  18734. this.$commitViewValue = function() {
  18735. var viewValue = ctrl.$viewValue;
  18736. $timeout.cancel(pendingDebounce);
  18737. // If the view value has not changed then we should just exit, except in the case where there is
  18738. // a native validator on the element. In this case the validation state may have changed even though
  18739. // the viewValue has stayed empty.
  18740. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  18741. return;
  18742. }
  18743. ctrl.$$lastCommittedViewValue = viewValue;
  18744. // change to dirty
  18745. if (ctrl.$pristine) {
  18746. this.$setDirty();
  18747. }
  18748. this.$$parseAndValidate();
  18749. };
  18750. this.$$parseAndValidate = function() {
  18751. var viewValue = ctrl.$$lastCommittedViewValue;
  18752. var modelValue = viewValue;
  18753. var parserValid = isUndefined(modelValue) ? undefined : true;
  18754. if (parserValid) {
  18755. for (var i = 0; i < ctrl.$parsers.length; i++) {
  18756. modelValue = ctrl.$parsers[i](modelValue);
  18757. if (isUndefined(modelValue)) {
  18758. parserValid = false;
  18759. break;
  18760. }
  18761. }
  18762. }
  18763. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18764. // ctrl.$modelValue has not been touched yet...
  18765. ctrl.$modelValue = ngModelGet($scope);
  18766. }
  18767. var prevModelValue = ctrl.$modelValue;
  18768. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18769. ctrl.$$rawModelValue = modelValue;
  18770. if (allowInvalid) {
  18771. ctrl.$modelValue = modelValue;
  18772. writeToModelIfNeeded();
  18773. }
  18774. ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
  18775. if (!allowInvalid) {
  18776. // Note: Don't check ctrl.$valid here, as we could have
  18777. // external validators (e.g. calculated on the server),
  18778. // that just call $setValidity and need the model value
  18779. // to calculate their validity.
  18780. ctrl.$modelValue = allValid ? modelValue : undefined;
  18781. writeToModelIfNeeded();
  18782. }
  18783. });
  18784. function writeToModelIfNeeded() {
  18785. if (ctrl.$modelValue !== prevModelValue) {
  18786. ctrl.$$writeModelToScope();
  18787. }
  18788. }
  18789. };
  18790. this.$$writeModelToScope = function() {
  18791. ngModelSet($scope, ctrl.$modelValue);
  18792. forEach(ctrl.$viewChangeListeners, function(listener) {
  18793. try {
  18794. listener();
  18795. } catch (e) {
  18796. $exceptionHandler(e);
  18797. }
  18798. });
  18799. };
  18800. /**
  18801. * @ngdoc method
  18802. * @name ngModel.NgModelController#$setViewValue
  18803. *
  18804. * @description
  18805. * Update the view value.
  18806. *
  18807. * This method should be called when an input directive want to change the view value; typically,
  18808. * this is done from within a DOM event handler.
  18809. *
  18810. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  18811. * {@link ng.directive:select select} calls it when an option is selected.
  18812. *
  18813. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  18814. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  18815. * watch of objects, it only looks for a change of identity. If you only change the property of
  18816. * the object then ngModel will not realise that the object has changed and will not invoke the
  18817. * `$parsers` and `$validators` pipelines.
  18818. *
  18819. * For this reason, you should not change properties of the copy once it has been passed to
  18820. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  18821. *
  18822. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  18823. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  18824. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  18825. * **expression** specified in the `ng-model` attribute.
  18826. *
  18827. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  18828. *
  18829. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  18830. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  18831. * `updateOn` events is triggered on the DOM element.
  18832. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  18833. * directive is used with a custom debounce for this particular event.
  18834. *
  18835. * Note that calling this function does not trigger a `$digest`.
  18836. *
  18837. * @param {string} value Value from the view.
  18838. * @param {string} trigger Event that triggered the update.
  18839. */
  18840. this.$setViewValue = function(value, trigger) {
  18841. ctrl.$viewValue = value;
  18842. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  18843. ctrl.$$debounceViewValueCommit(trigger);
  18844. }
  18845. };
  18846. this.$$debounceViewValueCommit = function(trigger) {
  18847. var debounceDelay = 0,
  18848. options = ctrl.$options,
  18849. debounce;
  18850. if (options && isDefined(options.debounce)) {
  18851. debounce = options.debounce;
  18852. if (isNumber(debounce)) {
  18853. debounceDelay = debounce;
  18854. } else if (isNumber(debounce[trigger])) {
  18855. debounceDelay = debounce[trigger];
  18856. } else if (isNumber(debounce['default'])) {
  18857. debounceDelay = debounce['default'];
  18858. }
  18859. }
  18860. $timeout.cancel(pendingDebounce);
  18861. if (debounceDelay) {
  18862. pendingDebounce = $timeout(function() {
  18863. ctrl.$commitViewValue();
  18864. }, debounceDelay);
  18865. } else if ($rootScope.$$phase) {
  18866. ctrl.$commitViewValue();
  18867. } else {
  18868. $scope.$apply(function() {
  18869. ctrl.$commitViewValue();
  18870. });
  18871. }
  18872. };
  18873. // model -> value
  18874. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  18875. // 1. scope value is 'a'
  18876. // 2. user enters 'b'
  18877. // 3. ng-change kicks in and reverts scope value to 'a'
  18878. // -> scope value did not change since the last digest as
  18879. // ng-change executes in apply phase
  18880. // 4. view should be changed back to 'a'
  18881. $scope.$watch(function ngModelWatch() {
  18882. var modelValue = ngModelGet($scope);
  18883. // if scope model value and ngModel value are out of sync
  18884. // TODO(perf): why not move this to the action fn?
  18885. if (modelValue !== ctrl.$modelValue) {
  18886. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  18887. var formatters = ctrl.$formatters,
  18888. idx = formatters.length;
  18889. var viewValue = modelValue;
  18890. while (idx--) {
  18891. viewValue = formatters[idx](viewValue);
  18892. }
  18893. if (ctrl.$viewValue !== viewValue) {
  18894. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  18895. ctrl.$render();
  18896. ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
  18897. }
  18898. }
  18899. return modelValue;
  18900. });
  18901. }];
  18902. /**
  18903. * @ngdoc directive
  18904. * @name ngModel
  18905. *
  18906. * @element input
  18907. * @priority 1
  18908. *
  18909. * @description
  18910. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  18911. * property on the scope using {@link ngModel.NgModelController NgModelController},
  18912. * which is created and exposed by this directive.
  18913. *
  18914. * `ngModel` is responsible for:
  18915. *
  18916. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  18917. * require.
  18918. * - Providing validation behavior (i.e. required, number, email, url).
  18919. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  18920. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  18921. * - Registering the control with its parent {@link ng.directive:form form}.
  18922. *
  18923. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  18924. * current scope. If the property doesn't already exist on this scope, it will be created
  18925. * implicitly and added to the scope.
  18926. *
  18927. * For best practices on using `ngModel`, see:
  18928. *
  18929. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  18930. *
  18931. * For basic examples, how to use `ngModel`, see:
  18932. *
  18933. * - {@link ng.directive:input input}
  18934. * - {@link input[text] text}
  18935. * - {@link input[checkbox] checkbox}
  18936. * - {@link input[radio] radio}
  18937. * - {@link input[number] number}
  18938. * - {@link input[email] email}
  18939. * - {@link input[url] url}
  18940. * - {@link input[date] date}
  18941. * - {@link input[datetime-local] datetime-local}
  18942. * - {@link input[time] time}
  18943. * - {@link input[month] month}
  18944. * - {@link input[week] week}
  18945. * - {@link ng.directive:select select}
  18946. * - {@link ng.directive:textarea textarea}
  18947. *
  18948. * # CSS classes
  18949. * The following CSS classes are added and removed on the associated input/select/textarea element
  18950. * depending on the validity of the model.
  18951. *
  18952. * - `ng-valid`: the model is valid
  18953. * - `ng-invalid`: the model is invalid
  18954. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  18955. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  18956. * - `ng-pristine`: the control hasn't been interacted with yet
  18957. * - `ng-dirty`: the control has been interacted with
  18958. * - `ng-touched`: the control has been blurred
  18959. * - `ng-untouched`: the control hasn't been blurred
  18960. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  18961. *
  18962. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18963. *
  18964. * ## Animation Hooks
  18965. *
  18966. * Animations within models are triggered when any of the associated CSS classes are added and removed
  18967. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  18968. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  18969. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  18970. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  18971. *
  18972. * The following example shows a simple way to utilize CSS transitions to style an input element
  18973. * that has been rendered as invalid after it has been validated:
  18974. *
  18975. * <pre>
  18976. * //be sure to include ngAnimate as a module to hook into more
  18977. * //advanced animations
  18978. * .my-input {
  18979. * transition:0.5s linear all;
  18980. * background: white;
  18981. * }
  18982. * .my-input.ng-invalid {
  18983. * background: red;
  18984. * color:white;
  18985. * }
  18986. * </pre>
  18987. *
  18988. * @example
  18989. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  18990. <file name="index.html">
  18991. <script>
  18992. angular.module('inputExample', [])
  18993. .controller('ExampleController', ['$scope', function($scope) {
  18994. $scope.val = '1';
  18995. }]);
  18996. </script>
  18997. <style>
  18998. .my-input {
  18999. -webkit-transition:all linear 0.5s;
  19000. transition:all linear 0.5s;
  19001. background: transparent;
  19002. }
  19003. .my-input.ng-invalid {
  19004. color:white;
  19005. background: red;
  19006. }
  19007. </style>
  19008. Update input to see transitions when valid/invalid.
  19009. Integer is a valid value.
  19010. <form name="testForm" ng-controller="ExampleController">
  19011. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  19012. </form>
  19013. </file>
  19014. * </example>
  19015. *
  19016. * ## Binding to a getter/setter
  19017. *
  19018. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  19019. * function that returns a representation of the model when called with zero arguments, and sets
  19020. * the internal state of a model when called with an argument. It's sometimes useful to use this
  19021. * for models that have an internal representation that's different than what the model exposes
  19022. * to the view.
  19023. *
  19024. * <div class="alert alert-success">
  19025. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  19026. * frequently than other parts of your code.
  19027. * </div>
  19028. *
  19029. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  19030. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  19031. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  19032. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  19033. *
  19034. * The following example shows how to use `ngModel` with a getter/setter:
  19035. *
  19036. * @example
  19037. * <example name="ngModel-getter-setter" module="getterSetterExample">
  19038. <file name="index.html">
  19039. <div ng-controller="ExampleController">
  19040. <form name="userForm">
  19041. Name:
  19042. <input type="text" name="userName"
  19043. ng-model="user.name"
  19044. ng-model-options="{ getterSetter: true }" />
  19045. </form>
  19046. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19047. </div>
  19048. </file>
  19049. <file name="app.js">
  19050. angular.module('getterSetterExample', [])
  19051. .controller('ExampleController', ['$scope', function($scope) {
  19052. var _name = 'Brian';
  19053. $scope.user = {
  19054. name: function(newName) {
  19055. if (angular.isDefined(newName)) {
  19056. _name = newName;
  19057. }
  19058. return _name;
  19059. }
  19060. };
  19061. }]);
  19062. </file>
  19063. * </example>
  19064. */
  19065. var ngModelDirective = ['$rootScope', function($rootScope) {
  19066. return {
  19067. restrict: 'A',
  19068. require: ['ngModel', '^?form', '^?ngModelOptions'],
  19069. controller: NgModelController,
  19070. // Prelink needs to run before any input directive
  19071. // so that we can set the NgModelOptions in NgModelController
  19072. // before anyone else uses it.
  19073. priority: 1,
  19074. compile: function ngModelCompile(element) {
  19075. // Setup initial state of the control
  19076. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  19077. return {
  19078. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  19079. var modelCtrl = ctrls[0],
  19080. formCtrl = ctrls[1] || nullFormCtrl;
  19081. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  19082. // notify others, especially parent forms
  19083. formCtrl.$addControl(modelCtrl);
  19084. attr.$observe('name', function(newValue) {
  19085. if (modelCtrl.$name !== newValue) {
  19086. formCtrl.$$renameControl(modelCtrl, newValue);
  19087. }
  19088. });
  19089. scope.$on('$destroy', function() {
  19090. formCtrl.$removeControl(modelCtrl);
  19091. });
  19092. },
  19093. post: function ngModelPostLink(scope, element, attr, ctrls) {
  19094. var modelCtrl = ctrls[0];
  19095. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  19096. element.on(modelCtrl.$options.updateOn, function(ev) {
  19097. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  19098. });
  19099. }
  19100. element.on('blur', function(ev) {
  19101. if (modelCtrl.$touched) return;
  19102. if ($rootScope.$$phase) {
  19103. scope.$evalAsync(modelCtrl.$setTouched);
  19104. } else {
  19105. scope.$apply(modelCtrl.$setTouched);
  19106. }
  19107. });
  19108. }
  19109. };
  19110. }
  19111. };
  19112. }];
  19113. /**
  19114. * @ngdoc directive
  19115. * @name ngChange
  19116. *
  19117. * @description
  19118. * Evaluate the given expression when the user changes the input.
  19119. * The expression is evaluated immediately, unlike the JavaScript onchange event
  19120. * which only triggers at the end of a change (usually, when the user leaves the
  19121. * form element or presses the return key).
  19122. *
  19123. * The `ngChange` expression is only evaluated when a change in the input value causes
  19124. * a new value to be committed to the model.
  19125. *
  19126. * It will not be evaluated:
  19127. * * if the value returned from the `$parsers` transformation pipeline has not changed
  19128. * * if the input has continued to be invalid since the model will stay `null`
  19129. * * if the model is changed programmatically and not by a change to the input value
  19130. *
  19131. *
  19132. * Note, this directive requires `ngModel` to be present.
  19133. *
  19134. * @element input
  19135. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  19136. * in input value.
  19137. *
  19138. * @example
  19139. * <example name="ngChange-directive" module="changeExample">
  19140. * <file name="index.html">
  19141. * <script>
  19142. * angular.module('changeExample', [])
  19143. * .controller('ExampleController', ['$scope', function($scope) {
  19144. * $scope.counter = 0;
  19145. * $scope.change = function() {
  19146. * $scope.counter++;
  19147. * };
  19148. * }]);
  19149. * </script>
  19150. * <div ng-controller="ExampleController">
  19151. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  19152. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  19153. * <label for="ng-change-example2">Confirmed</label><br />
  19154. * <tt>debug = {{confirmed}}</tt><br/>
  19155. * <tt>counter = {{counter}}</tt><br/>
  19156. * </div>
  19157. * </file>
  19158. * <file name="protractor.js" type="protractor">
  19159. * var counter = element(by.binding('counter'));
  19160. * var debug = element(by.binding('confirmed'));
  19161. *
  19162. * it('should evaluate the expression if changing from view', function() {
  19163. * expect(counter.getText()).toContain('0');
  19164. *
  19165. * element(by.id('ng-change-example1')).click();
  19166. *
  19167. * expect(counter.getText()).toContain('1');
  19168. * expect(debug.getText()).toContain('true');
  19169. * });
  19170. *
  19171. * it('should not evaluate the expression if changing from model', function() {
  19172. * element(by.id('ng-change-example2')).click();
  19173. * expect(counter.getText()).toContain('0');
  19174. * expect(debug.getText()).toContain('true');
  19175. * });
  19176. * </file>
  19177. * </example>
  19178. */
  19179. var ngChangeDirective = valueFn({
  19180. restrict: 'A',
  19181. require: 'ngModel',
  19182. link: function(scope, element, attr, ctrl) {
  19183. ctrl.$viewChangeListeners.push(function() {
  19184. scope.$eval(attr.ngChange);
  19185. });
  19186. }
  19187. });
  19188. var requiredDirective = function() {
  19189. return {
  19190. restrict: 'A',
  19191. require: '?ngModel',
  19192. link: function(scope, elm, attr, ctrl) {
  19193. if (!ctrl) return;
  19194. attr.required = true; // force truthy in case we are on non input element
  19195. ctrl.$validators.required = function(modelValue, viewValue) {
  19196. return !attr.required || !ctrl.$isEmpty(viewValue);
  19197. };
  19198. attr.$observe('required', function() {
  19199. ctrl.$validate();
  19200. });
  19201. }
  19202. };
  19203. };
  19204. var patternDirective = function() {
  19205. return {
  19206. restrict: 'A',
  19207. require: '?ngModel',
  19208. link: function(scope, elm, attr, ctrl) {
  19209. if (!ctrl) return;
  19210. var regexp, patternExp = attr.ngPattern || attr.pattern;
  19211. attr.$observe('pattern', function(regex) {
  19212. if (isString(regex) && regex.length > 0) {
  19213. regex = new RegExp('^' + regex + '$');
  19214. }
  19215. if (regex && !regex.test) {
  19216. throw minErr('ngPattern')('noregexp',
  19217. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  19218. regex, startingTag(elm));
  19219. }
  19220. regexp = regex || undefined;
  19221. ctrl.$validate();
  19222. });
  19223. ctrl.$validators.pattern = function(value) {
  19224. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  19225. };
  19226. }
  19227. };
  19228. };
  19229. var maxlengthDirective = function() {
  19230. return {
  19231. restrict: 'A',
  19232. require: '?ngModel',
  19233. link: function(scope, elm, attr, ctrl) {
  19234. if (!ctrl) return;
  19235. var maxlength = -1;
  19236. attr.$observe('maxlength', function(value) {
  19237. var intVal = int(value);
  19238. maxlength = isNaN(intVal) ? -1 : intVal;
  19239. ctrl.$validate();
  19240. });
  19241. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  19242. return (maxlength < 0) || ctrl.$isEmpty(modelValue) || (viewValue.length <= maxlength);
  19243. };
  19244. }
  19245. };
  19246. };
  19247. var minlengthDirective = function() {
  19248. return {
  19249. restrict: 'A',
  19250. require: '?ngModel',
  19251. link: function(scope, elm, attr, ctrl) {
  19252. if (!ctrl) return;
  19253. var minlength = 0;
  19254. attr.$observe('minlength', function(value) {
  19255. minlength = int(value) || 0;
  19256. ctrl.$validate();
  19257. });
  19258. ctrl.$validators.minlength = function(modelValue, viewValue) {
  19259. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  19260. };
  19261. }
  19262. };
  19263. };
  19264. /**
  19265. * @ngdoc directive
  19266. * @name ngList
  19267. *
  19268. * @description
  19269. * Text input that converts between a delimited string and an array of strings. The default
  19270. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  19271. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  19272. *
  19273. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  19274. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  19275. * list item is respected. This implies that the user of the directive is responsible for
  19276. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  19277. * tab or newline character.
  19278. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  19279. * when joining the list items back together) and whitespace around each list item is stripped
  19280. * before it is added to the model.
  19281. *
  19282. * ### Example with Validation
  19283. *
  19284. * <example name="ngList-directive" module="listExample">
  19285. * <file name="app.js">
  19286. * angular.module('listExample', [])
  19287. * .controller('ExampleController', ['$scope', function($scope) {
  19288. * $scope.names = ['morpheus', 'neo', 'trinity'];
  19289. * }]);
  19290. * </file>
  19291. * <file name="index.html">
  19292. * <form name="myForm" ng-controller="ExampleController">
  19293. * List: <input name="namesInput" ng-model="names" ng-list required>
  19294. * <span class="error" ng-show="myForm.namesInput.$error.required">
  19295. * Required!</span>
  19296. * <br>
  19297. * <tt>names = {{names}}</tt><br/>
  19298. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  19299. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  19300. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19301. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19302. * </form>
  19303. * </file>
  19304. * <file name="protractor.js" type="protractor">
  19305. * var listInput = element(by.model('names'));
  19306. * var names = element(by.exactBinding('names'));
  19307. * var valid = element(by.binding('myForm.namesInput.$valid'));
  19308. * var error = element(by.css('span.error'));
  19309. *
  19310. * it('should initialize to model', function() {
  19311. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  19312. * expect(valid.getText()).toContain('true');
  19313. * expect(error.getCssValue('display')).toBe('none');
  19314. * });
  19315. *
  19316. * it('should be invalid if empty', function() {
  19317. * listInput.clear();
  19318. * listInput.sendKeys('');
  19319. *
  19320. * expect(names.getText()).toContain('');
  19321. * expect(valid.getText()).toContain('false');
  19322. * expect(error.getCssValue('display')).not.toBe('none');
  19323. * });
  19324. * </file>
  19325. * </example>
  19326. *
  19327. * ### Example - splitting on whitespace
  19328. * <example name="ngList-directive-newlines">
  19329. * <file name="index.html">
  19330. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  19331. * <pre>{{ list | json }}</pre>
  19332. * </file>
  19333. * <file name="protractor.js" type="protractor">
  19334. * it("should split the text by newlines", function() {
  19335. * var listInput = element(by.model('list'));
  19336. * var output = element(by.binding('list | json'));
  19337. * listInput.sendKeys('abc\ndef\nghi');
  19338. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  19339. * });
  19340. * </file>
  19341. * </example>
  19342. *
  19343. * @element input
  19344. * @param {string=} ngList optional delimiter that should be used to split the value.
  19345. */
  19346. var ngListDirective = function() {
  19347. return {
  19348. restrict: 'A',
  19349. priority: 100,
  19350. require: 'ngModel',
  19351. link: function(scope, element, attr, ctrl) {
  19352. // We want to control whitespace trimming so we use this convoluted approach
  19353. // to access the ngList attribute, which doesn't pre-trim the attribute
  19354. var ngList = element.attr(attr.$attr.ngList) || ', ';
  19355. var trimValues = attr.ngTrim !== 'false';
  19356. var separator = trimValues ? trim(ngList) : ngList;
  19357. var parse = function(viewValue) {
  19358. // If the viewValue is invalid (say required but empty) it will be `undefined`
  19359. if (isUndefined(viewValue)) return;
  19360. var list = [];
  19361. if (viewValue) {
  19362. forEach(viewValue.split(separator), function(value) {
  19363. if (value) list.push(trimValues ? trim(value) : value);
  19364. });
  19365. }
  19366. return list;
  19367. };
  19368. ctrl.$parsers.push(parse);
  19369. ctrl.$formatters.push(function(value) {
  19370. if (isArray(value)) {
  19371. return value.join(ngList);
  19372. }
  19373. return undefined;
  19374. });
  19375. // Override the standard $isEmpty because an empty array means the input is empty.
  19376. ctrl.$isEmpty = function(value) {
  19377. return !value || !value.length;
  19378. };
  19379. }
  19380. };
  19381. };
  19382. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19383. /**
  19384. * @ngdoc directive
  19385. * @name ngValue
  19386. *
  19387. * @description
  19388. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  19389. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  19390. * the bound value.
  19391. *
  19392. * `ngValue` is useful when dynamically generating lists of radio buttons using
  19393. * {@link ngRepeat `ngRepeat`}, as shown below.
  19394. *
  19395. * Likewise, `ngValue` can be used to generate `<option>` elements for
  19396. * the {@link select `select`} element. In that case however, only strings are supported
  19397. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  19398. * Support for `select` models with non-string values is available via `ngOptions`.
  19399. *
  19400. * @element input
  19401. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19402. * of the `input` element
  19403. *
  19404. * @example
  19405. <example name="ngValue-directive" module="valueExample">
  19406. <file name="index.html">
  19407. <script>
  19408. angular.module('valueExample', [])
  19409. .controller('ExampleController', ['$scope', function($scope) {
  19410. $scope.names = ['pizza', 'unicorns', 'robots'];
  19411. $scope.my = { favorite: 'unicorns' };
  19412. }]);
  19413. </script>
  19414. <form ng-controller="ExampleController">
  19415. <h2>Which is your favorite?</h2>
  19416. <label ng-repeat="name in names" for="{{name}}">
  19417. {{name}}
  19418. <input type="radio"
  19419. ng-model="my.favorite"
  19420. ng-value="name"
  19421. id="{{name}}"
  19422. name="favorite">
  19423. </label>
  19424. <div>You chose {{my.favorite}}</div>
  19425. </form>
  19426. </file>
  19427. <file name="protractor.js" type="protractor">
  19428. var favorite = element(by.binding('my.favorite'));
  19429. it('should initialize to model', function() {
  19430. expect(favorite.getText()).toContain('unicorns');
  19431. });
  19432. it('should bind the values to the inputs', function() {
  19433. element.all(by.model('my.favorite')).get(0).click();
  19434. expect(favorite.getText()).toContain('pizza');
  19435. });
  19436. </file>
  19437. </example>
  19438. */
  19439. var ngValueDirective = function() {
  19440. return {
  19441. restrict: 'A',
  19442. priority: 100,
  19443. compile: function(tpl, tplAttr) {
  19444. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  19445. return function ngValueConstantLink(scope, elm, attr) {
  19446. attr.$set('value', scope.$eval(attr.ngValue));
  19447. };
  19448. } else {
  19449. return function ngValueLink(scope, elm, attr) {
  19450. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  19451. attr.$set('value', value);
  19452. });
  19453. };
  19454. }
  19455. }
  19456. };
  19457. };
  19458. /**
  19459. * @ngdoc directive
  19460. * @name ngModelOptions
  19461. *
  19462. * @description
  19463. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  19464. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  19465. * takes place when a timer expires; this timer will be reset after another change takes place.
  19466. *
  19467. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  19468. * be different than the value in the actual model. This means that if you update the model you
  19469. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  19470. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  19471. *
  19472. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  19473. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  19474. * important because `form` controllers are published to the related scope under the name in their
  19475. * `name` attribute.
  19476. *
  19477. * Any pending changes will take place immediately when an enclosing form is submitted via the
  19478. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19479. * to have access to the updated model.
  19480. *
  19481. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  19482. *
  19483. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  19484. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  19485. * events using an space delimited list. There is a special event called `default` that
  19486. * matches the default events belonging of the control.
  19487. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  19488. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  19489. * custom value for each event. For example:
  19490. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  19491. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  19492. * not validate correctly instead of the default behavior of setting the model to undefined.
  19493. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  19494. `ngModel` as getters/setters.
  19495. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  19496. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  19497. * otherwise the default timezone of the browser will be used.
  19498. *
  19499. * @example
  19500. The following example shows how to override immediate updates. Changes on the inputs within the
  19501. form will update the model only when the control loses focus (blur event). If `escape` key is
  19502. pressed while the input field is focused, the value is reset to the value in the current model.
  19503. <example name="ngModelOptions-directive-blur" module="optionsExample">
  19504. <file name="index.html">
  19505. <div ng-controller="ExampleController">
  19506. <form name="userForm">
  19507. Name:
  19508. <input type="text" name="userName"
  19509. ng-model="user.name"
  19510. ng-model-options="{ updateOn: 'blur' }"
  19511. ng-keyup="cancel($event)" /><br />
  19512. Other data:
  19513. <input type="text" ng-model="user.data" /><br />
  19514. </form>
  19515. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19516. </div>
  19517. </file>
  19518. <file name="app.js">
  19519. angular.module('optionsExample', [])
  19520. .controller('ExampleController', ['$scope', function($scope) {
  19521. $scope.user = { name: 'say', data: '' };
  19522. $scope.cancel = function(e) {
  19523. if (e.keyCode == 27) {
  19524. $scope.userForm.userName.$rollbackViewValue();
  19525. }
  19526. };
  19527. }]);
  19528. </file>
  19529. <file name="protractor.js" type="protractor">
  19530. var model = element(by.binding('user.name'));
  19531. var input = element(by.model('user.name'));
  19532. var other = element(by.model('user.data'));
  19533. it('should allow custom events', function() {
  19534. input.sendKeys(' hello');
  19535. input.click();
  19536. expect(model.getText()).toEqual('say');
  19537. other.click();
  19538. expect(model.getText()).toEqual('say hello');
  19539. });
  19540. it('should $rollbackViewValue when model changes', function() {
  19541. input.sendKeys(' hello');
  19542. expect(input.getAttribute('value')).toEqual('say hello');
  19543. input.sendKeys(protractor.Key.ESCAPE);
  19544. expect(input.getAttribute('value')).toEqual('say');
  19545. other.click();
  19546. expect(model.getText()).toEqual('say');
  19547. });
  19548. </file>
  19549. </example>
  19550. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  19551. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  19552. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  19553. <file name="index.html">
  19554. <div ng-controller="ExampleController">
  19555. <form name="userForm">
  19556. Name:
  19557. <input type="text" name="userName"
  19558. ng-model="user.name"
  19559. ng-model-options="{ debounce: 1000 }" />
  19560. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  19561. </form>
  19562. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19563. </div>
  19564. </file>
  19565. <file name="app.js">
  19566. angular.module('optionsExample', [])
  19567. .controller('ExampleController', ['$scope', function($scope) {
  19568. $scope.user = { name: 'say' };
  19569. }]);
  19570. </file>
  19571. </example>
  19572. This one shows how to bind to getter/setters:
  19573. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  19574. <file name="index.html">
  19575. <div ng-controller="ExampleController">
  19576. <form name="userForm">
  19577. Name:
  19578. <input type="text" name="userName"
  19579. ng-model="user.name"
  19580. ng-model-options="{ getterSetter: true }" />
  19581. </form>
  19582. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19583. </div>
  19584. </file>
  19585. <file name="app.js">
  19586. angular.module('getterSetterExample', [])
  19587. .controller('ExampleController', ['$scope', function($scope) {
  19588. var _name = 'Brian';
  19589. $scope.user = {
  19590. name: function(newName) {
  19591. return angular.isDefined(newName) ? (_name = newName) : _name;
  19592. }
  19593. };
  19594. }]);
  19595. </file>
  19596. </example>
  19597. */
  19598. var ngModelOptionsDirective = function() {
  19599. return {
  19600. restrict: 'A',
  19601. controller: ['$scope', '$attrs', function($scope, $attrs) {
  19602. var that = this;
  19603. this.$options = $scope.$eval($attrs.ngModelOptions);
  19604. // Allow adding/overriding bound events
  19605. if (this.$options.updateOn !== undefined) {
  19606. this.$options.updateOnDefault = false;
  19607. // extract "default" pseudo-event from list of events that can trigger a model update
  19608. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  19609. that.$options.updateOnDefault = true;
  19610. return ' ';
  19611. }));
  19612. } else {
  19613. this.$options.updateOnDefault = true;
  19614. }
  19615. }]
  19616. };
  19617. };
  19618. // helper methods
  19619. function addSetValidityMethod(context) {
  19620. var ctrl = context.ctrl,
  19621. $element = context.$element,
  19622. classCache = {},
  19623. set = context.set,
  19624. unset = context.unset,
  19625. parentForm = context.parentForm,
  19626. $animate = context.$animate;
  19627. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  19628. ctrl.$setValidity = setValidity;
  19629. function setValidity(validationErrorKey, state, options) {
  19630. if (state === undefined) {
  19631. createAndSet('$pending', validationErrorKey, options);
  19632. } else {
  19633. unsetAndCleanup('$pending', validationErrorKey, options);
  19634. }
  19635. if (!isBoolean(state)) {
  19636. unset(ctrl.$error, validationErrorKey, options);
  19637. unset(ctrl.$$success, validationErrorKey, options);
  19638. } else {
  19639. if (state) {
  19640. unset(ctrl.$error, validationErrorKey, options);
  19641. set(ctrl.$$success, validationErrorKey, options);
  19642. } else {
  19643. set(ctrl.$error, validationErrorKey, options);
  19644. unset(ctrl.$$success, validationErrorKey, options);
  19645. }
  19646. }
  19647. if (ctrl.$pending) {
  19648. cachedToggleClass(PENDING_CLASS, true);
  19649. ctrl.$valid = ctrl.$invalid = undefined;
  19650. toggleValidationCss('', null);
  19651. } else {
  19652. cachedToggleClass(PENDING_CLASS, false);
  19653. ctrl.$valid = isObjectEmpty(ctrl.$error);
  19654. ctrl.$invalid = !ctrl.$valid;
  19655. toggleValidationCss('', ctrl.$valid);
  19656. }
  19657. // re-read the state as the set/unset methods could have
  19658. // combined state in ctrl.$error[validationError] (used for forms),
  19659. // where setting/unsetting only increments/decrements the value,
  19660. // and does not replace it.
  19661. var combinedState;
  19662. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  19663. combinedState = undefined;
  19664. } else if (ctrl.$error[validationErrorKey]) {
  19665. combinedState = false;
  19666. } else if (ctrl.$$success[validationErrorKey]) {
  19667. combinedState = true;
  19668. } else {
  19669. combinedState = null;
  19670. }
  19671. toggleValidationCss(validationErrorKey, combinedState);
  19672. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  19673. }
  19674. function createAndSet(name, value, options) {
  19675. if (!ctrl[name]) {
  19676. ctrl[name] = {};
  19677. }
  19678. set(ctrl[name], value, options);
  19679. }
  19680. function unsetAndCleanup(name, value, options) {
  19681. if (ctrl[name]) {
  19682. unset(ctrl[name], value, options);
  19683. }
  19684. if (isObjectEmpty(ctrl[name])) {
  19685. ctrl[name] = undefined;
  19686. }
  19687. }
  19688. function cachedToggleClass(className, switchValue) {
  19689. if (switchValue && !classCache[className]) {
  19690. $animate.addClass($element, className);
  19691. classCache[className] = true;
  19692. } else if (!switchValue && classCache[className]) {
  19693. $animate.removeClass($element, className);
  19694. classCache[className] = false;
  19695. }
  19696. }
  19697. function toggleValidationCss(validationErrorKey, isValid) {
  19698. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  19699. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  19700. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  19701. }
  19702. }
  19703. function isObjectEmpty(obj) {
  19704. if (obj) {
  19705. for (var prop in obj) {
  19706. return false;
  19707. }
  19708. }
  19709. return true;
  19710. }
  19711. /**
  19712. * @ngdoc directive
  19713. * @name ngBind
  19714. * @restrict AC
  19715. *
  19716. * @description
  19717. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  19718. * with the value of a given expression, and to update the text content when the value of that
  19719. * expression changes.
  19720. *
  19721. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  19722. * `{{ expression }}` which is similar but less verbose.
  19723. *
  19724. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  19725. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  19726. * element attribute, it makes the bindings invisible to the user while the page is loading.
  19727. *
  19728. * An alternative solution to this problem would be using the
  19729. * {@link ng.directive:ngCloak ngCloak} directive.
  19730. *
  19731. *
  19732. * @element ANY
  19733. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  19734. *
  19735. * @example
  19736. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  19737. <example module="bindExample">
  19738. <file name="index.html">
  19739. <script>
  19740. angular.module('bindExample', [])
  19741. .controller('ExampleController', ['$scope', function($scope) {
  19742. $scope.name = 'Whirled';
  19743. }]);
  19744. </script>
  19745. <div ng-controller="ExampleController">
  19746. Enter name: <input type="text" ng-model="name"><br>
  19747. Hello <span ng-bind="name"></span>!
  19748. </div>
  19749. </file>
  19750. <file name="protractor.js" type="protractor">
  19751. it('should check ng-bind', function() {
  19752. var nameInput = element(by.model('name'));
  19753. expect(element(by.binding('name')).getText()).toBe('Whirled');
  19754. nameInput.clear();
  19755. nameInput.sendKeys('world');
  19756. expect(element(by.binding('name')).getText()).toBe('world');
  19757. });
  19758. </file>
  19759. </example>
  19760. */
  19761. var ngBindDirective = ['$compile', function($compile) {
  19762. return {
  19763. restrict: 'AC',
  19764. compile: function ngBindCompile(templateElement) {
  19765. $compile.$$addBindingClass(templateElement);
  19766. return function ngBindLink(scope, element, attr) {
  19767. $compile.$$addBindingInfo(element, attr.ngBind);
  19768. element = element[0];
  19769. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  19770. element.textContent = value === undefined ? '' : value;
  19771. });
  19772. };
  19773. }
  19774. };
  19775. }];
  19776. /**
  19777. * @ngdoc directive
  19778. * @name ngBindTemplate
  19779. *
  19780. * @description
  19781. * The `ngBindTemplate` directive specifies that the element
  19782. * text content should be replaced with the interpolation of the template
  19783. * in the `ngBindTemplate` attribute.
  19784. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  19785. * expressions. This directive is needed since some HTML elements
  19786. * (such as TITLE and OPTION) cannot contain SPAN elements.
  19787. *
  19788. * @element ANY
  19789. * @param {string} ngBindTemplate template of form
  19790. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  19791. *
  19792. * @example
  19793. * Try it here: enter text in text box and watch the greeting change.
  19794. <example module="bindExample">
  19795. <file name="index.html">
  19796. <script>
  19797. angular.module('bindExample', [])
  19798. .controller('ExampleController', ['$scope', function($scope) {
  19799. $scope.salutation = 'Hello';
  19800. $scope.name = 'World';
  19801. }]);
  19802. </script>
  19803. <div ng-controller="ExampleController">
  19804. Salutation: <input type="text" ng-model="salutation"><br>
  19805. Name: <input type="text" ng-model="name"><br>
  19806. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  19807. </div>
  19808. </file>
  19809. <file name="protractor.js" type="protractor">
  19810. it('should check ng-bind', function() {
  19811. var salutationElem = element(by.binding('salutation'));
  19812. var salutationInput = element(by.model('salutation'));
  19813. var nameInput = element(by.model('name'));
  19814. expect(salutationElem.getText()).toBe('Hello World!');
  19815. salutationInput.clear();
  19816. salutationInput.sendKeys('Greetings');
  19817. nameInput.clear();
  19818. nameInput.sendKeys('user');
  19819. expect(salutationElem.getText()).toBe('Greetings user!');
  19820. });
  19821. </file>
  19822. </example>
  19823. */
  19824. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  19825. return {
  19826. compile: function ngBindTemplateCompile(templateElement) {
  19827. $compile.$$addBindingClass(templateElement);
  19828. return function ngBindTemplateLink(scope, element, attr) {
  19829. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  19830. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  19831. element = element[0];
  19832. attr.$observe('ngBindTemplate', function(value) {
  19833. element.textContent = value === undefined ? '' : value;
  19834. });
  19835. };
  19836. }
  19837. };
  19838. }];
  19839. /**
  19840. * @ngdoc directive
  19841. * @name ngBindHtml
  19842. *
  19843. * @description
  19844. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  19845. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  19846. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  19847. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  19848. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  19849. *
  19850. * You may also bypass sanitization for values you know are safe. To do so, bind to
  19851. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  19852. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  19853. *
  19854. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  19855. * will have an exception (instead of an exploit.)
  19856. *
  19857. * @element ANY
  19858. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  19859. *
  19860. * @example
  19861. <example module="bindHtmlExample" deps="angular-sanitize.js">
  19862. <file name="index.html">
  19863. <div ng-controller="ExampleController">
  19864. <p ng-bind-html="myHTML"></p>
  19865. </div>
  19866. </file>
  19867. <file name="script.js">
  19868. angular.module('bindHtmlExample', ['ngSanitize'])
  19869. .controller('ExampleController', ['$scope', function($scope) {
  19870. $scope.myHTML =
  19871. 'I am an <code>HTML</code>string with ' +
  19872. '<a href="#">links!</a> and other <em>stuff</em>';
  19873. }]);
  19874. </file>
  19875. <file name="protractor.js" type="protractor">
  19876. it('should check ng-bind-html', function() {
  19877. expect(element(by.binding('myHTML')).getText()).toBe(
  19878. 'I am an HTMLstring with links! and other stuff');
  19879. });
  19880. </file>
  19881. </example>
  19882. */
  19883. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  19884. return {
  19885. restrict: 'A',
  19886. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  19887. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  19888. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  19889. return (value || '').toString();
  19890. });
  19891. $compile.$$addBindingClass(tElement);
  19892. return function ngBindHtmlLink(scope, element, attr) {
  19893. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  19894. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  19895. // we re-evaluate the expr because we want a TrustedValueHolderType
  19896. // for $sce, not a string
  19897. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  19898. });
  19899. };
  19900. }
  19901. };
  19902. }];
  19903. function classDirective(name, selector) {
  19904. name = 'ngClass' + name;
  19905. return ['$animate', function($animate) {
  19906. return {
  19907. restrict: 'AC',
  19908. link: function(scope, element, attr) {
  19909. var oldVal;
  19910. scope.$watch(attr[name], ngClassWatchAction, true);
  19911. attr.$observe('class', function(value) {
  19912. ngClassWatchAction(scope.$eval(attr[name]));
  19913. });
  19914. if (name !== 'ngClass') {
  19915. scope.$watch('$index', function($index, old$index) {
  19916. // jshint bitwise: false
  19917. var mod = $index & 1;
  19918. if (mod !== (old$index & 1)) {
  19919. var classes = arrayClasses(scope.$eval(attr[name]));
  19920. mod === selector ?
  19921. addClasses(classes) :
  19922. removeClasses(classes);
  19923. }
  19924. });
  19925. }
  19926. function addClasses(classes) {
  19927. var newClasses = digestClassCounts(classes, 1);
  19928. attr.$addClass(newClasses);
  19929. }
  19930. function removeClasses(classes) {
  19931. var newClasses = digestClassCounts(classes, -1);
  19932. attr.$removeClass(newClasses);
  19933. }
  19934. function digestClassCounts(classes, count) {
  19935. var classCounts = element.data('$classCounts') || {};
  19936. var classesToUpdate = [];
  19937. forEach(classes, function(className) {
  19938. if (count > 0 || classCounts[className]) {
  19939. classCounts[className] = (classCounts[className] || 0) + count;
  19940. if (classCounts[className] === +(count > 0)) {
  19941. classesToUpdate.push(className);
  19942. }
  19943. }
  19944. });
  19945. element.data('$classCounts', classCounts);
  19946. return classesToUpdate.join(' ');
  19947. }
  19948. function updateClasses(oldClasses, newClasses) {
  19949. var toAdd = arrayDifference(newClasses, oldClasses);
  19950. var toRemove = arrayDifference(oldClasses, newClasses);
  19951. toAdd = digestClassCounts(toAdd, 1);
  19952. toRemove = digestClassCounts(toRemove, -1);
  19953. if (toAdd && toAdd.length) {
  19954. $animate.addClass(element, toAdd);
  19955. }
  19956. if (toRemove && toRemove.length) {
  19957. $animate.removeClass(element, toRemove);
  19958. }
  19959. }
  19960. function ngClassWatchAction(newVal) {
  19961. if (selector === true || scope.$index % 2 === selector) {
  19962. var newClasses = arrayClasses(newVal || []);
  19963. if (!oldVal) {
  19964. addClasses(newClasses);
  19965. } else if (!equals(newVal,oldVal)) {
  19966. var oldClasses = arrayClasses(oldVal);
  19967. updateClasses(oldClasses, newClasses);
  19968. }
  19969. }
  19970. oldVal = shallowCopy(newVal);
  19971. }
  19972. }
  19973. };
  19974. function arrayDifference(tokens1, tokens2) {
  19975. var values = [];
  19976. outer:
  19977. for (var i = 0; i < tokens1.length; i++) {
  19978. var token = tokens1[i];
  19979. for (var j = 0; j < tokens2.length; j++) {
  19980. if (token == tokens2[j]) continue outer;
  19981. }
  19982. values.push(token);
  19983. }
  19984. return values;
  19985. }
  19986. function arrayClasses(classVal) {
  19987. if (isArray(classVal)) {
  19988. return classVal;
  19989. } else if (isString(classVal)) {
  19990. return classVal.split(' ');
  19991. } else if (isObject(classVal)) {
  19992. var classes = [];
  19993. forEach(classVal, function(v, k) {
  19994. if (v) {
  19995. classes = classes.concat(k.split(' '));
  19996. }
  19997. });
  19998. return classes;
  19999. }
  20000. return classVal;
  20001. }
  20002. }];
  20003. }
  20004. /**
  20005. * @ngdoc directive
  20006. * @name ngClass
  20007. * @restrict AC
  20008. *
  20009. * @description
  20010. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20011. * an expression that represents all classes to be added.
  20012. *
  20013. * The directive operates in three different ways, depending on which of three types the expression
  20014. * evaluates to:
  20015. *
  20016. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20017. * names.
  20018. *
  20019. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  20020. * one or more space-delimited class names.
  20021. *
  20022. * 3. If the expression evaluates to an object, then for each key-value pair of the
  20023. * object with a truthy value the corresponding key is used as a class name.
  20024. *
  20025. * The directive won't add duplicate classes if a particular class was already set.
  20026. *
  20027. * When the expression changes, the previously added classes are removed and only then the
  20028. * new classes are added.
  20029. *
  20030. * @animations
  20031. * add - happens just before the class is applied to the element
  20032. * remove - happens just before the class is removed from the element
  20033. *
  20034. * @element ANY
  20035. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20036. * of the evaluation can be a string representing space delimited class
  20037. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20038. * names of the properties whose values are truthy will be added as css classes to the
  20039. * element.
  20040. *
  20041. * @example Example that demonstrates basic bindings via ngClass directive.
  20042. <example>
  20043. <file name="index.html">
  20044. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  20045. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  20046. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  20047. <input type="checkbox" ng-model="error"> error (apply "red" class)
  20048. <hr>
  20049. <p ng-class="style">Using String Syntax</p>
  20050. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  20051. <hr>
  20052. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20053. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  20054. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  20055. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  20056. </file>
  20057. <file name="style.css">
  20058. .strike {
  20059. text-decoration: line-through;
  20060. }
  20061. .bold {
  20062. font-weight: bold;
  20063. }
  20064. .red {
  20065. color: red;
  20066. }
  20067. </file>
  20068. <file name="protractor.js" type="protractor">
  20069. var ps = element.all(by.css('p'));
  20070. it('should let you toggle the class', function() {
  20071. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20072. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  20073. element(by.model('important')).click();
  20074. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20075. element(by.model('error')).click();
  20076. expect(ps.first().getAttribute('class')).toMatch(/red/);
  20077. });
  20078. it('should let you toggle string example', function() {
  20079. expect(ps.get(1).getAttribute('class')).toBe('');
  20080. element(by.model('style')).clear();
  20081. element(by.model('style')).sendKeys('red');
  20082. expect(ps.get(1).getAttribute('class')).toBe('red');
  20083. });
  20084. it('array example should have 3 classes', function() {
  20085. expect(ps.last().getAttribute('class')).toBe('');
  20086. element(by.model('style1')).sendKeys('bold');
  20087. element(by.model('style2')).sendKeys('strike');
  20088. element(by.model('style3')).sendKeys('red');
  20089. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  20090. });
  20091. </file>
  20092. </example>
  20093. ## Animations
  20094. The example below demonstrates how to perform animations using ngClass.
  20095. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20096. <file name="index.html">
  20097. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20098. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20099. <br>
  20100. <span class="base-class" ng-class="myVar">Sample Text</span>
  20101. </file>
  20102. <file name="style.css">
  20103. .base-class {
  20104. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20105. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20106. }
  20107. .base-class.my-class {
  20108. color: red;
  20109. font-size:3em;
  20110. }
  20111. </file>
  20112. <file name="protractor.js" type="protractor">
  20113. it('should check ng-class', function() {
  20114. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20115. toMatch(/my-class/);
  20116. element(by.id('setbtn')).click();
  20117. expect(element(by.css('.base-class')).getAttribute('class')).
  20118. toMatch(/my-class/);
  20119. element(by.id('clearbtn')).click();
  20120. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20121. toMatch(/my-class/);
  20122. });
  20123. </file>
  20124. </example>
  20125. ## ngClass and pre-existing CSS3 Transitions/Animations
  20126. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20127. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20128. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20129. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  20130. {@link ng.$animate#removeClass $animate.removeClass}.
  20131. */
  20132. var ngClassDirective = classDirective('', true);
  20133. /**
  20134. * @ngdoc directive
  20135. * @name ngClassOdd
  20136. * @restrict AC
  20137. *
  20138. * @description
  20139. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20140. * {@link ng.directive:ngClass ngClass}, except they work in
  20141. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20142. *
  20143. * This directive can be applied only within the scope of an
  20144. * {@link ng.directive:ngRepeat ngRepeat}.
  20145. *
  20146. * @element ANY
  20147. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20148. * of the evaluation can be a string representing space delimited class names or an array.
  20149. *
  20150. * @example
  20151. <example>
  20152. <file name="index.html">
  20153. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20154. <li ng-repeat="name in names">
  20155. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20156. {{name}}
  20157. </span>
  20158. </li>
  20159. </ol>
  20160. </file>
  20161. <file name="style.css">
  20162. .odd {
  20163. color: red;
  20164. }
  20165. .even {
  20166. color: blue;
  20167. }
  20168. </file>
  20169. <file name="protractor.js" type="protractor">
  20170. it('should check ng-class-odd and ng-class-even', function() {
  20171. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20172. toMatch(/odd/);
  20173. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20174. toMatch(/even/);
  20175. });
  20176. </file>
  20177. </example>
  20178. */
  20179. var ngClassOddDirective = classDirective('Odd', 0);
  20180. /**
  20181. * @ngdoc directive
  20182. * @name ngClassEven
  20183. * @restrict AC
  20184. *
  20185. * @description
  20186. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20187. * {@link ng.directive:ngClass ngClass}, except they work in
  20188. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20189. *
  20190. * This directive can be applied only within the scope of an
  20191. * {@link ng.directive:ngRepeat ngRepeat}.
  20192. *
  20193. * @element ANY
  20194. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20195. * result of the evaluation can be a string representing space delimited class names or an array.
  20196. *
  20197. * @example
  20198. <example>
  20199. <file name="index.html">
  20200. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20201. <li ng-repeat="name in names">
  20202. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20203. {{name}} &nbsp; &nbsp; &nbsp;
  20204. </span>
  20205. </li>
  20206. </ol>
  20207. </file>
  20208. <file name="style.css">
  20209. .odd {
  20210. color: red;
  20211. }
  20212. .even {
  20213. color: blue;
  20214. }
  20215. </file>
  20216. <file name="protractor.js" type="protractor">
  20217. it('should check ng-class-odd and ng-class-even', function() {
  20218. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20219. toMatch(/odd/);
  20220. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20221. toMatch(/even/);
  20222. });
  20223. </file>
  20224. </example>
  20225. */
  20226. var ngClassEvenDirective = classDirective('Even', 1);
  20227. /**
  20228. * @ngdoc directive
  20229. * @name ngCloak
  20230. * @restrict AC
  20231. *
  20232. * @description
  20233. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20234. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20235. * directive to avoid the undesirable flicker effect caused by the html template display.
  20236. *
  20237. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20238. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20239. * of the browser view.
  20240. *
  20241. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20242. * `angular.min.js`.
  20243. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20244. *
  20245. * ```css
  20246. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20247. * display: none !important;
  20248. * }
  20249. * ```
  20250. *
  20251. * When this css rule is loaded by the browser, all html elements (including their children) that
  20252. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20253. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20254. * the compiled element visible.
  20255. *
  20256. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20257. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20258. * application.
  20259. *
  20260. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  20261. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  20262. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  20263. *
  20264. * @element ANY
  20265. *
  20266. * @example
  20267. <example>
  20268. <file name="index.html">
  20269. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20270. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  20271. </file>
  20272. <file name="protractor.js" type="protractor">
  20273. it('should remove the template directive and css class', function() {
  20274. expect($('#template1').getAttribute('ng-cloak')).
  20275. toBeNull();
  20276. expect($('#template2').getAttribute('ng-cloak')).
  20277. toBeNull();
  20278. });
  20279. </file>
  20280. </example>
  20281. *
  20282. */
  20283. var ngCloakDirective = ngDirective({
  20284. compile: function(element, attr) {
  20285. attr.$set('ngCloak', undefined);
  20286. element.removeClass('ng-cloak');
  20287. }
  20288. });
  20289. /**
  20290. * @ngdoc directive
  20291. * @name ngController
  20292. *
  20293. * @description
  20294. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20295. * supports the principles behind the Model-View-Controller design pattern.
  20296. *
  20297. * MVC components in angular:
  20298. *
  20299. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20300. * are accessed through bindings.
  20301. * * View — The template (HTML with data bindings) that is rendered into the View.
  20302. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20303. * logic behind the application to decorate the scope with functions and values
  20304. *
  20305. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20306. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20307. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20308. * and executed twice.
  20309. *
  20310. * @element ANY
  20311. * @scope
  20312. * @priority 500
  20313. * @param {expression} ngController Name of a constructor function registered with the current
  20314. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20315. * that on the current scope evaluates to a constructor function.
  20316. *
  20317. * The controller instance can be published into a scope property by specifying
  20318. * `ng-controller="as propertyName"`.
  20319. *
  20320. * If the current `$controllerProvider` is configured to use globals (via
  20321. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20322. * also be the name of a globally accessible constructor function (not recommended).
  20323. *
  20324. * @example
  20325. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20326. * greeting are methods declared on the controller (see source tab). These methods can
  20327. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20328. * in the View without the need for a manual update.
  20329. *
  20330. * Two different declaration styles are included below:
  20331. *
  20332. * * one binds methods and properties directly onto the controller using `this`:
  20333. * `ng-controller="SettingsController1 as settings"`
  20334. * * one injects `$scope` into the controller:
  20335. * `ng-controller="SettingsController2"`
  20336. *
  20337. * The second option is more common in the Angular community, and is generally used in boilerplates
  20338. * and in this guide. However, there are advantages to binding properties directly to the controller
  20339. * and avoiding scope.
  20340. *
  20341. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20342. * multiple controllers apply to an element.
  20343. * * If you are writing your controllers as classes you have easier access to the properties and
  20344. * methods, which will appear on the scope, from inside the controller code.
  20345. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20346. * inheritance masking primitives.
  20347. *
  20348. * This example demonstrates the `controller as` syntax.
  20349. *
  20350. * <example name="ngControllerAs" module="controllerAsExample">
  20351. * <file name="index.html">
  20352. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20353. * Name: <input type="text" ng-model="settings.name"/>
  20354. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  20355. * Contact:
  20356. * <ul>
  20357. * <li ng-repeat="contact in settings.contacts">
  20358. * <select ng-model="contact.type">
  20359. * <option>phone</option>
  20360. * <option>email</option>
  20361. * </select>
  20362. * <input type="text" ng-model="contact.value"/>
  20363. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  20364. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  20365. * </li>
  20366. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  20367. * </ul>
  20368. * </div>
  20369. * </file>
  20370. * <file name="app.js">
  20371. * angular.module('controllerAsExample', [])
  20372. * .controller('SettingsController1', SettingsController1);
  20373. *
  20374. * function SettingsController1() {
  20375. * this.name = "John Smith";
  20376. * this.contacts = [
  20377. * {type: 'phone', value: '408 555 1212'},
  20378. * {type: 'email', value: 'john.smith@example.org'} ];
  20379. * }
  20380. *
  20381. * SettingsController1.prototype.greet = function() {
  20382. * alert(this.name);
  20383. * };
  20384. *
  20385. * SettingsController1.prototype.addContact = function() {
  20386. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20387. * };
  20388. *
  20389. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20390. * var index = this.contacts.indexOf(contactToRemove);
  20391. * this.contacts.splice(index, 1);
  20392. * };
  20393. *
  20394. * SettingsController1.prototype.clearContact = function(contact) {
  20395. * contact.type = 'phone';
  20396. * contact.value = '';
  20397. * };
  20398. * </file>
  20399. * <file name="protractor.js" type="protractor">
  20400. * it('should check controller as', function() {
  20401. * var container = element(by.id('ctrl-as-exmpl'));
  20402. * expect(container.element(by.model('settings.name'))
  20403. * .getAttribute('value')).toBe('John Smith');
  20404. *
  20405. * var firstRepeat =
  20406. * container.element(by.repeater('contact in settings.contacts').row(0));
  20407. * var secondRepeat =
  20408. * container.element(by.repeater('contact in settings.contacts').row(1));
  20409. *
  20410. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20411. * .toBe('408 555 1212');
  20412. *
  20413. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20414. * .toBe('john.smith@example.org');
  20415. *
  20416. * firstRepeat.element(by.linkText('clear')).click();
  20417. *
  20418. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20419. * .toBe('');
  20420. *
  20421. * container.element(by.linkText('add')).click();
  20422. *
  20423. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20424. * .element(by.model('contact.value'))
  20425. * .getAttribute('value'))
  20426. * .toBe('yourname@example.org');
  20427. * });
  20428. * </file>
  20429. * </example>
  20430. *
  20431. * This example demonstrates the "attach to `$scope`" style of controller.
  20432. *
  20433. * <example name="ngController" module="controllerExample">
  20434. * <file name="index.html">
  20435. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20436. * Name: <input type="text" ng-model="name"/>
  20437. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  20438. * Contact:
  20439. * <ul>
  20440. * <li ng-repeat="contact in contacts">
  20441. * <select ng-model="contact.type">
  20442. * <option>phone</option>
  20443. * <option>email</option>
  20444. * </select>
  20445. * <input type="text" ng-model="contact.value"/>
  20446. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  20447. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  20448. * </li>
  20449. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  20450. * </ul>
  20451. * </div>
  20452. * </file>
  20453. * <file name="app.js">
  20454. * angular.module('controllerExample', [])
  20455. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20456. *
  20457. * function SettingsController2($scope) {
  20458. * $scope.name = "John Smith";
  20459. * $scope.contacts = [
  20460. * {type:'phone', value:'408 555 1212'},
  20461. * {type:'email', value:'john.smith@example.org'} ];
  20462. *
  20463. * $scope.greet = function() {
  20464. * alert($scope.name);
  20465. * };
  20466. *
  20467. * $scope.addContact = function() {
  20468. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20469. * };
  20470. *
  20471. * $scope.removeContact = function(contactToRemove) {
  20472. * var index = $scope.contacts.indexOf(contactToRemove);
  20473. * $scope.contacts.splice(index, 1);
  20474. * };
  20475. *
  20476. * $scope.clearContact = function(contact) {
  20477. * contact.type = 'phone';
  20478. * contact.value = '';
  20479. * };
  20480. * }
  20481. * </file>
  20482. * <file name="protractor.js" type="protractor">
  20483. * it('should check controller', function() {
  20484. * var container = element(by.id('ctrl-exmpl'));
  20485. *
  20486. * expect(container.element(by.model('name'))
  20487. * .getAttribute('value')).toBe('John Smith');
  20488. *
  20489. * var firstRepeat =
  20490. * container.element(by.repeater('contact in contacts').row(0));
  20491. * var secondRepeat =
  20492. * container.element(by.repeater('contact in contacts').row(1));
  20493. *
  20494. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20495. * .toBe('408 555 1212');
  20496. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20497. * .toBe('john.smith@example.org');
  20498. *
  20499. * firstRepeat.element(by.linkText('clear')).click();
  20500. *
  20501. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20502. * .toBe('');
  20503. *
  20504. * container.element(by.linkText('add')).click();
  20505. *
  20506. * expect(container.element(by.repeater('contact in contacts').row(2))
  20507. * .element(by.model('contact.value'))
  20508. * .getAttribute('value'))
  20509. * .toBe('yourname@example.org');
  20510. * });
  20511. * </file>
  20512. *</example>
  20513. */
  20514. var ngControllerDirective = [function() {
  20515. return {
  20516. restrict: 'A',
  20517. scope: true,
  20518. controller: '@',
  20519. priority: 500
  20520. };
  20521. }];
  20522. /**
  20523. * @ngdoc directive
  20524. * @name ngCsp
  20525. *
  20526. * @element html
  20527. * @description
  20528. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20529. *
  20530. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20531. *
  20532. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20533. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20534. *
  20535. * - don't use `Function` constructor to generate optimized value getters
  20536. * - don't inject custom stylesheet into the document
  20537. *
  20538. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20539. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20540. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20541. * be raised.
  20542. *
  20543. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20544. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20545. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20546. *
  20547. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20548. * autodetection however triggers a CSP error to be logged in the console:
  20549. *
  20550. * ```
  20551. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20552. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20553. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20554. * ```
  20555. *
  20556. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20557. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20558. * appears first in the html document.
  20559. *
  20560. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20561. *
  20562. * @example
  20563. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20564. ```html
  20565. <!doctype html>
  20566. <html ng-app ng-csp>
  20567. ...
  20568. ...
  20569. </html>
  20570. ```
  20571. * @example
  20572. // Note: the suffix `.csp` in the example name triggers
  20573. // csp mode in our http server!
  20574. <example name="example.csp" module="cspExample" ng-csp="true">
  20575. <file name="index.html">
  20576. <div ng-controller="MainController as ctrl">
  20577. <div>
  20578. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  20579. <span id="counter">
  20580. {{ctrl.counter}}
  20581. </span>
  20582. </div>
  20583. <div>
  20584. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  20585. <span id="evilError">
  20586. {{ctrl.evilError}}
  20587. </span>
  20588. </div>
  20589. </div>
  20590. </file>
  20591. <file name="script.js">
  20592. angular.module('cspExample', [])
  20593. .controller('MainController', function() {
  20594. this.counter = 0;
  20595. this.inc = function() {
  20596. this.counter++;
  20597. };
  20598. this.evil = function() {
  20599. // jshint evil:true
  20600. try {
  20601. eval('1+2');
  20602. } catch (e) {
  20603. this.evilError = e.message;
  20604. }
  20605. };
  20606. });
  20607. </file>
  20608. <file name="protractor.js" type="protractor">
  20609. var util, webdriver;
  20610. var incBtn = element(by.id('inc'));
  20611. var counter = element(by.id('counter'));
  20612. var evilBtn = element(by.id('evil'));
  20613. var evilError = element(by.id('evilError'));
  20614. function getAndClearSevereErrors() {
  20615. return browser.manage().logs().get('browser').then(function(browserLog) {
  20616. return browserLog.filter(function(logEntry) {
  20617. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  20618. });
  20619. });
  20620. }
  20621. function clearErrors() {
  20622. getAndClearSevereErrors();
  20623. }
  20624. function expectNoErrors() {
  20625. getAndClearSevereErrors().then(function(filteredLog) {
  20626. expect(filteredLog.length).toEqual(0);
  20627. if (filteredLog.length) {
  20628. console.log('browser console errors: ' + util.inspect(filteredLog));
  20629. }
  20630. });
  20631. }
  20632. function expectError(regex) {
  20633. getAndClearSevereErrors().then(function(filteredLog) {
  20634. var found = false;
  20635. filteredLog.forEach(function(log) {
  20636. if (log.message.match(regex)) {
  20637. found = true;
  20638. }
  20639. });
  20640. if (!found) {
  20641. throw new Error('expected an error that matches ' + regex);
  20642. }
  20643. });
  20644. }
  20645. beforeEach(function() {
  20646. util = require('util');
  20647. webdriver = require('protractor/node_modules/selenium-webdriver');
  20648. });
  20649. // For now, we only test on Chrome,
  20650. // as Safari does not load the page with Protractor's injected scripts,
  20651. // and Firefox webdriver always disables content security policy (#6358)
  20652. if (browser.params.browser !== 'chrome') {
  20653. return;
  20654. }
  20655. it('should not report errors when the page is loaded', function() {
  20656. // clear errors so we are not dependent on previous tests
  20657. clearErrors();
  20658. // Need to reload the page as the page is already loaded when
  20659. // we come here
  20660. browser.driver.getCurrentUrl().then(function(url) {
  20661. browser.get(url);
  20662. });
  20663. expectNoErrors();
  20664. });
  20665. it('should evaluate expressions', function() {
  20666. expect(counter.getText()).toEqual('0');
  20667. incBtn.click();
  20668. expect(counter.getText()).toEqual('1');
  20669. expectNoErrors();
  20670. });
  20671. it('should throw and report an error when using "eval"', function() {
  20672. evilBtn.click();
  20673. expect(evilError.getText()).toMatch(/Content Security Policy/);
  20674. expectError(/Content Security Policy/);
  20675. });
  20676. </file>
  20677. </example>
  20678. */
  20679. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  20680. // bootstrap the system (before $parse is instantiated), for this reason we just have
  20681. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  20682. /**
  20683. * @ngdoc directive
  20684. * @name ngClick
  20685. *
  20686. * @description
  20687. * The ngClick directive allows you to specify custom behavior when
  20688. * an element is clicked.
  20689. *
  20690. * @element ANY
  20691. * @priority 0
  20692. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  20693. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  20694. *
  20695. * @example
  20696. <example>
  20697. <file name="index.html">
  20698. <button ng-click="count = count + 1" ng-init="count=0">
  20699. Increment
  20700. </button>
  20701. <span>
  20702. count: {{count}}
  20703. </span>
  20704. </file>
  20705. <file name="protractor.js" type="protractor">
  20706. it('should check ng-click', function() {
  20707. expect(element(by.binding('count')).getText()).toMatch('0');
  20708. element(by.css('button')).click();
  20709. expect(element(by.binding('count')).getText()).toMatch('1');
  20710. });
  20711. </file>
  20712. </example>
  20713. */
  20714. /*
  20715. * A collection of directives that allows creation of custom event handlers that are defined as
  20716. * angular expressions and are compiled and executed within the current scope.
  20717. */
  20718. var ngEventDirectives = {};
  20719. // For events that might fire synchronously during DOM manipulation
  20720. // we need to execute their event handlers asynchronously using $evalAsync,
  20721. // so that they are not executed in an inconsistent state.
  20722. var forceAsyncEvents = {
  20723. 'blur': true,
  20724. 'focus': true
  20725. };
  20726. forEach(
  20727. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  20728. function(eventName) {
  20729. var directiveName = directiveNormalize('ng-' + eventName);
  20730. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  20731. return {
  20732. restrict: 'A',
  20733. compile: function($element, attr) {
  20734. // We expose the powerful $event object on the scope that provides access to the Window,
  20735. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  20736. // checks at the cost of speed since event handler expressions are not executed as
  20737. // frequently as regular change detection.
  20738. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  20739. return function ngEventHandler(scope, element) {
  20740. element.on(eventName, function(event) {
  20741. var callback = function() {
  20742. fn(scope, {$event:event});
  20743. };
  20744. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  20745. scope.$evalAsync(callback);
  20746. } else {
  20747. scope.$apply(callback);
  20748. }
  20749. });
  20750. };
  20751. }
  20752. };
  20753. }];
  20754. }
  20755. );
  20756. /**
  20757. * @ngdoc directive
  20758. * @name ngDblclick
  20759. *
  20760. * @description
  20761. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  20762. *
  20763. * @element ANY
  20764. * @priority 0
  20765. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  20766. * a dblclick. (The Event object is available as `$event`)
  20767. *
  20768. * @example
  20769. <example>
  20770. <file name="index.html">
  20771. <button ng-dblclick="count = count + 1" ng-init="count=0">
  20772. Increment (on double click)
  20773. </button>
  20774. count: {{count}}
  20775. </file>
  20776. </example>
  20777. */
  20778. /**
  20779. * @ngdoc directive
  20780. * @name ngMousedown
  20781. *
  20782. * @description
  20783. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  20784. *
  20785. * @element ANY
  20786. * @priority 0
  20787. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  20788. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  20789. *
  20790. * @example
  20791. <example>
  20792. <file name="index.html">
  20793. <button ng-mousedown="count = count + 1" ng-init="count=0">
  20794. Increment (on mouse down)
  20795. </button>
  20796. count: {{count}}
  20797. </file>
  20798. </example>
  20799. */
  20800. /**
  20801. * @ngdoc directive
  20802. * @name ngMouseup
  20803. *
  20804. * @description
  20805. * Specify custom behavior on mouseup event.
  20806. *
  20807. * @element ANY
  20808. * @priority 0
  20809. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  20810. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  20811. *
  20812. * @example
  20813. <example>
  20814. <file name="index.html">
  20815. <button ng-mouseup="count = count + 1" ng-init="count=0">
  20816. Increment (on mouse up)
  20817. </button>
  20818. count: {{count}}
  20819. </file>
  20820. </example>
  20821. */
  20822. /**
  20823. * @ngdoc directive
  20824. * @name ngMouseover
  20825. *
  20826. * @description
  20827. * Specify custom behavior on mouseover event.
  20828. *
  20829. * @element ANY
  20830. * @priority 0
  20831. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  20832. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  20833. *
  20834. * @example
  20835. <example>
  20836. <file name="index.html">
  20837. <button ng-mouseover="count = count + 1" ng-init="count=0">
  20838. Increment (when mouse is over)
  20839. </button>
  20840. count: {{count}}
  20841. </file>
  20842. </example>
  20843. */
  20844. /**
  20845. * @ngdoc directive
  20846. * @name ngMouseenter
  20847. *
  20848. * @description
  20849. * Specify custom behavior on mouseenter event.
  20850. *
  20851. * @element ANY
  20852. * @priority 0
  20853. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  20854. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  20855. *
  20856. * @example
  20857. <example>
  20858. <file name="index.html">
  20859. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  20860. Increment (when mouse enters)
  20861. </button>
  20862. count: {{count}}
  20863. </file>
  20864. </example>
  20865. */
  20866. /**
  20867. * @ngdoc directive
  20868. * @name ngMouseleave
  20869. *
  20870. * @description
  20871. * Specify custom behavior on mouseleave event.
  20872. *
  20873. * @element ANY
  20874. * @priority 0
  20875. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  20876. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  20877. *
  20878. * @example
  20879. <example>
  20880. <file name="index.html">
  20881. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  20882. Increment (when mouse leaves)
  20883. </button>
  20884. count: {{count}}
  20885. </file>
  20886. </example>
  20887. */
  20888. /**
  20889. * @ngdoc directive
  20890. * @name ngMousemove
  20891. *
  20892. * @description
  20893. * Specify custom behavior on mousemove event.
  20894. *
  20895. * @element ANY
  20896. * @priority 0
  20897. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  20898. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  20899. *
  20900. * @example
  20901. <example>
  20902. <file name="index.html">
  20903. <button ng-mousemove="count = count + 1" ng-init="count=0">
  20904. Increment (when mouse moves)
  20905. </button>
  20906. count: {{count}}
  20907. </file>
  20908. </example>
  20909. */
  20910. /**
  20911. * @ngdoc directive
  20912. * @name ngKeydown
  20913. *
  20914. * @description
  20915. * Specify custom behavior on keydown event.
  20916. *
  20917. * @element ANY
  20918. * @priority 0
  20919. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  20920. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20921. *
  20922. * @example
  20923. <example>
  20924. <file name="index.html">
  20925. <input ng-keydown="count = count + 1" ng-init="count=0">
  20926. key down count: {{count}}
  20927. </file>
  20928. </example>
  20929. */
  20930. /**
  20931. * @ngdoc directive
  20932. * @name ngKeyup
  20933. *
  20934. * @description
  20935. * Specify custom behavior on keyup event.
  20936. *
  20937. * @element ANY
  20938. * @priority 0
  20939. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  20940. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20941. *
  20942. * @example
  20943. <example>
  20944. <file name="index.html">
  20945. <p>Typing in the input box below updates the key count</p>
  20946. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  20947. <p>Typing in the input box below updates the keycode</p>
  20948. <input ng-keyup="event=$event">
  20949. <p>event keyCode: {{ event.keyCode }}</p>
  20950. <p>event altKey: {{ event.altKey }}</p>
  20951. </file>
  20952. </example>
  20953. */
  20954. /**
  20955. * @ngdoc directive
  20956. * @name ngKeypress
  20957. *
  20958. * @description
  20959. * Specify custom behavior on keypress event.
  20960. *
  20961. * @element ANY
  20962. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  20963. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  20964. * and can be interrogated for keyCode, altKey, etc.)
  20965. *
  20966. * @example
  20967. <example>
  20968. <file name="index.html">
  20969. <input ng-keypress="count = count + 1" ng-init="count=0">
  20970. key press count: {{count}}
  20971. </file>
  20972. </example>
  20973. */
  20974. /**
  20975. * @ngdoc directive
  20976. * @name ngSubmit
  20977. *
  20978. * @description
  20979. * Enables binding angular expressions to onsubmit events.
  20980. *
  20981. * Additionally it prevents the default action (which for form means sending the request to the
  20982. * server and reloading the current page), but only if the form does not contain `action`,
  20983. * `data-action`, or `x-action` attributes.
  20984. *
  20985. * <div class="alert alert-warning">
  20986. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  20987. * `ngSubmit` handlers together. See the
  20988. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  20989. * for a detailed discussion of when `ngSubmit` may be triggered.
  20990. * </div>
  20991. *
  20992. * @element form
  20993. * @priority 0
  20994. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  20995. * ({@link guide/expression#-event- Event object is available as `$event`})
  20996. *
  20997. * @example
  20998. <example module="submitExample">
  20999. <file name="index.html">
  21000. <script>
  21001. angular.module('submitExample', [])
  21002. .controller('ExampleController', ['$scope', function($scope) {
  21003. $scope.list = [];
  21004. $scope.text = 'hello';
  21005. $scope.submit = function() {
  21006. if ($scope.text) {
  21007. $scope.list.push(this.text);
  21008. $scope.text = '';
  21009. }
  21010. };
  21011. }]);
  21012. </script>
  21013. <form ng-submit="submit()" ng-controller="ExampleController">
  21014. Enter text and hit enter:
  21015. <input type="text" ng-model="text" name="text" />
  21016. <input type="submit" id="submit" value="Submit" />
  21017. <pre>list={{list}}</pre>
  21018. </form>
  21019. </file>
  21020. <file name="protractor.js" type="protractor">
  21021. it('should check ng-submit', function() {
  21022. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21023. element(by.css('#submit')).click();
  21024. expect(element(by.binding('list')).getText()).toContain('hello');
  21025. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21026. });
  21027. it('should ignore empty strings', function() {
  21028. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21029. element(by.css('#submit')).click();
  21030. element(by.css('#submit')).click();
  21031. expect(element(by.binding('list')).getText()).toContain('hello');
  21032. });
  21033. </file>
  21034. </example>
  21035. */
  21036. /**
  21037. * @ngdoc directive
  21038. * @name ngFocus
  21039. *
  21040. * @description
  21041. * Specify custom behavior on focus event.
  21042. *
  21043. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21044. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21045. * during an `$apply` to ensure a consistent state.
  21046. *
  21047. * @element window, input, select, textarea, a
  21048. * @priority 0
  21049. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21050. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21051. *
  21052. * @example
  21053. * See {@link ng.directive:ngClick ngClick}
  21054. */
  21055. /**
  21056. * @ngdoc directive
  21057. * @name ngBlur
  21058. *
  21059. * @description
  21060. * Specify custom behavior on blur event.
  21061. *
  21062. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21063. * an element has lost focus.
  21064. *
  21065. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21066. * (e.g. removing a focussed input),
  21067. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21068. * during an `$apply` to ensure a consistent state.
  21069. *
  21070. * @element window, input, select, textarea, a
  21071. * @priority 0
  21072. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21073. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21074. *
  21075. * @example
  21076. * See {@link ng.directive:ngClick ngClick}
  21077. */
  21078. /**
  21079. * @ngdoc directive
  21080. * @name ngCopy
  21081. *
  21082. * @description
  21083. * Specify custom behavior on copy event.
  21084. *
  21085. * @element window, input, select, textarea, a
  21086. * @priority 0
  21087. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21088. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21089. *
  21090. * @example
  21091. <example>
  21092. <file name="index.html">
  21093. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21094. copied: {{copied}}
  21095. </file>
  21096. </example>
  21097. */
  21098. /**
  21099. * @ngdoc directive
  21100. * @name ngCut
  21101. *
  21102. * @description
  21103. * Specify custom behavior on cut event.
  21104. *
  21105. * @element window, input, select, textarea, a
  21106. * @priority 0
  21107. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21108. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21109. *
  21110. * @example
  21111. <example>
  21112. <file name="index.html">
  21113. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21114. cut: {{cut}}
  21115. </file>
  21116. </example>
  21117. */
  21118. /**
  21119. * @ngdoc directive
  21120. * @name ngPaste
  21121. *
  21122. * @description
  21123. * Specify custom behavior on paste event.
  21124. *
  21125. * @element window, input, select, textarea, a
  21126. * @priority 0
  21127. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21128. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21129. *
  21130. * @example
  21131. <example>
  21132. <file name="index.html">
  21133. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21134. pasted: {{paste}}
  21135. </file>
  21136. </example>
  21137. */
  21138. /**
  21139. * @ngdoc directive
  21140. * @name ngIf
  21141. * @restrict A
  21142. *
  21143. * @description
  21144. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21145. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21146. * value then the element is removed from the DOM, otherwise a clone of the
  21147. * element is reinserted into the DOM.
  21148. *
  21149. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21150. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21151. * case when this difference is significant is when using css selectors that rely on an element's
  21152. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21153. *
  21154. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21155. * is created when the element is restored. The scope created within `ngIf` inherits from
  21156. * its parent scope using
  21157. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21158. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21159. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21160. * variable within the child scope will override (hide) the value in the parent scope.
  21161. *
  21162. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21163. * is if an element's class attribute is directly modified after it's compiled, using something like
  21164. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21165. * the added class will be lost because the original compiled state is used to regenerate the element.
  21166. *
  21167. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21168. * and `leave` effects.
  21169. *
  21170. * @animations
  21171. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21172. * leave - happens just before the `ngIf` contents are removed from the DOM
  21173. *
  21174. * @element ANY
  21175. * @scope
  21176. * @priority 600
  21177. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21178. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21179. * element is added to the DOM tree.
  21180. *
  21181. * @example
  21182. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21183. <file name="index.html">
  21184. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  21185. Show when checked:
  21186. <span ng-if="checked" class="animate-if">
  21187. This is removed when the checkbox is unchecked.
  21188. </span>
  21189. </file>
  21190. <file name="animations.css">
  21191. .animate-if {
  21192. background:white;
  21193. border:1px solid black;
  21194. padding:10px;
  21195. }
  21196. .animate-if.ng-enter, .animate-if.ng-leave {
  21197. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21198. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21199. }
  21200. .animate-if.ng-enter,
  21201. .animate-if.ng-leave.ng-leave-active {
  21202. opacity:0;
  21203. }
  21204. .animate-if.ng-leave,
  21205. .animate-if.ng-enter.ng-enter-active {
  21206. opacity:1;
  21207. }
  21208. </file>
  21209. </example>
  21210. */
  21211. var ngIfDirective = ['$animate', function($animate) {
  21212. return {
  21213. multiElement: true,
  21214. transclude: 'element',
  21215. priority: 600,
  21216. terminal: true,
  21217. restrict: 'A',
  21218. $$tlb: true,
  21219. link: function($scope, $element, $attr, ctrl, $transclude) {
  21220. var block, childScope, previousElements;
  21221. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21222. if (value) {
  21223. if (!childScope) {
  21224. $transclude(function(clone, newScope) {
  21225. childScope = newScope;
  21226. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21227. // Note: We only need the first/last node of the cloned nodes.
  21228. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21229. // by a directive with templateUrl when its template arrives.
  21230. block = {
  21231. clone: clone
  21232. };
  21233. $animate.enter(clone, $element.parent(), $element);
  21234. });
  21235. }
  21236. } else {
  21237. if (previousElements) {
  21238. previousElements.remove();
  21239. previousElements = null;
  21240. }
  21241. if (childScope) {
  21242. childScope.$destroy();
  21243. childScope = null;
  21244. }
  21245. if (block) {
  21246. previousElements = getBlockNodes(block.clone);
  21247. $animate.leave(previousElements).then(function() {
  21248. previousElements = null;
  21249. });
  21250. block = null;
  21251. }
  21252. }
  21253. });
  21254. }
  21255. };
  21256. }];
  21257. /**
  21258. * @ngdoc directive
  21259. * @name ngInclude
  21260. * @restrict ECA
  21261. *
  21262. * @description
  21263. * Fetches, compiles and includes an external HTML fragment.
  21264. *
  21265. * By default, the template URL is restricted to the same domain and protocol as the
  21266. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21267. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21268. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21269. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21270. * ng.$sce Strict Contextual Escaping}.
  21271. *
  21272. * In addition, the browser's
  21273. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21274. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21275. * policy may further restrict whether the template is successfully loaded.
  21276. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21277. * access on some browsers.
  21278. *
  21279. * @animations
  21280. * enter - animation is used to bring new content into the browser.
  21281. * leave - animation is used to animate existing content away.
  21282. *
  21283. * The enter and leave animation occur concurrently.
  21284. *
  21285. * @scope
  21286. * @priority 400
  21287. *
  21288. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21289. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21290. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21291. *
  21292. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21293. * $anchorScroll} to scroll the viewport after the content is loaded.
  21294. *
  21295. * - If the attribute is not set, disable scrolling.
  21296. * - If the attribute is set without value, enable scrolling.
  21297. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21298. *
  21299. * @example
  21300. <example module="includeExample" deps="angular-animate.js" animations="true">
  21301. <file name="index.html">
  21302. <div ng-controller="ExampleController">
  21303. <select ng-model="template" ng-options="t.name for t in templates">
  21304. <option value="">(blank)</option>
  21305. </select>
  21306. url of the template: <tt>{{template.url}}</tt>
  21307. <hr/>
  21308. <div class="slide-animate-container">
  21309. <div class="slide-animate" ng-include="template.url"></div>
  21310. </div>
  21311. </div>
  21312. </file>
  21313. <file name="script.js">
  21314. angular.module('includeExample', ['ngAnimate'])
  21315. .controller('ExampleController', ['$scope', function($scope) {
  21316. $scope.templates =
  21317. [ { name: 'template1.html', url: 'template1.html'},
  21318. { name: 'template2.html', url: 'template2.html'} ];
  21319. $scope.template = $scope.templates[0];
  21320. }]);
  21321. </file>
  21322. <file name="template1.html">
  21323. Content of template1.html
  21324. </file>
  21325. <file name="template2.html">
  21326. Content of template2.html
  21327. </file>
  21328. <file name="animations.css">
  21329. .slide-animate-container {
  21330. position:relative;
  21331. background:white;
  21332. border:1px solid black;
  21333. height:40px;
  21334. overflow:hidden;
  21335. }
  21336. .slide-animate {
  21337. padding:10px;
  21338. }
  21339. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21340. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21341. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21342. position:absolute;
  21343. top:0;
  21344. left:0;
  21345. right:0;
  21346. bottom:0;
  21347. display:block;
  21348. padding:10px;
  21349. }
  21350. .slide-animate.ng-enter {
  21351. top:-50px;
  21352. }
  21353. .slide-animate.ng-enter.ng-enter-active {
  21354. top:0;
  21355. }
  21356. .slide-animate.ng-leave {
  21357. top:0;
  21358. }
  21359. .slide-animate.ng-leave.ng-leave-active {
  21360. top:50px;
  21361. }
  21362. </file>
  21363. <file name="protractor.js" type="protractor">
  21364. var templateSelect = element(by.model('template'));
  21365. var includeElem = element(by.css('[ng-include]'));
  21366. it('should load template1.html', function() {
  21367. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21368. });
  21369. it('should load template2.html', function() {
  21370. if (browser.params.browser == 'firefox') {
  21371. // Firefox can't handle using selects
  21372. // See https://github.com/angular/protractor/issues/480
  21373. return;
  21374. }
  21375. templateSelect.click();
  21376. templateSelect.all(by.css('option')).get(2).click();
  21377. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21378. });
  21379. it('should change to blank', function() {
  21380. if (browser.params.browser == 'firefox') {
  21381. // Firefox can't handle using selects
  21382. return;
  21383. }
  21384. templateSelect.click();
  21385. templateSelect.all(by.css('option')).get(0).click();
  21386. expect(includeElem.isPresent()).toBe(false);
  21387. });
  21388. </file>
  21389. </example>
  21390. */
  21391. /**
  21392. * @ngdoc event
  21393. * @name ngInclude#$includeContentRequested
  21394. * @eventType emit on the scope ngInclude was declared in
  21395. * @description
  21396. * Emitted every time the ngInclude content is requested.
  21397. *
  21398. * @param {Object} angularEvent Synthetic event object.
  21399. * @param {String} src URL of content to load.
  21400. */
  21401. /**
  21402. * @ngdoc event
  21403. * @name ngInclude#$includeContentLoaded
  21404. * @eventType emit on the current ngInclude scope
  21405. * @description
  21406. * Emitted every time the ngInclude content is reloaded.
  21407. *
  21408. * @param {Object} angularEvent Synthetic event object.
  21409. * @param {String} src URL of content to load.
  21410. */
  21411. /**
  21412. * @ngdoc event
  21413. * @name ngInclude#$includeContentError
  21414. * @eventType emit on the scope ngInclude was declared in
  21415. * @description
  21416. * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
  21417. *
  21418. * @param {Object} angularEvent Synthetic event object.
  21419. * @param {String} src URL of content to load.
  21420. */
  21421. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21422. function($templateRequest, $anchorScroll, $animate, $sce) {
  21423. return {
  21424. restrict: 'ECA',
  21425. priority: 400,
  21426. terminal: true,
  21427. transclude: 'element',
  21428. controller: angular.noop,
  21429. compile: function(element, attr) {
  21430. var srcExp = attr.ngInclude || attr.src,
  21431. onloadExp = attr.onload || '',
  21432. autoScrollExp = attr.autoscroll;
  21433. return function(scope, $element, $attr, ctrl, $transclude) {
  21434. var changeCounter = 0,
  21435. currentScope,
  21436. previousElement,
  21437. currentElement;
  21438. var cleanupLastIncludeContent = function() {
  21439. if (previousElement) {
  21440. previousElement.remove();
  21441. previousElement = null;
  21442. }
  21443. if (currentScope) {
  21444. currentScope.$destroy();
  21445. currentScope = null;
  21446. }
  21447. if (currentElement) {
  21448. $animate.leave(currentElement).then(function() {
  21449. previousElement = null;
  21450. });
  21451. previousElement = currentElement;
  21452. currentElement = null;
  21453. }
  21454. };
  21455. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21456. var afterAnimation = function() {
  21457. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21458. $anchorScroll();
  21459. }
  21460. };
  21461. var thisChangeId = ++changeCounter;
  21462. if (src) {
  21463. //set the 2nd param to true to ignore the template request error so that the inner
  21464. //contents and scope can be cleaned up.
  21465. $templateRequest(src, true).then(function(response) {
  21466. if (thisChangeId !== changeCounter) return;
  21467. var newScope = scope.$new();
  21468. ctrl.template = response;
  21469. // Note: This will also link all children of ng-include that were contained in the original
  21470. // html. If that content contains controllers, ... they could pollute/change the scope.
  21471. // However, using ng-include on an element with additional content does not make sense...
  21472. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21473. // function is called before linking the content, which would apply child
  21474. // directives to non existing elements.
  21475. var clone = $transclude(newScope, function(clone) {
  21476. cleanupLastIncludeContent();
  21477. $animate.enter(clone, null, $element).then(afterAnimation);
  21478. });
  21479. currentScope = newScope;
  21480. currentElement = clone;
  21481. currentScope.$emit('$includeContentLoaded', src);
  21482. scope.$eval(onloadExp);
  21483. }, function() {
  21484. if (thisChangeId === changeCounter) {
  21485. cleanupLastIncludeContent();
  21486. scope.$emit('$includeContentError', src);
  21487. }
  21488. });
  21489. scope.$emit('$includeContentRequested', src);
  21490. } else {
  21491. cleanupLastIncludeContent();
  21492. ctrl.template = null;
  21493. }
  21494. });
  21495. };
  21496. }
  21497. };
  21498. }];
  21499. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21500. // It will replace and compile the content of the element with the loaded template.
  21501. // We need this directive so that the element content is already filled when
  21502. // the link function of another directive on the same element as ngInclude
  21503. // is called.
  21504. var ngIncludeFillContentDirective = ['$compile',
  21505. function($compile) {
  21506. return {
  21507. restrict: 'ECA',
  21508. priority: -400,
  21509. require: 'ngInclude',
  21510. link: function(scope, $element, $attr, ctrl) {
  21511. if (/SVG/.test($element[0].toString())) {
  21512. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21513. // support innerHTML, so detect this here and try to generate the contents
  21514. // specially.
  21515. $element.empty();
  21516. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21517. function namespaceAdaptedClone(clone) {
  21518. $element.append(clone);
  21519. }, {futureParentElement: $element});
  21520. return;
  21521. }
  21522. $element.html(ctrl.template);
  21523. $compile($element.contents())(scope);
  21524. }
  21525. };
  21526. }];
  21527. /**
  21528. * @ngdoc directive
  21529. * @name ngInit
  21530. * @restrict AC
  21531. *
  21532. * @description
  21533. * The `ngInit` directive allows you to evaluate an expression in the
  21534. * current scope.
  21535. *
  21536. * <div class="alert alert-error">
  21537. * The only appropriate use of `ngInit` is for aliasing special properties of
  21538. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21539. * should use {@link guide/controller controllers} rather than `ngInit`
  21540. * to initialize values on a scope.
  21541. * </div>
  21542. * <div class="alert alert-warning">
  21543. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21544. * sure you have parenthesis for correct precedence:
  21545. * <pre class="prettyprint">
  21546. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  21547. * </pre>
  21548. * </div>
  21549. *
  21550. * @priority 450
  21551. *
  21552. * @element ANY
  21553. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21554. *
  21555. * @example
  21556. <example module="initExample">
  21557. <file name="index.html">
  21558. <script>
  21559. angular.module('initExample', [])
  21560. .controller('ExampleController', ['$scope', function($scope) {
  21561. $scope.list = [['a', 'b'], ['c', 'd']];
  21562. }]);
  21563. </script>
  21564. <div ng-controller="ExampleController">
  21565. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  21566. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  21567. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  21568. </div>
  21569. </div>
  21570. </div>
  21571. </file>
  21572. <file name="protractor.js" type="protractor">
  21573. it('should alias index positions', function() {
  21574. var elements = element.all(by.css('.example-init'));
  21575. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  21576. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  21577. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  21578. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  21579. });
  21580. </file>
  21581. </example>
  21582. */
  21583. var ngInitDirective = ngDirective({
  21584. priority: 450,
  21585. compile: function() {
  21586. return {
  21587. pre: function(scope, element, attrs) {
  21588. scope.$eval(attrs.ngInit);
  21589. }
  21590. };
  21591. }
  21592. });
  21593. /**
  21594. * @ngdoc directive
  21595. * @name ngNonBindable
  21596. * @restrict AC
  21597. * @priority 1000
  21598. *
  21599. * @description
  21600. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21601. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21602. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21603. * displays snippets of code, for instance.
  21604. *
  21605. * @element ANY
  21606. *
  21607. * @example
  21608. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21609. * but the one wrapped in `ngNonBindable` is left alone.
  21610. *
  21611. * @example
  21612. <example>
  21613. <file name="index.html">
  21614. <div>Normal: {{1 + 2}}</div>
  21615. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21616. </file>
  21617. <file name="protractor.js" type="protractor">
  21618. it('should check ng-non-bindable', function() {
  21619. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21620. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21621. });
  21622. </file>
  21623. </example>
  21624. */
  21625. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21626. /**
  21627. * @ngdoc directive
  21628. * @name ngPluralize
  21629. * @restrict EA
  21630. *
  21631. * @description
  21632. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21633. * These rules are bundled with angular.js, but can be overridden
  21634. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21635. * by specifying the mappings between
  21636. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21637. * and the strings to be displayed.
  21638. *
  21639. * # Plural categories and explicit number rules
  21640. * There are two
  21641. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21642. * in Angular's default en-US locale: "one" and "other".
  21643. *
  21644. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21645. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21646. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21647. * and explicit number rules throughout the rest of this documentation.
  21648. *
  21649. * # Configuring ngPluralize
  21650. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21651. * You can also provide an optional attribute, `offset`.
  21652. *
  21653. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21654. * Angular expression}; these are evaluated on the current scope for its bound value.
  21655. *
  21656. * The `when` attribute specifies the mappings between plural categories and the actual
  21657. * string to be displayed. The value of the attribute should be a JSON object.
  21658. *
  21659. * The following example shows how to configure ngPluralize:
  21660. *
  21661. * ```html
  21662. * <ng-pluralize count="personCount"
  21663. when="{'0': 'Nobody is viewing.',
  21664. * 'one': '1 person is viewing.',
  21665. * 'other': '{} people are viewing.'}">
  21666. * </ng-pluralize>
  21667. *```
  21668. *
  21669. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21670. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21671. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21672. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21673. * show "a dozen people are viewing".
  21674. *
  21675. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21676. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21677. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21678. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21679. *
  21680. * # Configuring ngPluralize with offset
  21681. * The `offset` attribute allows further customization of pluralized text, which can result in
  21682. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21683. * you might display "John, Kate and 2 others are viewing this document".
  21684. * The offset attribute allows you to offset a number by any desired value.
  21685. * Let's take a look at an example:
  21686. *
  21687. * ```html
  21688. * <ng-pluralize count="personCount" offset=2
  21689. * when="{'0': 'Nobody is viewing.',
  21690. * '1': '{{person1}} is viewing.',
  21691. * '2': '{{person1}} and {{person2}} are viewing.',
  21692. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21693. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21694. * </ng-pluralize>
  21695. * ```
  21696. *
  21697. * Notice that we are still using two plural categories(one, other), but we added
  21698. * three explicit number rules 0, 1 and 2.
  21699. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21700. * When three people view the document, no explicit number rule is found, so
  21701. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21702. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21703. * is shown.
  21704. *
  21705. * Note that when you specify offsets, you must provide explicit number rules for
  21706. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21707. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21708. * plural categories "one" and "other".
  21709. *
  21710. * @param {string|expression} count The variable to be bound to.
  21711. * @param {string} when The mapping between plural category to its corresponding strings.
  21712. * @param {number=} offset Offset to deduct from the total number.
  21713. *
  21714. * @example
  21715. <example module="pluralizeExample">
  21716. <file name="index.html">
  21717. <script>
  21718. angular.module('pluralizeExample', [])
  21719. .controller('ExampleController', ['$scope', function($scope) {
  21720. $scope.person1 = 'Igor';
  21721. $scope.person2 = 'Misko';
  21722. $scope.personCount = 1;
  21723. }]);
  21724. </script>
  21725. <div ng-controller="ExampleController">
  21726. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21727. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21728. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21729. <!--- Example with simple pluralization rules for en locale --->
  21730. Without Offset:
  21731. <ng-pluralize count="personCount"
  21732. when="{'0': 'Nobody is viewing.',
  21733. 'one': '1 person is viewing.',
  21734. 'other': '{} people are viewing.'}">
  21735. </ng-pluralize><br>
  21736. <!--- Example with offset --->
  21737. With Offset(2):
  21738. <ng-pluralize count="personCount" offset=2
  21739. when="{'0': 'Nobody is viewing.',
  21740. '1': '{{person1}} is viewing.',
  21741. '2': '{{person1}} and {{person2}} are viewing.',
  21742. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21743. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21744. </ng-pluralize>
  21745. </div>
  21746. </file>
  21747. <file name="protractor.js" type="protractor">
  21748. it('should show correct pluralized string', function() {
  21749. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21750. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21751. var countInput = element(by.model('personCount'));
  21752. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21753. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21754. countInput.clear();
  21755. countInput.sendKeys('0');
  21756. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21757. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21758. countInput.clear();
  21759. countInput.sendKeys('2');
  21760. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21761. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21762. countInput.clear();
  21763. countInput.sendKeys('3');
  21764. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21765. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21766. countInput.clear();
  21767. countInput.sendKeys('4');
  21768. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21769. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21770. });
  21771. it('should show data-bound names', function() {
  21772. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21773. var personCount = element(by.model('personCount'));
  21774. var person1 = element(by.model('person1'));
  21775. var person2 = element(by.model('person2'));
  21776. personCount.clear();
  21777. personCount.sendKeys('4');
  21778. person1.clear();
  21779. person1.sendKeys('Di');
  21780. person2.clear();
  21781. person2.sendKeys('Vojta');
  21782. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21783. });
  21784. </file>
  21785. </example>
  21786. */
  21787. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21788. var BRACE = /{}/g,
  21789. IS_WHEN = /^when(Minus)?(.+)$/;
  21790. return {
  21791. restrict: 'EA',
  21792. link: function(scope, element, attr) {
  21793. var numberExp = attr.count,
  21794. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21795. offset = attr.offset || 0,
  21796. whens = scope.$eval(whenExp) || {},
  21797. whensExpFns = {},
  21798. startSymbol = $interpolate.startSymbol(),
  21799. endSymbol = $interpolate.endSymbol(),
  21800. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  21801. watchRemover = angular.noop,
  21802. lastCount;
  21803. forEach(attr, function(expression, attributeName) {
  21804. var tmpMatch = IS_WHEN.exec(attributeName);
  21805. if (tmpMatch) {
  21806. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  21807. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  21808. }
  21809. });
  21810. forEach(whens, function(expression, key) {
  21811. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  21812. });
  21813. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  21814. var count = parseFloat(newVal);
  21815. var countIsNaN = isNaN(count);
  21816. if (!countIsNaN && !(count in whens)) {
  21817. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  21818. // Otherwise, check it against pluralization rules in $locale service.
  21819. count = $locale.pluralCat(count - offset);
  21820. }
  21821. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  21822. // In JS `NaN !== NaN`, so we have to exlicitly check.
  21823. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
  21824. watchRemover();
  21825. watchRemover = scope.$watch(whensExpFns[count], updateElementText);
  21826. lastCount = count;
  21827. }
  21828. });
  21829. function updateElementText(newText) {
  21830. element.text(newText || '');
  21831. }
  21832. }
  21833. };
  21834. }];
  21835. /**
  21836. * @ngdoc directive
  21837. * @name ngRepeat
  21838. *
  21839. * @description
  21840. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  21841. * instance gets its own scope, where the given loop variable is set to the current collection item,
  21842. * and `$index` is set to the item index or key.
  21843. *
  21844. * Special properties are exposed on the local scope of each template instance, including:
  21845. *
  21846. * | Variable | Type | Details |
  21847. * |-----------|-----------------|-----------------------------------------------------------------------------|
  21848. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  21849. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  21850. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  21851. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  21852. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  21853. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  21854. *
  21855. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  21856. * This may be useful when, for instance, nesting ngRepeats.
  21857. *
  21858. * # Special repeat start and end points
  21859. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  21860. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  21861. * 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)
  21862. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  21863. *
  21864. * The example below makes use of this feature:
  21865. * ```html
  21866. * <header ng-repeat-start="item in items">
  21867. * Header {{ item }}
  21868. * </header>
  21869. * <div class="body">
  21870. * Body {{ item }}
  21871. * </div>
  21872. * <footer ng-repeat-end>
  21873. * Footer {{ item }}
  21874. * </footer>
  21875. * ```
  21876. *
  21877. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  21878. * ```html
  21879. * <header>
  21880. * Header A
  21881. * </header>
  21882. * <div class="body">
  21883. * Body A
  21884. * </div>
  21885. * <footer>
  21886. * Footer A
  21887. * </footer>
  21888. * <header>
  21889. * Header B
  21890. * </header>
  21891. * <div class="body">
  21892. * Body B
  21893. * </div>
  21894. * <footer>
  21895. * Footer B
  21896. * </footer>
  21897. * ```
  21898. *
  21899. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  21900. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  21901. *
  21902. * @animations
  21903. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  21904. *
  21905. * **.leave** - when an item is removed from the list or when an item is filtered out
  21906. *
  21907. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  21908. *
  21909. * @element ANY
  21910. * @scope
  21911. * @priority 1000
  21912. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  21913. * formats are currently supported:
  21914. *
  21915. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  21916. * is a scope expression giving the collection to enumerate.
  21917. *
  21918. * For example: `album in artist.albums`.
  21919. *
  21920. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  21921. * and `expression` is the scope expression giving the collection to enumerate.
  21922. *
  21923. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  21924. *
  21925. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  21926. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  21927. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  21928. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  21929. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  21930. * before specifying a tracking expression.
  21931. *
  21932. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  21933. * will be associated by item identity in the array.
  21934. *
  21935. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  21936. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  21937. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  21938. * element in the same way in the DOM.
  21939. *
  21940. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  21941. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  21942. * property is same.
  21943. *
  21944. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  21945. * to items in conjunction with a tracking expression.
  21946. *
  21947. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  21948. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  21949. * when a filter is active on the repeater, but the filtered result set is empty.
  21950. *
  21951. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  21952. * the items have been processed through the filter.
  21953. *
  21954. * @example
  21955. * This example initializes the scope to a list of names and
  21956. * then uses `ngRepeat` to display every person:
  21957. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21958. <file name="index.html">
  21959. <div ng-init="friends = [
  21960. {name:'John', age:25, gender:'boy'},
  21961. {name:'Jessie', age:30, gender:'girl'},
  21962. {name:'Johanna', age:28, gender:'girl'},
  21963. {name:'Joy', age:15, gender:'girl'},
  21964. {name:'Mary', age:28, gender:'girl'},
  21965. {name:'Peter', age:95, gender:'boy'},
  21966. {name:'Sebastian', age:50, gender:'boy'},
  21967. {name:'Erika', age:27, gender:'girl'},
  21968. {name:'Patrick', age:40, gender:'boy'},
  21969. {name:'Samantha', age:60, gender:'girl'}
  21970. ]">
  21971. I have {{friends.length}} friends. They are:
  21972. <input type="search" ng-model="q" placeholder="filter friends..." />
  21973. <ul class="example-animate-container">
  21974. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  21975. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  21976. </li>
  21977. <li class="animate-repeat" ng-if="results.length == 0">
  21978. <strong>No results found...</strong>
  21979. </li>
  21980. </ul>
  21981. </div>
  21982. </file>
  21983. <file name="animations.css">
  21984. .example-animate-container {
  21985. background:white;
  21986. border:1px solid black;
  21987. list-style:none;
  21988. margin:0;
  21989. padding:0 10px;
  21990. }
  21991. .animate-repeat {
  21992. line-height:40px;
  21993. list-style:none;
  21994. box-sizing:border-box;
  21995. }
  21996. .animate-repeat.ng-move,
  21997. .animate-repeat.ng-enter,
  21998. .animate-repeat.ng-leave {
  21999. -webkit-transition:all linear 0.5s;
  22000. transition:all linear 0.5s;
  22001. }
  22002. .animate-repeat.ng-leave.ng-leave-active,
  22003. .animate-repeat.ng-move,
  22004. .animate-repeat.ng-enter {
  22005. opacity:0;
  22006. max-height:0;
  22007. }
  22008. .animate-repeat.ng-leave,
  22009. .animate-repeat.ng-move.ng-move-active,
  22010. .animate-repeat.ng-enter.ng-enter-active {
  22011. opacity:1;
  22012. max-height:40px;
  22013. }
  22014. </file>
  22015. <file name="protractor.js" type="protractor">
  22016. var friends = element.all(by.repeater('friend in friends'));
  22017. it('should render initial data set', function() {
  22018. expect(friends.count()).toBe(10);
  22019. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  22020. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  22021. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  22022. expect(element(by.binding('friends.length')).getText())
  22023. .toMatch("I have 10 friends. They are:");
  22024. });
  22025. it('should update repeater when filter predicate changes', function() {
  22026. expect(friends.count()).toBe(10);
  22027. element(by.model('q')).sendKeys('ma');
  22028. expect(friends.count()).toBe(2);
  22029. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  22030. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  22031. });
  22032. </file>
  22033. </example>
  22034. */
  22035. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  22036. var NG_REMOVED = '$$NG_REMOVED';
  22037. var ngRepeatMinErr = minErr('ngRepeat');
  22038. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  22039. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  22040. scope[valueIdentifier] = value;
  22041. if (keyIdentifier) scope[keyIdentifier] = key;
  22042. scope.$index = index;
  22043. scope.$first = (index === 0);
  22044. scope.$last = (index === (arrayLength - 1));
  22045. scope.$middle = !(scope.$first || scope.$last);
  22046. // jshint bitwise: false
  22047. scope.$odd = !(scope.$even = (index&1) === 0);
  22048. // jshint bitwise: true
  22049. };
  22050. var getBlockStart = function(block) {
  22051. return block.clone[0];
  22052. };
  22053. var getBlockEnd = function(block) {
  22054. return block.clone[block.clone.length - 1];
  22055. };
  22056. return {
  22057. restrict: 'A',
  22058. multiElement: true,
  22059. transclude: 'element',
  22060. priority: 1000,
  22061. terminal: true,
  22062. $$tlb: true,
  22063. compile: function ngRepeatCompile($element, $attr) {
  22064. var expression = $attr.ngRepeat;
  22065. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  22066. 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*$/);
  22067. if (!match) {
  22068. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  22069. expression);
  22070. }
  22071. var lhs = match[1];
  22072. var rhs = match[2];
  22073. var aliasAs = match[3];
  22074. var trackByExp = match[4];
  22075. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  22076. if (!match) {
  22077. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  22078. lhs);
  22079. }
  22080. var valueIdentifier = match[3] || match[1];
  22081. var keyIdentifier = match[2];
  22082. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  22083. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) {
  22084. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  22085. aliasAs);
  22086. }
  22087. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  22088. var hashFnLocals = {$id: hashKey};
  22089. if (trackByExp) {
  22090. trackByExpGetter = $parse(trackByExp);
  22091. } else {
  22092. trackByIdArrayFn = function(key, value) {
  22093. return hashKey(value);
  22094. };
  22095. trackByIdObjFn = function(key) {
  22096. return key;
  22097. };
  22098. }
  22099. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  22100. if (trackByExpGetter) {
  22101. trackByIdExpFn = function(key, value, index) {
  22102. // assign key, value, and $index to the locals so that they can be used in hash functions
  22103. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  22104. hashFnLocals[valueIdentifier] = value;
  22105. hashFnLocals.$index = index;
  22106. return trackByExpGetter($scope, hashFnLocals);
  22107. };
  22108. }
  22109. // Store a list of elements from previous run. This is a hash where key is the item from the
  22110. // iterator, and the value is objects with following properties.
  22111. // - scope: bound scope
  22112. // - element: previous element.
  22113. // - index: position
  22114. //
  22115. // We are using no-proto object so that we don't need to guard against inherited props via
  22116. // hasOwnProperty.
  22117. var lastBlockMap = createMap();
  22118. //watch props
  22119. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  22120. var index, length,
  22121. previousNode = $element[0], // node that cloned nodes should be inserted after
  22122. // initialized to the comment node anchor
  22123. nextNode,
  22124. // Same as lastBlockMap but it has the current state. It will become the
  22125. // lastBlockMap on the next iteration.
  22126. nextBlockMap = createMap(),
  22127. collectionLength,
  22128. key, value, // key/value of iteration
  22129. trackById,
  22130. trackByIdFn,
  22131. collectionKeys,
  22132. block, // last object information {scope, element, id}
  22133. nextBlockOrder,
  22134. elementsToRemove;
  22135. if (aliasAs) {
  22136. $scope[aliasAs] = collection;
  22137. }
  22138. if (isArrayLike(collection)) {
  22139. collectionKeys = collection;
  22140. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  22141. } else {
  22142. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  22143. // if object, extract keys, sort them and use to determine order of iteration over obj props
  22144. collectionKeys = [];
  22145. for (var itemKey in collection) {
  22146. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  22147. collectionKeys.push(itemKey);
  22148. }
  22149. }
  22150. collectionKeys.sort();
  22151. }
  22152. collectionLength = collectionKeys.length;
  22153. nextBlockOrder = new Array(collectionLength);
  22154. // locate existing items
  22155. for (index = 0; index < collectionLength; index++) {
  22156. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22157. value = collection[key];
  22158. trackById = trackByIdFn(key, value, index);
  22159. if (lastBlockMap[trackById]) {
  22160. // found previously seen block
  22161. block = lastBlockMap[trackById];
  22162. delete lastBlockMap[trackById];
  22163. nextBlockMap[trackById] = block;
  22164. nextBlockOrder[index] = block;
  22165. } else if (nextBlockMap[trackById]) {
  22166. // if collision detected. restore lastBlockMap and throw an error
  22167. forEach(nextBlockOrder, function(block) {
  22168. if (block && block.scope) lastBlockMap[block.id] = block;
  22169. });
  22170. throw ngRepeatMinErr('dupes',
  22171. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22172. expression, trackById, value);
  22173. } else {
  22174. // new never before seen block
  22175. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22176. nextBlockMap[trackById] = true;
  22177. }
  22178. }
  22179. // remove leftover items
  22180. for (var blockKey in lastBlockMap) {
  22181. block = lastBlockMap[blockKey];
  22182. elementsToRemove = getBlockNodes(block.clone);
  22183. $animate.leave(elementsToRemove);
  22184. if (elementsToRemove[0].parentNode) {
  22185. // if the element was not removed yet because of pending animation, mark it as deleted
  22186. // so that we can ignore it later
  22187. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22188. elementsToRemove[index][NG_REMOVED] = true;
  22189. }
  22190. }
  22191. block.scope.$destroy();
  22192. }
  22193. // we are not using forEach for perf reasons (trying to avoid #call)
  22194. for (index = 0; index < collectionLength; index++) {
  22195. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22196. value = collection[key];
  22197. block = nextBlockOrder[index];
  22198. if (block.scope) {
  22199. // if we have already seen this object, then we need to reuse the
  22200. // associated scope/element
  22201. nextNode = previousNode;
  22202. // skip nodes that are already pending removal via leave animation
  22203. do {
  22204. nextNode = nextNode.nextSibling;
  22205. } while (nextNode && nextNode[NG_REMOVED]);
  22206. if (getBlockStart(block) != nextNode) {
  22207. // existing item which got moved
  22208. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22209. }
  22210. previousNode = getBlockEnd(block);
  22211. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22212. } else {
  22213. // new item which we don't know about
  22214. $transclude(function ngRepeatTransclude(clone, scope) {
  22215. block.scope = scope;
  22216. // http://jsperf.com/clone-vs-createcomment
  22217. var endNode = ngRepeatEndComment.cloneNode(false);
  22218. clone[clone.length++] = endNode;
  22219. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22220. $animate.enter(clone, null, jqLite(previousNode));
  22221. previousNode = endNode;
  22222. // Note: We only need the first/last node of the cloned nodes.
  22223. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22224. // by a directive with templateUrl when its template arrives.
  22225. block.clone = clone;
  22226. nextBlockMap[block.id] = block;
  22227. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22228. });
  22229. }
  22230. }
  22231. lastBlockMap = nextBlockMap;
  22232. });
  22233. };
  22234. }
  22235. };
  22236. }];
  22237. var NG_HIDE_CLASS = 'ng-hide';
  22238. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22239. /**
  22240. * @ngdoc directive
  22241. * @name ngShow
  22242. *
  22243. * @description
  22244. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22245. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22246. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22247. * in AngularJS and sets the display style to none (using an !important flag).
  22248. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22249. *
  22250. * ```html
  22251. * <!-- when $scope.myValue is truthy (element is visible) -->
  22252. * <div ng-show="myValue"></div>
  22253. *
  22254. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22255. * <div ng-show="myValue" class="ng-hide"></div>
  22256. * ```
  22257. *
  22258. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22259. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22260. * from the element causing the element not to appear hidden.
  22261. *
  22262. * ## Why is !important used?
  22263. *
  22264. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22265. * can be easily overridden by heavier selectors. For example, something as simple
  22266. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22267. * This also becomes a bigger issue when dealing with CSS frameworks.
  22268. *
  22269. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22270. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22271. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22272. *
  22273. * ### Overriding `.ng-hide`
  22274. *
  22275. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22276. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22277. * class in CSS:
  22278. *
  22279. * ```css
  22280. * .ng-hide {
  22281. * /&#42; this is just another form of hiding an element &#42;/
  22282. * display: block!important;
  22283. * position: absolute;
  22284. * top: -9999px;
  22285. * left: -9999px;
  22286. * }
  22287. * ```
  22288. *
  22289. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22290. *
  22291. * ## A note about animations with `ngShow`
  22292. *
  22293. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22294. * is true and false. This system works like the animation system present with ngClass except that
  22295. * you must also include the !important flag to override the display property
  22296. * so that you can perform an animation when the element is hidden during the time of the animation.
  22297. *
  22298. * ```css
  22299. * //
  22300. * //a working example can be found at the bottom of this page
  22301. * //
  22302. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22303. * /&#42; this is required as of 1.3x to properly
  22304. * apply all styling in a show/hide animation &#42;/
  22305. * transition: 0s linear all;
  22306. * }
  22307. *
  22308. * .my-element.ng-hide-add-active,
  22309. * .my-element.ng-hide-remove-active {
  22310. * /&#42; the transition is defined in the active class &#42;/
  22311. * transition: 1s linear all;
  22312. * }
  22313. *
  22314. * .my-element.ng-hide-add { ... }
  22315. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22316. * .my-element.ng-hide-remove { ... }
  22317. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22318. * ```
  22319. *
  22320. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22321. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22322. *
  22323. * @animations
  22324. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22325. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22326. *
  22327. * @element ANY
  22328. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22329. * then the element is shown or hidden respectively.
  22330. *
  22331. * @example
  22332. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22333. <file name="index.html">
  22334. Click me: <input type="checkbox" ng-model="checked"><br/>
  22335. <div>
  22336. Show:
  22337. <div class="check-element animate-show" ng-show="checked">
  22338. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22339. </div>
  22340. </div>
  22341. <div>
  22342. Hide:
  22343. <div class="check-element animate-show" ng-hide="checked">
  22344. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22345. </div>
  22346. </div>
  22347. </file>
  22348. <file name="glyphicons.css">
  22349. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22350. </file>
  22351. <file name="animations.css">
  22352. .animate-show {
  22353. line-height: 20px;
  22354. opacity: 1;
  22355. padding: 10px;
  22356. border: 1px solid black;
  22357. background: white;
  22358. }
  22359. .animate-show.ng-hide-add.ng-hide-add-active,
  22360. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22361. -webkit-transition: all linear 0.5s;
  22362. transition: all linear 0.5s;
  22363. }
  22364. .animate-show.ng-hide {
  22365. line-height: 0;
  22366. opacity: 0;
  22367. padding: 0 10px;
  22368. }
  22369. .check-element {
  22370. padding: 10px;
  22371. border: 1px solid black;
  22372. background: white;
  22373. }
  22374. </file>
  22375. <file name="protractor.js" type="protractor">
  22376. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22377. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22378. it('should check ng-show / ng-hide', function() {
  22379. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22380. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22381. element(by.model('checked')).click();
  22382. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22383. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22384. });
  22385. </file>
  22386. </example>
  22387. */
  22388. var ngShowDirective = ['$animate', function($animate) {
  22389. return {
  22390. restrict: 'A',
  22391. multiElement: true,
  22392. link: function(scope, element, attr) {
  22393. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22394. // we're adding a temporary, animation-specific class for ng-hide since this way
  22395. // we can control when the element is actually displayed on screen without having
  22396. // to have a global/greedy CSS selector that breaks when other animations are run.
  22397. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22398. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22399. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22400. });
  22401. });
  22402. }
  22403. };
  22404. }];
  22405. /**
  22406. * @ngdoc directive
  22407. * @name ngHide
  22408. *
  22409. * @description
  22410. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22411. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22412. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22413. * in AngularJS and sets the display style to none (using an !important flag).
  22414. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22415. *
  22416. * ```html
  22417. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22418. * <div ng-hide="myValue" class="ng-hide"></div>
  22419. *
  22420. * <!-- when $scope.myValue is falsy (element is visible) -->
  22421. * <div ng-hide="myValue"></div>
  22422. * ```
  22423. *
  22424. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22425. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22426. * from the element causing the element not to appear hidden.
  22427. *
  22428. * ## Why is !important used?
  22429. *
  22430. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22431. * can be easily overridden by heavier selectors. For example, something as simple
  22432. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22433. * This also becomes a bigger issue when dealing with CSS frameworks.
  22434. *
  22435. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22436. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22437. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22438. *
  22439. * ### Overriding `.ng-hide`
  22440. *
  22441. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  22442. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22443. * class in CSS:
  22444. *
  22445. * ```css
  22446. * .ng-hide {
  22447. * /&#42; this is just another form of hiding an element &#42;/
  22448. * display: block!important;
  22449. * position: absolute;
  22450. * top: -9999px;
  22451. * left: -9999px;
  22452. * }
  22453. * ```
  22454. *
  22455. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22456. *
  22457. * ## A note about animations with `ngHide`
  22458. *
  22459. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22460. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22461. * CSS class is added and removed for you instead of your own CSS class.
  22462. *
  22463. * ```css
  22464. * //
  22465. * //a working example can be found at the bottom of this page
  22466. * //
  22467. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22468. * transition: 0.5s linear all;
  22469. * }
  22470. *
  22471. * .my-element.ng-hide-add { ... }
  22472. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22473. * .my-element.ng-hide-remove { ... }
  22474. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22475. * ```
  22476. *
  22477. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22478. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22479. *
  22480. * @animations
  22481. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22482. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22483. *
  22484. * @element ANY
  22485. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22486. * the element is shown or hidden respectively.
  22487. *
  22488. * @example
  22489. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22490. <file name="index.html">
  22491. Click me: <input type="checkbox" ng-model="checked"><br/>
  22492. <div>
  22493. Show:
  22494. <div class="check-element animate-hide" ng-show="checked">
  22495. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22496. </div>
  22497. </div>
  22498. <div>
  22499. Hide:
  22500. <div class="check-element animate-hide" ng-hide="checked">
  22501. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22502. </div>
  22503. </div>
  22504. </file>
  22505. <file name="glyphicons.css">
  22506. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22507. </file>
  22508. <file name="animations.css">
  22509. .animate-hide {
  22510. -webkit-transition: all linear 0.5s;
  22511. transition: all linear 0.5s;
  22512. line-height: 20px;
  22513. opacity: 1;
  22514. padding: 10px;
  22515. border: 1px solid black;
  22516. background: white;
  22517. }
  22518. .animate-hide.ng-hide {
  22519. line-height: 0;
  22520. opacity: 0;
  22521. padding: 0 10px;
  22522. }
  22523. .check-element {
  22524. padding: 10px;
  22525. border: 1px solid black;
  22526. background: white;
  22527. }
  22528. </file>
  22529. <file name="protractor.js" type="protractor">
  22530. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22531. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22532. it('should check ng-show / ng-hide', function() {
  22533. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22534. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22535. element(by.model('checked')).click();
  22536. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22537. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22538. });
  22539. </file>
  22540. </example>
  22541. */
  22542. var ngHideDirective = ['$animate', function($animate) {
  22543. return {
  22544. restrict: 'A',
  22545. multiElement: true,
  22546. link: function(scope, element, attr) {
  22547. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22548. // The comment inside of the ngShowDirective explains why we add and
  22549. // remove a temporary class for the show/hide animation
  22550. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22551. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22552. });
  22553. });
  22554. }
  22555. };
  22556. }];
  22557. /**
  22558. * @ngdoc directive
  22559. * @name ngStyle
  22560. * @restrict AC
  22561. *
  22562. * @description
  22563. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22564. *
  22565. * @element ANY
  22566. * @param {expression} ngStyle
  22567. *
  22568. * {@link guide/expression Expression} which evals to an
  22569. * object whose keys are CSS style names and values are corresponding values for those CSS
  22570. * keys.
  22571. *
  22572. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22573. * See the 'background-color' style in the example below.
  22574. *
  22575. * @example
  22576. <example>
  22577. <file name="index.html">
  22578. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22579. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22580. <input type="button" value="clear" ng-click="myStyle={}">
  22581. <br/>
  22582. <span ng-style="myStyle">Sample Text</span>
  22583. <pre>myStyle={{myStyle}}</pre>
  22584. </file>
  22585. <file name="style.css">
  22586. span {
  22587. color: black;
  22588. }
  22589. </file>
  22590. <file name="protractor.js" type="protractor">
  22591. var colorSpan = element(by.css('span'));
  22592. it('should check ng-style', function() {
  22593. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22594. element(by.css('input[value=\'set color\']')).click();
  22595. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22596. element(by.css('input[value=clear]')).click();
  22597. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22598. });
  22599. </file>
  22600. </example>
  22601. */
  22602. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22603. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22604. if (oldStyles && (newStyles !== oldStyles)) {
  22605. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22606. }
  22607. if (newStyles) element.css(newStyles);
  22608. }, true);
  22609. });
  22610. /**
  22611. * @ngdoc directive
  22612. * @name ngSwitch
  22613. * @restrict EA
  22614. *
  22615. * @description
  22616. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22617. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22618. * as specified in the template.
  22619. *
  22620. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22621. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22622. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22623. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22624. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22625. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22626. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22627. * attribute is displayed.
  22628. *
  22629. * <div class="alert alert-info">
  22630. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22631. * as literal string values to match against.
  22632. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22633. * value of the expression `$scope.someVal`.
  22634. * </div>
  22635. * @animations
  22636. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22637. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22638. *
  22639. * @usage
  22640. *
  22641. * ```
  22642. * <ANY ng-switch="expression">
  22643. * <ANY ng-switch-when="matchValue1">...</ANY>
  22644. * <ANY ng-switch-when="matchValue2">...</ANY>
  22645. * <ANY ng-switch-default>...</ANY>
  22646. * </ANY>
  22647. * ```
  22648. *
  22649. *
  22650. * @scope
  22651. * @priority 1200
  22652. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22653. * On child elements add:
  22654. *
  22655. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22656. * case will be displayed. If the same match appears multiple times, all the
  22657. * elements will be displayed.
  22658. * * `ngSwitchDefault`: the default case when no other case match. If there
  22659. * are multiple default cases, all of them will be displayed when no other
  22660. * case match.
  22661. *
  22662. *
  22663. * @example
  22664. <example module="switchExample" deps="angular-animate.js" animations="true">
  22665. <file name="index.html">
  22666. <div ng-controller="ExampleController">
  22667. <select ng-model="selection" ng-options="item for item in items">
  22668. </select>
  22669. <tt>selection={{selection}}</tt>
  22670. <hr/>
  22671. <div class="animate-switch-container"
  22672. ng-switch on="selection">
  22673. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22674. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22675. <div class="animate-switch" ng-switch-default>default</div>
  22676. </div>
  22677. </div>
  22678. </file>
  22679. <file name="script.js">
  22680. angular.module('switchExample', ['ngAnimate'])
  22681. .controller('ExampleController', ['$scope', function($scope) {
  22682. $scope.items = ['settings', 'home', 'other'];
  22683. $scope.selection = $scope.items[0];
  22684. }]);
  22685. </file>
  22686. <file name="animations.css">
  22687. .animate-switch-container {
  22688. position:relative;
  22689. background:white;
  22690. border:1px solid black;
  22691. height:40px;
  22692. overflow:hidden;
  22693. }
  22694. .animate-switch {
  22695. padding:10px;
  22696. }
  22697. .animate-switch.ng-animate {
  22698. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22699. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22700. position:absolute;
  22701. top:0;
  22702. left:0;
  22703. right:0;
  22704. bottom:0;
  22705. }
  22706. .animate-switch.ng-leave.ng-leave-active,
  22707. .animate-switch.ng-enter {
  22708. top:-50px;
  22709. }
  22710. .animate-switch.ng-leave,
  22711. .animate-switch.ng-enter.ng-enter-active {
  22712. top:0;
  22713. }
  22714. </file>
  22715. <file name="protractor.js" type="protractor">
  22716. var switchElem = element(by.css('[ng-switch]'));
  22717. var select = element(by.model('selection'));
  22718. it('should start in settings', function() {
  22719. expect(switchElem.getText()).toMatch(/Settings Div/);
  22720. });
  22721. it('should change to home', function() {
  22722. select.all(by.css('option')).get(1).click();
  22723. expect(switchElem.getText()).toMatch(/Home Span/);
  22724. });
  22725. it('should select default', function() {
  22726. select.all(by.css('option')).get(2).click();
  22727. expect(switchElem.getText()).toMatch(/default/);
  22728. });
  22729. </file>
  22730. </example>
  22731. */
  22732. var ngSwitchDirective = ['$animate', function($animate) {
  22733. return {
  22734. restrict: 'EA',
  22735. require: 'ngSwitch',
  22736. // asks for $scope to fool the BC controller module
  22737. controller: ['$scope', function ngSwitchController() {
  22738. this.cases = {};
  22739. }],
  22740. link: function(scope, element, attr, ngSwitchController) {
  22741. var watchExpr = attr.ngSwitch || attr.on,
  22742. selectedTranscludes = [],
  22743. selectedElements = [],
  22744. previousLeaveAnimations = [],
  22745. selectedScopes = [];
  22746. var spliceFactory = function(array, index) {
  22747. return function() { array.splice(index, 1); };
  22748. };
  22749. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  22750. var i, ii;
  22751. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  22752. $animate.cancel(previousLeaveAnimations[i]);
  22753. }
  22754. previousLeaveAnimations.length = 0;
  22755. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  22756. var selected = getBlockNodes(selectedElements[i].clone);
  22757. selectedScopes[i].$destroy();
  22758. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  22759. promise.then(spliceFactory(previousLeaveAnimations, i));
  22760. }
  22761. selectedElements.length = 0;
  22762. selectedScopes.length = 0;
  22763. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  22764. forEach(selectedTranscludes, function(selectedTransclude) {
  22765. selectedTransclude.transclude(function(caseElement, selectedScope) {
  22766. selectedScopes.push(selectedScope);
  22767. var anchor = selectedTransclude.element;
  22768. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  22769. var block = { clone: caseElement };
  22770. selectedElements.push(block);
  22771. $animate.enter(caseElement, anchor.parent(), anchor);
  22772. });
  22773. });
  22774. }
  22775. });
  22776. }
  22777. };
  22778. }];
  22779. var ngSwitchWhenDirective = ngDirective({
  22780. transclude: 'element',
  22781. priority: 1200,
  22782. require: '^ngSwitch',
  22783. multiElement: true,
  22784. link: function(scope, element, attrs, ctrl, $transclude) {
  22785. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  22786. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  22787. }
  22788. });
  22789. var ngSwitchDefaultDirective = ngDirective({
  22790. transclude: 'element',
  22791. priority: 1200,
  22792. require: '^ngSwitch',
  22793. multiElement: true,
  22794. link: function(scope, element, attr, ctrl, $transclude) {
  22795. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  22796. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  22797. }
  22798. });
  22799. /**
  22800. * @ngdoc directive
  22801. * @name ngTransclude
  22802. * @restrict EAC
  22803. *
  22804. * @description
  22805. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  22806. *
  22807. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  22808. *
  22809. * @element ANY
  22810. *
  22811. * @example
  22812. <example module="transcludeExample">
  22813. <file name="index.html">
  22814. <script>
  22815. angular.module('transcludeExample', [])
  22816. .directive('pane', function(){
  22817. return {
  22818. restrict: 'E',
  22819. transclude: true,
  22820. scope: { title:'@' },
  22821. template: '<div style="border: 1px solid black;">' +
  22822. '<div style="background-color: gray">{{title}}</div>' +
  22823. '<ng-transclude></ng-transclude>' +
  22824. '</div>'
  22825. };
  22826. })
  22827. .controller('ExampleController', ['$scope', function($scope) {
  22828. $scope.title = 'Lorem Ipsum';
  22829. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  22830. }]);
  22831. </script>
  22832. <div ng-controller="ExampleController">
  22833. <input ng-model="title"><br>
  22834. <textarea ng-model="text"></textarea> <br/>
  22835. <pane title="{{title}}">{{text}}</pane>
  22836. </div>
  22837. </file>
  22838. <file name="protractor.js" type="protractor">
  22839. it('should have transcluded', function() {
  22840. var titleElement = element(by.model('title'));
  22841. titleElement.clear();
  22842. titleElement.sendKeys('TITLE');
  22843. var textElement = element(by.model('text'));
  22844. textElement.clear();
  22845. textElement.sendKeys('TEXT');
  22846. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  22847. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  22848. });
  22849. </file>
  22850. </example>
  22851. *
  22852. */
  22853. var ngTranscludeDirective = ngDirective({
  22854. restrict: 'EAC',
  22855. link: function($scope, $element, $attrs, controller, $transclude) {
  22856. if (!$transclude) {
  22857. throw minErr('ngTransclude')('orphan',
  22858. 'Illegal use of ngTransclude directive in the template! ' +
  22859. 'No parent directive that requires a transclusion found. ' +
  22860. 'Element: {0}',
  22861. startingTag($element));
  22862. }
  22863. $transclude(function(clone) {
  22864. $element.empty();
  22865. $element.append(clone);
  22866. });
  22867. }
  22868. });
  22869. /**
  22870. * @ngdoc directive
  22871. * @name script
  22872. * @restrict E
  22873. *
  22874. * @description
  22875. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  22876. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  22877. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  22878. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  22879. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  22880. *
  22881. * @param {string} type Must be set to `'text/ng-template'`.
  22882. * @param {string} id Cache name of the template.
  22883. *
  22884. * @example
  22885. <example>
  22886. <file name="index.html">
  22887. <script type="text/ng-template" id="/tpl.html">
  22888. Content of the template.
  22889. </script>
  22890. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  22891. <div id="tpl-content" ng-include src="currentTpl"></div>
  22892. </file>
  22893. <file name="protractor.js" type="protractor">
  22894. it('should load template defined inside script tag', function() {
  22895. element(by.css('#tpl-link')).click();
  22896. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  22897. });
  22898. </file>
  22899. </example>
  22900. */
  22901. var scriptDirective = ['$templateCache', function($templateCache) {
  22902. return {
  22903. restrict: 'E',
  22904. terminal: true,
  22905. compile: function(element, attr) {
  22906. if (attr.type == 'text/ng-template') {
  22907. var templateUrl = attr.id,
  22908. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  22909. text = element[0].text;
  22910. $templateCache.put(templateUrl, text);
  22911. }
  22912. }
  22913. };
  22914. }];
  22915. var ngOptionsMinErr = minErr('ngOptions');
  22916. /**
  22917. * @ngdoc directive
  22918. * @name select
  22919. * @restrict E
  22920. *
  22921. * @description
  22922. * HTML `SELECT` element with angular data-binding.
  22923. *
  22924. * # `ngOptions`
  22925. *
  22926. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  22927. * elements for the `<select>` element using the array or object obtained by evaluating the
  22928. * `ngOptions` comprehension_expression.
  22929. *
  22930. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  22931. * similar result. However, the `ngOptions` provides some benefits such as reducing memory and
  22932. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  22933. * more flexibility in how the `select`'s model is assigned via `select as`. `ngOptions` should be
  22934. * used when the `select` model needs to be bound to a non-string value. This is because an option
  22935. * element can only be bound to string values at present.
  22936. *
  22937. * When an item in the `<select>` menu is selected, the array element or object property
  22938. * represented by the selected option will be bound to the model identified by the `ngModel`
  22939. * directive.
  22940. *
  22941. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  22942. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  22943. * option. See example below for demonstration.
  22944. *
  22945. * <div class="alert alert-warning">
  22946. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  22947. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  22948. * </div>
  22949. *
  22950. * ## `select as`
  22951. *
  22952. * Using `select as` will bind the result of the `select as` expression to the model, but
  22953. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  22954. * or property name (for object data sources) of the value within the collection. If a `track by` expression
  22955. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  22956. *
  22957. * ### `select as` with `trackexpr`
  22958. *
  22959. * Using `select as` together with `trackexpr` is not recommended. Reasoning:
  22960. *
  22961. * - Example: &lt;select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"&gt;
  22962. * values: [{id: 1, label: 'aLabel', subItem: {name: 'aSubItem'}}, {id: 2, label: 'bLabel', subItem: {name: 'bSubItem'}}],
  22963. * $scope.selected = {name: 'aSubItem'};
  22964. * - track by is always applied to `value`, with the purpose of preserving the selection,
  22965. * (to `item` in this case)
  22966. * - to calculate whether an item is selected we do the following:
  22967. * 1. apply `track by` to the values in the array, e.g.
  22968. * In the example: [1,2]
  22969. * 2. apply `track by` to the already selected value in `ngModel`:
  22970. * In the example: this is not possible, as `track by` refers to `item.id`, but the selected
  22971. * value from `ngModel` is `{name: aSubItem}`.
  22972. *
  22973. * @param {string} ngModel Assignable angular expression to data-bind to.
  22974. * @param {string=} name Property name of the form under which the control is published.
  22975. * @param {string=} required The control is considered valid only if value is entered.
  22976. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22977. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22978. * `required` when you want to data-bind to the `required` attribute.
  22979. * @param {comprehension_expression=} ngOptions in one of the following forms:
  22980. *
  22981. * * for array data sources:
  22982. * * `label` **`for`** `value` **`in`** `array`
  22983. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  22984. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  22985. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  22986. * * for object data sources:
  22987. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22988. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22989. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  22990. * * `select` **`as`** `label` **`group by`** `group`
  22991. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  22992. *
  22993. * Where:
  22994. *
  22995. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  22996. * * `value`: local variable which will refer to each item in the `array` or each property value
  22997. * of `object` during iteration.
  22998. * * `key`: local variable which will refer to a property name in `object` during iteration.
  22999. * * `label`: The result of this expression will be the label for `<option>` element. The
  23000. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23001. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23002. * element. If not specified, `select` expression will default to `value`.
  23003. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23004. * DOM element.
  23005. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23006. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23007. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23008. * even when the options are recreated (e.g. reloaded from the server).
  23009. *
  23010. * @example
  23011. <example module="selectExample">
  23012. <file name="index.html">
  23013. <script>
  23014. angular.module('selectExample', [])
  23015. .controller('ExampleController', ['$scope', function($scope) {
  23016. $scope.colors = [
  23017. {name:'black', shade:'dark'},
  23018. {name:'white', shade:'light'},
  23019. {name:'red', shade:'dark'},
  23020. {name:'blue', shade:'dark'},
  23021. {name:'yellow', shade:'light'}
  23022. ];
  23023. $scope.myColor = $scope.colors[2]; // red
  23024. }]);
  23025. </script>
  23026. <div ng-controller="ExampleController">
  23027. <ul>
  23028. <li ng-repeat="color in colors">
  23029. Name: <input ng-model="color.name">
  23030. [<a href ng-click="colors.splice($index, 1)">X</a>]
  23031. </li>
  23032. <li>
  23033. [<a href ng-click="colors.push({})">add</a>]
  23034. </li>
  23035. </ul>
  23036. <hr/>
  23037. Color (null not allowed):
  23038. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  23039. Color (null allowed):
  23040. <span class="nullable">
  23041. <select ng-model="myColor" ng-options="color.name for color in colors">
  23042. <option value="">-- choose color --</option>
  23043. </select>
  23044. </span><br/>
  23045. Color grouped by shade:
  23046. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23047. </select><br/>
  23048. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  23049. <hr/>
  23050. Currently selected: {{ {selected_color:myColor} }}
  23051. <div style="border:solid 1px black; height:20px"
  23052. ng-style="{'background-color':myColor.name}">
  23053. </div>
  23054. </div>
  23055. </file>
  23056. <file name="protractor.js" type="protractor">
  23057. it('should check ng-options', function() {
  23058. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23059. element.all(by.model('myColor')).first().click();
  23060. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23061. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23062. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23063. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23064. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23065. });
  23066. </file>
  23067. </example>
  23068. */
  23069. var ngOptionsDirective = valueFn({
  23070. restrict: 'A',
  23071. terminal: true
  23072. });
  23073. // jshint maxlen: false
  23074. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  23075. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  23076. 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]+?))?$/,
  23077. nullModelCtrl = {$setViewValue: noop};
  23078. // jshint maxlen: 100
  23079. return {
  23080. restrict: 'E',
  23081. require: ['select', '?ngModel'],
  23082. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  23083. var self = this,
  23084. optionsMap = {},
  23085. ngModelCtrl = nullModelCtrl,
  23086. nullOption,
  23087. unknownOption;
  23088. self.databound = $attrs.ngModel;
  23089. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  23090. ngModelCtrl = ngModelCtrl_;
  23091. nullOption = nullOption_;
  23092. unknownOption = unknownOption_;
  23093. };
  23094. self.addOption = function(value, element) {
  23095. assertNotHasOwnProperty(value, '"option value"');
  23096. optionsMap[value] = true;
  23097. if (ngModelCtrl.$viewValue == value) {
  23098. $element.val(value);
  23099. if (unknownOption.parent()) unknownOption.remove();
  23100. }
  23101. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  23102. // Adding an <option selected="selected"> element to a <select required="required"> should
  23103. // automatically select the new element
  23104. if (element && element[0].hasAttribute('selected')) {
  23105. element[0].selected = true;
  23106. }
  23107. };
  23108. self.removeOption = function(value) {
  23109. if (this.hasOption(value)) {
  23110. delete optionsMap[value];
  23111. if (ngModelCtrl.$viewValue == value) {
  23112. this.renderUnknownOption(value);
  23113. }
  23114. }
  23115. };
  23116. self.renderUnknownOption = function(val) {
  23117. var unknownVal = '? ' + hashKey(val) + ' ?';
  23118. unknownOption.val(unknownVal);
  23119. $element.prepend(unknownOption);
  23120. $element.val(unknownVal);
  23121. unknownOption.prop('selected', true); // needed for IE
  23122. };
  23123. self.hasOption = function(value) {
  23124. return optionsMap.hasOwnProperty(value);
  23125. };
  23126. $scope.$on('$destroy', function() {
  23127. // disable unknown option so that we don't do work when the whole select is being destroyed
  23128. self.renderUnknownOption = noop;
  23129. });
  23130. }],
  23131. link: function(scope, element, attr, ctrls) {
  23132. // if ngModel is not defined, we don't need to do anything
  23133. if (!ctrls[1]) return;
  23134. var selectCtrl = ctrls[0],
  23135. ngModelCtrl = ctrls[1],
  23136. multiple = attr.multiple,
  23137. optionsExp = attr.ngOptions,
  23138. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  23139. emptyOption,
  23140. renderScheduled = false,
  23141. // we can't just jqLite('<option>') since jqLite is not smart enough
  23142. // to create it in <select> and IE barfs otherwise.
  23143. optionTemplate = jqLite(document.createElement('option')),
  23144. optGroupTemplate =jqLite(document.createElement('optgroup')),
  23145. unknownOption = optionTemplate.clone();
  23146. // find "null" option
  23147. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  23148. if (children[i].value === '') {
  23149. emptyOption = nullOption = children.eq(i);
  23150. break;
  23151. }
  23152. }
  23153. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  23154. // required validator
  23155. if (multiple) {
  23156. ngModelCtrl.$isEmpty = function(value) {
  23157. return !value || value.length === 0;
  23158. };
  23159. }
  23160. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  23161. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  23162. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  23163. ////////////////////////////
  23164. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  23165. ngModelCtrl.$render = function() {
  23166. var viewValue = ngModelCtrl.$viewValue;
  23167. if (selectCtrl.hasOption(viewValue)) {
  23168. if (unknownOption.parent()) unknownOption.remove();
  23169. selectElement.val(viewValue);
  23170. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23171. } else {
  23172. if (isUndefined(viewValue) && emptyOption) {
  23173. selectElement.val('');
  23174. } else {
  23175. selectCtrl.renderUnknownOption(viewValue);
  23176. }
  23177. }
  23178. };
  23179. selectElement.on('change', function() {
  23180. scope.$apply(function() {
  23181. if (unknownOption.parent()) unknownOption.remove();
  23182. ngModelCtrl.$setViewValue(selectElement.val());
  23183. });
  23184. });
  23185. }
  23186. function setupAsMultiple(scope, selectElement, ctrl) {
  23187. var lastView;
  23188. ctrl.$render = function() {
  23189. var items = new HashMap(ctrl.$viewValue);
  23190. forEach(selectElement.find('option'), function(option) {
  23191. option.selected = isDefined(items.get(option.value));
  23192. });
  23193. };
  23194. // we have to do it on each watch since ngModel watches reference, but
  23195. // we need to work of an array, so we need to see if anything was inserted/removed
  23196. scope.$watch(function selectMultipleWatch() {
  23197. if (!equals(lastView, ctrl.$viewValue)) {
  23198. lastView = shallowCopy(ctrl.$viewValue);
  23199. ctrl.$render();
  23200. }
  23201. });
  23202. selectElement.on('change', function() {
  23203. scope.$apply(function() {
  23204. var array = [];
  23205. forEach(selectElement.find('option'), function(option) {
  23206. if (option.selected) {
  23207. array.push(option.value);
  23208. }
  23209. });
  23210. ctrl.$setViewValue(array);
  23211. });
  23212. });
  23213. }
  23214. function setupAsOptions(scope, selectElement, ctrl) {
  23215. var match;
  23216. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23217. throw ngOptionsMinErr('iexp',
  23218. "Expected expression in form of " +
  23219. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23220. " but got '{0}'. Element: {1}",
  23221. optionsExp, startingTag(selectElement));
  23222. }
  23223. var displayFn = $parse(match[2] || match[1]),
  23224. valueName = match[4] || match[6],
  23225. selectAs = / as /.test(match[0]) && match[1],
  23226. selectAsFn = selectAs ? $parse(selectAs) : null,
  23227. keyName = match[5],
  23228. groupByFn = $parse(match[3] || ''),
  23229. valueFn = $parse(match[2] ? match[1] : valueName),
  23230. valuesFn = $parse(match[7]),
  23231. track = match[8],
  23232. trackFn = track ? $parse(match[8]) : null,
  23233. trackKeysCache = {},
  23234. // This is an array of array of existing option groups in DOM.
  23235. // We try to reuse these if possible
  23236. // - optionGroupsCache[0] is the options with no option group
  23237. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23238. optionGroupsCache = [[{element: selectElement, label:''}]],
  23239. //re-usable object to represent option's locals
  23240. locals = {};
  23241. if (nullOption) {
  23242. // compile the element since there might be bindings in it
  23243. $compile(nullOption)(scope);
  23244. // remove the class, which is added automatically because we recompile the element and it
  23245. // becomes the compilation root
  23246. nullOption.removeClass('ng-scope');
  23247. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23248. // remove the label from the element. wtf?
  23249. nullOption.remove();
  23250. }
  23251. // clear contents, we'll add what's needed based on the model
  23252. selectElement.empty();
  23253. selectElement.on('change', selectionChanged);
  23254. ctrl.$render = render;
  23255. scope.$watchCollection(valuesFn, scheduleRendering);
  23256. scope.$watchCollection(getLabels, scheduleRendering);
  23257. if (multiple) {
  23258. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23259. }
  23260. // ------------------------------------------------------------------ //
  23261. function callExpression(exprFn, key, value) {
  23262. locals[valueName] = value;
  23263. if (keyName) locals[keyName] = key;
  23264. return exprFn(scope, locals);
  23265. }
  23266. function selectionChanged() {
  23267. scope.$apply(function() {
  23268. var collection = valuesFn(scope) || [];
  23269. var viewValue;
  23270. if (multiple) {
  23271. viewValue = [];
  23272. forEach(selectElement.val(), function(selectedKey) {
  23273. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23274. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23275. });
  23276. } else {
  23277. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23278. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23279. }
  23280. ctrl.$setViewValue(viewValue);
  23281. render();
  23282. });
  23283. }
  23284. function getViewValue(key, value) {
  23285. if (key === '?') {
  23286. return undefined;
  23287. } else if (key === '') {
  23288. return null;
  23289. } else {
  23290. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23291. return callExpression(viewValueFn, key, value);
  23292. }
  23293. }
  23294. function getLabels() {
  23295. var values = valuesFn(scope);
  23296. var toDisplay;
  23297. if (values && isArray(values)) {
  23298. toDisplay = new Array(values.length);
  23299. for (var i = 0, ii = values.length; i < ii; i++) {
  23300. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23301. }
  23302. return toDisplay;
  23303. } else if (values) {
  23304. // TODO: Add a test for this case
  23305. toDisplay = {};
  23306. for (var prop in values) {
  23307. if (values.hasOwnProperty(prop)) {
  23308. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23309. }
  23310. }
  23311. }
  23312. return toDisplay;
  23313. }
  23314. function createIsSelectedFn(viewValue) {
  23315. var selectedSet;
  23316. if (multiple) {
  23317. if (trackFn && isArray(viewValue)) {
  23318. selectedSet = new HashMap([]);
  23319. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23320. // tracking by key
  23321. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23322. }
  23323. } else {
  23324. selectedSet = new HashMap(viewValue);
  23325. }
  23326. } else if (trackFn) {
  23327. viewValue = callExpression(trackFn, null, viewValue);
  23328. }
  23329. return function isSelected(key, value) {
  23330. var compareValueFn;
  23331. if (trackFn) {
  23332. compareValueFn = trackFn;
  23333. } else if (selectAsFn) {
  23334. compareValueFn = selectAsFn;
  23335. } else {
  23336. compareValueFn = valueFn;
  23337. }
  23338. if (multiple) {
  23339. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23340. } else {
  23341. return viewValue === callExpression(compareValueFn, key, value);
  23342. }
  23343. };
  23344. }
  23345. function scheduleRendering() {
  23346. if (!renderScheduled) {
  23347. scope.$$postDigest(render);
  23348. renderScheduled = true;
  23349. }
  23350. }
  23351. /**
  23352. * A new labelMap is created with each render.
  23353. * This function is called for each existing option with added=false,
  23354. * and each new option with added=true.
  23355. * - Labels that are passed to this method twice,
  23356. * (once with added=true and once with added=false) will end up with a value of 0, and
  23357. * will cause no change to happen to the corresponding option.
  23358. * - Labels that are passed to this method only once with added=false will end up with a
  23359. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23360. * - Labels that are passed to this method only once with added=true will end up with a
  23361. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23362. */
  23363. function updateLabelMap(labelMap, label, added) {
  23364. labelMap[label] = labelMap[label] || 0;
  23365. labelMap[label] += (added ? 1 : -1);
  23366. }
  23367. function render() {
  23368. renderScheduled = false;
  23369. // Temporary location for the option groups before we render them
  23370. var optionGroups = {'':[]},
  23371. optionGroupNames = [''],
  23372. optionGroupName,
  23373. optionGroup,
  23374. option,
  23375. existingParent, existingOptions, existingOption,
  23376. viewValue = ctrl.$viewValue,
  23377. values = valuesFn(scope) || [],
  23378. keys = keyName ? sortedKeys(values) : values,
  23379. key,
  23380. value,
  23381. groupLength, length,
  23382. groupIndex, index,
  23383. labelMap = {},
  23384. selected,
  23385. isSelected = createIsSelectedFn(viewValue),
  23386. anySelected = false,
  23387. lastElement,
  23388. element,
  23389. label,
  23390. optionId;
  23391. trackKeysCache = {};
  23392. // We now build up the list of options we need (we merge later)
  23393. for (index = 0; length = keys.length, index < length; index++) {
  23394. key = index;
  23395. if (keyName) {
  23396. key = keys[index];
  23397. if (key.charAt(0) === '$') continue;
  23398. }
  23399. value = values[key];
  23400. optionGroupName = callExpression(groupByFn, key, value) || '';
  23401. if (!(optionGroup = optionGroups[optionGroupName])) {
  23402. optionGroup = optionGroups[optionGroupName] = [];
  23403. optionGroupNames.push(optionGroupName);
  23404. }
  23405. selected = isSelected(key, value);
  23406. anySelected = anySelected || selected;
  23407. label = callExpression(displayFn, key, value); // what will be seen by the user
  23408. // doing displayFn(scope, locals) || '' overwrites zero values
  23409. label = isDefined(label) ? label : '';
  23410. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23411. if (trackFn) {
  23412. trackKeysCache[optionId] = key;
  23413. }
  23414. optionGroup.push({
  23415. // either the index into array or key from object
  23416. id: optionId,
  23417. label: label,
  23418. selected: selected // determine if we should be selected
  23419. });
  23420. }
  23421. if (!multiple) {
  23422. if (nullOption || viewValue === null) {
  23423. // insert null option if we have a placeholder, or the model is null
  23424. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23425. } else if (!anySelected) {
  23426. // option could not be found, we have to insert the undefined item
  23427. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23428. }
  23429. }
  23430. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23431. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23432. groupIndex < groupLength;
  23433. groupIndex++) {
  23434. // current option group name or '' if no group
  23435. optionGroupName = optionGroupNames[groupIndex];
  23436. // list of options for that group. (first item has the parent)
  23437. optionGroup = optionGroups[optionGroupName];
  23438. if (optionGroupsCache.length <= groupIndex) {
  23439. // we need to grow the optionGroups
  23440. existingParent = {
  23441. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23442. label: optionGroup.label
  23443. };
  23444. existingOptions = [existingParent];
  23445. optionGroupsCache.push(existingOptions);
  23446. selectElement.append(existingParent.element);
  23447. } else {
  23448. existingOptions = optionGroupsCache[groupIndex];
  23449. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23450. // update the OPTGROUP label if not the same.
  23451. if (existingParent.label != optionGroupName) {
  23452. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23453. }
  23454. }
  23455. lastElement = null; // start at the beginning
  23456. for (index = 0, length = optionGroup.length; index < length; index++) {
  23457. option = optionGroup[index];
  23458. if ((existingOption = existingOptions[index + 1])) {
  23459. // reuse elements
  23460. lastElement = existingOption.element;
  23461. if (existingOption.label !== option.label) {
  23462. updateLabelMap(labelMap, existingOption.label, false);
  23463. updateLabelMap(labelMap, option.label, true);
  23464. lastElement.text(existingOption.label = option.label);
  23465. lastElement.prop('label', existingOption.label);
  23466. }
  23467. if (existingOption.id !== option.id) {
  23468. lastElement.val(existingOption.id = option.id);
  23469. }
  23470. // lastElement.prop('selected') provided by jQuery has side-effects
  23471. if (lastElement[0].selected !== option.selected) {
  23472. lastElement.prop('selected', (existingOption.selected = option.selected));
  23473. if (msie) {
  23474. // See #7692
  23475. // The selected item wouldn't visually update on IE without this.
  23476. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23477. lastElement.prop('selected', existingOption.selected);
  23478. }
  23479. }
  23480. } else {
  23481. // grow elements
  23482. // if it's a null option
  23483. if (option.id === '' && nullOption) {
  23484. // put back the pre-compiled element
  23485. element = nullOption;
  23486. } else {
  23487. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23488. // in this version of jQuery on some browser the .text() returns a string
  23489. // rather then the element.
  23490. (element = optionTemplate.clone())
  23491. .val(option.id)
  23492. .prop('selected', option.selected)
  23493. .attr('selected', option.selected)
  23494. .prop('label', option.label)
  23495. .text(option.label);
  23496. }
  23497. existingOptions.push(existingOption = {
  23498. element: element,
  23499. label: option.label,
  23500. id: option.id,
  23501. selected: option.selected
  23502. });
  23503. updateLabelMap(labelMap, option.label, true);
  23504. if (lastElement) {
  23505. lastElement.after(element);
  23506. } else {
  23507. existingParent.element.append(element);
  23508. }
  23509. lastElement = element;
  23510. }
  23511. }
  23512. // remove any excessive OPTIONs in a group
  23513. index++; // increment since the existingOptions[0] is parent element not OPTION
  23514. while (existingOptions.length > index) {
  23515. option = existingOptions.pop();
  23516. updateLabelMap(labelMap, option.label, false);
  23517. option.element.remove();
  23518. }
  23519. forEach(labelMap, function(count, label) {
  23520. if (count > 0) {
  23521. selectCtrl.addOption(label);
  23522. } else if (count < 0) {
  23523. selectCtrl.removeOption(label);
  23524. }
  23525. });
  23526. }
  23527. // remove any excessive OPTGROUPs from select
  23528. while (optionGroupsCache.length > groupIndex) {
  23529. optionGroupsCache.pop()[0].element.remove();
  23530. }
  23531. }
  23532. }
  23533. }
  23534. };
  23535. }];
  23536. var optionDirective = ['$interpolate', function($interpolate) {
  23537. var nullSelectCtrl = {
  23538. addOption: noop,
  23539. removeOption: noop
  23540. };
  23541. return {
  23542. restrict: 'E',
  23543. priority: 100,
  23544. compile: function(element, attr) {
  23545. if (isUndefined(attr.value)) {
  23546. var interpolateFn = $interpolate(element.text(), true);
  23547. if (!interpolateFn) {
  23548. attr.$set('value', element.text());
  23549. }
  23550. }
  23551. return function(scope, element, attr) {
  23552. var selectCtrlName = '$selectController',
  23553. parent = element.parent(),
  23554. selectCtrl = parent.data(selectCtrlName) ||
  23555. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23556. if (!selectCtrl || !selectCtrl.databound) {
  23557. selectCtrl = nullSelectCtrl;
  23558. }
  23559. if (interpolateFn) {
  23560. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23561. attr.$set('value', newVal);
  23562. if (oldVal !== newVal) {
  23563. selectCtrl.removeOption(oldVal);
  23564. }
  23565. selectCtrl.addOption(newVal, element);
  23566. });
  23567. } else {
  23568. selectCtrl.addOption(attr.value, element);
  23569. }
  23570. element.on('$destroy', function() {
  23571. selectCtrl.removeOption(attr.value);
  23572. });
  23573. };
  23574. }
  23575. };
  23576. }];
  23577. var styleDirective = valueFn({
  23578. restrict: 'E',
  23579. terminal: false
  23580. });
  23581. if (window.angular.bootstrap) {
  23582. //AngularJS is already loaded, so we can return here...
  23583. console.log('WARNING: Tried to load angular more than once.');
  23584. return;
  23585. }
  23586. //try to bind to jquery now so that one can write jqLite(document).ready()
  23587. //but we will rebind on bootstrap again.
  23588. bindJQuery();
  23589. publishExternalAPI(angular);
  23590. jqLite(document).ready(function() {
  23591. angularInit(document, bootstrap);
  23592. });
  23593. })(window, document);
  23594. !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');