angular.js 913 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722
  1. /**
  2. * @license AngularJS v1.3.2
  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. stringify = function(obj) {
  44. if (typeof obj === 'function') {
  45. return obj.toString().replace(/ \{[\s\S]*$/, '');
  46. } else if (typeof obj === 'undefined') {
  47. return 'undefined';
  48. } else if (typeof obj !== 'string') {
  49. return JSON.stringify(obj);
  50. }
  51. return obj;
  52. },
  53. message, i;
  54. message = prefix + template.replace(/\{\d+\}/g, function(match) {
  55. var index = +match.slice(1, -1), arg;
  56. if (index + 2 < templateArgs.length) {
  57. arg = templateArgs[index + 2];
  58. if (typeof arg === 'function') {
  59. return arg.toString().replace(/ ?\{[\s\S]*$/, '');
  60. } else if (typeof arg === 'undefined') {
  61. return 'undefined';
  62. } else if (typeof arg !== 'string') {
  63. return toJson(arg);
  64. }
  65. return arg;
  66. }
  67. return match;
  68. });
  69. message = message + '\nhttp://errors.angularjs.org/1.3.2/' +
  70. (module ? module + '/' : '') + code;
  71. for (i = 2; i < arguments.length; i++) {
  72. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  73. encodeURIComponent(stringify(arguments[i]));
  74. }
  75. return new ErrorConstructor(message);
  76. };
  77. }
  78. /* We need to tell jshint what variables are being exported */
  79. /* global angular: true,
  80. msie: true,
  81. jqLite: true,
  82. jQuery: true,
  83. slice: true,
  84. splice: true,
  85. push: true,
  86. toString: true,
  87. ngMinErr: true,
  88. angularModule: true,
  89. uid: true,
  90. REGEX_STRING_REGEXP: true,
  91. VALIDITY_STATE_PROPERTY: true,
  92. lowercase: true,
  93. uppercase: true,
  94. manualLowercase: true,
  95. manualUppercase: true,
  96. nodeName_: true,
  97. isArrayLike: true,
  98. forEach: true,
  99. sortedKeys: true,
  100. forEachSorted: true,
  101. reverseParams: true,
  102. nextUid: true,
  103. setHashKey: true,
  104. extend: true,
  105. int: true,
  106. inherit: true,
  107. noop: true,
  108. identity: true,
  109. valueFn: true,
  110. isUndefined: true,
  111. isDefined: true,
  112. isObject: true,
  113. isString: true,
  114. isNumber: true,
  115. isDate: true,
  116. isArray: true,
  117. isFunction: true,
  118. isRegExp: true,
  119. isWindow: true,
  120. isScope: true,
  121. isFile: true,
  122. isBlob: true,
  123. isBoolean: true,
  124. isPromiseLike: true,
  125. trim: true,
  126. escapeForRegexp: true,
  127. isElement: true,
  128. makeMap: true,
  129. includes: true,
  130. arrayRemove: true,
  131. copy: true,
  132. shallowCopy: true,
  133. equals: true,
  134. csp: true,
  135. concat: true,
  136. sliceArgs: true,
  137. bind: true,
  138. toJsonReplacer: true,
  139. toJson: true,
  140. fromJson: true,
  141. startingTag: true,
  142. tryDecodeURIComponent: true,
  143. parseKeyValue: true,
  144. toKeyValue: true,
  145. encodeUriSegment: true,
  146. encodeUriQuery: true,
  147. angularInit: true,
  148. bootstrap: true,
  149. getTestability: true,
  150. snake_case: true,
  151. bindJQuery: true,
  152. assertArg: true,
  153. assertArgFn: true,
  154. assertNotHasOwnProperty: true,
  155. getter: true,
  156. getBlockNodes: true,
  157. hasOwnProperty: true,
  158. createMap: true,
  159. NODE_TYPE_ELEMENT: true,
  160. NODE_TYPE_TEXT: true,
  161. NODE_TYPE_COMMENT: true,
  162. NODE_TYPE_DOCUMENT: true,
  163. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  164. */
  165. ////////////////////////////////////
  166. /**
  167. * @ngdoc module
  168. * @name ng
  169. * @module ng
  170. * @description
  171. *
  172. * # ng (core module)
  173. * The ng module is loaded by default when an AngularJS application is started. The module itself
  174. * contains the essential components for an AngularJS application to function. The table below
  175. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  176. * components available within this core module.
  177. *
  178. * <div doc-module-components="ng"></div>
  179. */
  180. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  181. // The name of a form control's ValidityState property.
  182. // This is used so that it's possible for internal tests to create mock ValidityStates.
  183. var VALIDITY_STATE_PROPERTY = 'validity';
  184. /**
  185. * @ngdoc function
  186. * @name angular.lowercase
  187. * @module ng
  188. * @kind function
  189. *
  190. * @description Converts the specified string to lowercase.
  191. * @param {string} string String to be converted to lowercase.
  192. * @returns {string} Lowercased string.
  193. */
  194. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  195. var hasOwnProperty = Object.prototype.hasOwnProperty;
  196. /**
  197. * @ngdoc function
  198. * @name angular.uppercase
  199. * @module ng
  200. * @kind function
  201. *
  202. * @description Converts the specified string to uppercase.
  203. * @param {string} string String to be converted to uppercase.
  204. * @returns {string} Uppercased string.
  205. */
  206. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  207. var manualLowercase = function(s) {
  208. /* jshint bitwise: false */
  209. return isString(s)
  210. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  211. : s;
  212. };
  213. var manualUppercase = function(s) {
  214. /* jshint bitwise: false */
  215. return isString(s)
  216. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  217. : s;
  218. };
  219. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  220. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  221. // with correct but slower alternatives.
  222. if ('i' !== 'I'.toLowerCase()) {
  223. lowercase = manualLowercase;
  224. uppercase = manualUppercase;
  225. }
  226. var /** holds major version number for IE or NaN for real browsers */
  227. msie,
  228. jqLite, // delay binding since jQuery could be loaded after us.
  229. jQuery, // delay binding
  230. slice = [].slice,
  231. splice = [].splice,
  232. push = [].push,
  233. toString = Object.prototype.toString,
  234. ngMinErr = minErr('ng'),
  235. /** @name angular */
  236. angular = window.angular || (window.angular = {}),
  237. angularModule,
  238. uid = 0;
  239. /**
  240. * documentMode is an IE-only property
  241. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  242. */
  243. msie = document.documentMode;
  244. /**
  245. * @private
  246. * @param {*} obj
  247. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  248. * String ...)
  249. */
  250. function isArrayLike(obj) {
  251. if (obj == null || isWindow(obj)) {
  252. return false;
  253. }
  254. var length = obj.length;
  255. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  256. return true;
  257. }
  258. return isString(obj) || isArray(obj) || length === 0 ||
  259. typeof length === 'number' && length > 0 && (length - 1) in obj;
  260. }
  261. /**
  262. * @ngdoc function
  263. * @name angular.forEach
  264. * @module ng
  265. * @kind function
  266. *
  267. * @description
  268. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  269. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  270. * is the value of an object property or an array element, `key` is the object property key or
  271. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  272. *
  273. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  274. * using the `hasOwnProperty` method.
  275. *
  276. * Unlike ES262's
  277. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  278. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  279. * return the value provided.
  280. *
  281. ```js
  282. var values = {name: 'misko', gender: 'male'};
  283. var log = [];
  284. angular.forEach(values, function(value, key) {
  285. this.push(key + ': ' + value);
  286. }, log);
  287. expect(log).toEqual(['name: misko', 'gender: male']);
  288. ```
  289. *
  290. * @param {Object|Array} obj Object to iterate over.
  291. * @param {Function} iterator Iterator function.
  292. * @param {Object=} context Object to become context (`this`) for the iterator function.
  293. * @returns {Object|Array} Reference to `obj`.
  294. */
  295. function forEach(obj, iterator, context) {
  296. var key, length;
  297. if (obj) {
  298. if (isFunction(obj)) {
  299. for (key in obj) {
  300. // Need to check if hasOwnProperty exists,
  301. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  302. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else if (isArray(obj) || isArrayLike(obj)) {
  307. var isPrimitive = typeof obj !== 'object';
  308. for (key = 0, length = obj.length; key < length; key++) {
  309. if (isPrimitive || key in obj) {
  310. iterator.call(context, obj[key], key, obj);
  311. }
  312. }
  313. } else if (obj.forEach && obj.forEach !== forEach) {
  314. obj.forEach(iterator, context, obj);
  315. } else {
  316. for (key in obj) {
  317. if (obj.hasOwnProperty(key)) {
  318. iterator.call(context, obj[key], key, obj);
  319. }
  320. }
  321. }
  322. }
  323. return obj;
  324. }
  325. function sortedKeys(obj) {
  326. return Object.keys(obj).sort();
  327. }
  328. function forEachSorted(obj, iterator, context) {
  329. var keys = sortedKeys(obj);
  330. for (var i = 0; i < keys.length; i++) {
  331. iterator.call(context, obj[keys[i]], keys[i]);
  332. }
  333. return keys;
  334. }
  335. /**
  336. * when using forEach the params are value, key, but it is often useful to have key, value.
  337. * @param {function(string, *)} iteratorFn
  338. * @returns {function(*, string)}
  339. */
  340. function reverseParams(iteratorFn) {
  341. return function(value, key) { iteratorFn(key, value); };
  342. }
  343. /**
  344. * A consistent way of creating unique IDs in angular.
  345. *
  346. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  347. * we hit number precision issues in JavaScript.
  348. *
  349. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  350. *
  351. * @returns {number} an unique alpha-numeric string
  352. */
  353. function nextUid() {
  354. return ++uid;
  355. }
  356. /**
  357. * Set or clear the hashkey for an object.
  358. * @param obj object
  359. * @param h the hashkey (!truthy to delete the hashkey)
  360. */
  361. function setHashKey(obj, h) {
  362. if (h) {
  363. obj.$$hashKey = h;
  364. }
  365. else {
  366. delete obj.$$hashKey;
  367. }
  368. }
  369. /**
  370. * @ngdoc function
  371. * @name angular.extend
  372. * @module ng
  373. * @kind function
  374. *
  375. * @description
  376. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  377. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  378. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  379. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
  380. *
  381. * @param {Object} dst Destination object.
  382. * @param {...Object} src Source object(s).
  383. * @returns {Object} Reference to `dst`.
  384. */
  385. function extend(dst) {
  386. var h = dst.$$hashKey;
  387. for (var i = 1, ii = arguments.length; i < ii; i++) {
  388. var obj = arguments[i];
  389. if (obj) {
  390. var keys = Object.keys(obj);
  391. for (var j = 0, jj = keys.length; j < jj; j++) {
  392. var key = keys[j];
  393. dst[key] = obj[key];
  394. }
  395. }
  396. }
  397. setHashKey(dst, h);
  398. return dst;
  399. }
  400. function int(str) {
  401. return parseInt(str, 10);
  402. }
  403. function inherit(parent, extra) {
  404. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  405. }
  406. /**
  407. * @ngdoc function
  408. * @name angular.noop
  409. * @module ng
  410. * @kind function
  411. *
  412. * @description
  413. * A function that performs no operations. This function can be useful when writing code in the
  414. * functional style.
  415. ```js
  416. function foo(callback) {
  417. var result = calculateResult();
  418. (callback || angular.noop)(result);
  419. }
  420. ```
  421. */
  422. function noop() {}
  423. noop.$inject = [];
  424. /**
  425. * @ngdoc function
  426. * @name angular.identity
  427. * @module ng
  428. * @kind function
  429. *
  430. * @description
  431. * A function that returns its first argument. This function is useful when writing code in the
  432. * functional style.
  433. *
  434. ```js
  435. function transformer(transformationFn, value) {
  436. return (transformationFn || angular.identity)(value);
  437. };
  438. ```
  439. */
  440. function identity($) {return $;}
  441. identity.$inject = [];
  442. function valueFn(value) {return function() {return value;};}
  443. /**
  444. * @ngdoc function
  445. * @name angular.isUndefined
  446. * @module ng
  447. * @kind function
  448. *
  449. * @description
  450. * Determines if a reference is undefined.
  451. *
  452. * @param {*} value Reference to check.
  453. * @returns {boolean} True if `value` is undefined.
  454. */
  455. function isUndefined(value) {return typeof value === 'undefined';}
  456. /**
  457. * @ngdoc function
  458. * @name angular.isDefined
  459. * @module ng
  460. * @kind function
  461. *
  462. * @description
  463. * Determines if a reference is defined.
  464. *
  465. * @param {*} value Reference to check.
  466. * @returns {boolean} True if `value` is defined.
  467. */
  468. function isDefined(value) {return typeof value !== 'undefined';}
  469. /**
  470. * @ngdoc function
  471. * @name angular.isObject
  472. * @module ng
  473. * @kind function
  474. *
  475. * @description
  476. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  477. * considered to be objects. Note that JavaScript arrays are objects.
  478. *
  479. * @param {*} value Reference to check.
  480. * @returns {boolean} True if `value` is an `Object` but not `null`.
  481. */
  482. function isObject(value) {
  483. // http://jsperf.com/isobject4
  484. return value !== null && typeof value === 'object';
  485. }
  486. /**
  487. * @ngdoc function
  488. * @name angular.isString
  489. * @module ng
  490. * @kind function
  491. *
  492. * @description
  493. * Determines if a reference is a `String`.
  494. *
  495. * @param {*} value Reference to check.
  496. * @returns {boolean} True if `value` is a `String`.
  497. */
  498. function isString(value) {return typeof value === 'string';}
  499. /**
  500. * @ngdoc function
  501. * @name angular.isNumber
  502. * @module ng
  503. * @kind function
  504. *
  505. * @description
  506. * Determines if a reference is a `Number`.
  507. *
  508. * @param {*} value Reference to check.
  509. * @returns {boolean} True if `value` is a `Number`.
  510. */
  511. function isNumber(value) {return typeof value === 'number';}
  512. /**
  513. * @ngdoc function
  514. * @name angular.isDate
  515. * @module ng
  516. * @kind function
  517. *
  518. * @description
  519. * Determines if a value is a date.
  520. *
  521. * @param {*} value Reference to check.
  522. * @returns {boolean} True if `value` is a `Date`.
  523. */
  524. function isDate(value) {
  525. return toString.call(value) === '[object Date]';
  526. }
  527. /**
  528. * @ngdoc function
  529. * @name angular.isArray
  530. * @module ng
  531. * @kind function
  532. *
  533. * @description
  534. * Determines if a reference is an `Array`.
  535. *
  536. * @param {*} value Reference to check.
  537. * @returns {boolean} True if `value` is an `Array`.
  538. */
  539. var isArray = Array.isArray;
  540. /**
  541. * @ngdoc function
  542. * @name angular.isFunction
  543. * @module ng
  544. * @kind function
  545. *
  546. * @description
  547. * Determines if a reference is a `Function`.
  548. *
  549. * @param {*} value Reference to check.
  550. * @returns {boolean} True if `value` is a `Function`.
  551. */
  552. function isFunction(value) {return typeof value === 'function';}
  553. /**
  554. * Determines if a value is a regular expression object.
  555. *
  556. * @private
  557. * @param {*} value Reference to check.
  558. * @returns {boolean} True if `value` is a `RegExp`.
  559. */
  560. function isRegExp(value) {
  561. return toString.call(value) === '[object RegExp]';
  562. }
  563. /**
  564. * Checks if `obj` is a window object.
  565. *
  566. * @private
  567. * @param {*} obj Object to check
  568. * @returns {boolean} True if `obj` is a window obj.
  569. */
  570. function isWindow(obj) {
  571. return obj && obj.window === obj;
  572. }
  573. function isScope(obj) {
  574. return obj && obj.$evalAsync && obj.$watch;
  575. }
  576. function isFile(obj) {
  577. return toString.call(obj) === '[object File]';
  578. }
  579. function isBlob(obj) {
  580. return toString.call(obj) === '[object Blob]';
  581. }
  582. function isBoolean(value) {
  583. return typeof value === 'boolean';
  584. }
  585. function isPromiseLike(obj) {
  586. return obj && isFunction(obj.then);
  587. }
  588. var trim = function(value) {
  589. return isString(value) ? value.trim() : value;
  590. };
  591. // Copied from:
  592. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  593. // Prereq: s is a string.
  594. var escapeForRegexp = function(s) {
  595. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  596. replace(/\x08/g, '\\x08');
  597. };
  598. /**
  599. * @ngdoc function
  600. * @name angular.isElement
  601. * @module ng
  602. * @kind function
  603. *
  604. * @description
  605. * Determines if a reference is a DOM element (or wrapped jQuery element).
  606. *
  607. * @param {*} value Reference to check.
  608. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  609. */
  610. function isElement(node) {
  611. return !!(node &&
  612. (node.nodeName // we are a direct element
  613. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  614. }
  615. /**
  616. * @param str 'key1,key2,...'
  617. * @returns {object} in the form of {key1:true, key2:true, ...}
  618. */
  619. function makeMap(str) {
  620. var obj = {}, items = str.split(","), i;
  621. for (i = 0; i < items.length; i++)
  622. obj[ items[i] ] = true;
  623. return obj;
  624. }
  625. function nodeName_(element) {
  626. return lowercase(element.nodeName || element[0].nodeName);
  627. }
  628. function includes(array, obj) {
  629. return Array.prototype.indexOf.call(array, obj) != -1;
  630. }
  631. function arrayRemove(array, value) {
  632. var index = array.indexOf(value);
  633. if (index >=0)
  634. array.splice(index, 1);
  635. return value;
  636. }
  637. /**
  638. * @ngdoc function
  639. * @name angular.copy
  640. * @module ng
  641. * @kind function
  642. *
  643. * @description
  644. * Creates a deep copy of `source`, which should be an object or an array.
  645. *
  646. * * If no destination is supplied, a copy of the object or array is created.
  647. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  648. * are deleted and then all elements/properties from the source are copied to it.
  649. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  650. * * If `source` is identical to 'destination' an exception will be thrown.
  651. *
  652. * @param {*} source The source that will be used to make a copy.
  653. * Can be any type, including primitives, `null`, and `undefined`.
  654. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  655. * provided, must be of the same type as `source`.
  656. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  657. *
  658. * @example
  659. <example module="copyExample">
  660. <file name="index.html">
  661. <div ng-controller="ExampleController">
  662. <form novalidate class="simple-form">
  663. Name: <input type="text" ng-model="user.name" /><br />
  664. E-mail: <input type="email" ng-model="user.email" /><br />
  665. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  666. <input type="radio" ng-model="user.gender" value="female" />female<br />
  667. <button ng-click="reset()">RESET</button>
  668. <button ng-click="update(user)">SAVE</button>
  669. </form>
  670. <pre>form = {{user | json}}</pre>
  671. <pre>master = {{master | json}}</pre>
  672. </div>
  673. <script>
  674. angular.module('copyExample', [])
  675. .controller('ExampleController', ['$scope', function($scope) {
  676. $scope.master= {};
  677. $scope.update = function(user) {
  678. // Example with 1 argument
  679. $scope.master= angular.copy(user);
  680. };
  681. $scope.reset = function() {
  682. // Example with 2 arguments
  683. angular.copy($scope.master, $scope.user);
  684. };
  685. $scope.reset();
  686. }]);
  687. </script>
  688. </file>
  689. </example>
  690. */
  691. function copy(source, destination, stackSource, stackDest) {
  692. if (isWindow(source) || isScope(source)) {
  693. throw ngMinErr('cpws',
  694. "Can't copy! Making copies of Window or Scope instances is not supported.");
  695. }
  696. if (!destination) {
  697. destination = source;
  698. if (source) {
  699. if (isArray(source)) {
  700. destination = copy(source, [], stackSource, stackDest);
  701. } else if (isDate(source)) {
  702. destination = new Date(source.getTime());
  703. } else if (isRegExp(source)) {
  704. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  705. destination.lastIndex = source.lastIndex;
  706. } else if (isObject(source)) {
  707. var emptyObject = Object.create(Object.getPrototypeOf(source));
  708. destination = copy(source, emptyObject, stackSource, stackDest);
  709. }
  710. }
  711. } else {
  712. if (source === destination) throw ngMinErr('cpi',
  713. "Can't copy! Source and destination are identical.");
  714. stackSource = stackSource || [];
  715. stackDest = stackDest || [];
  716. if (isObject(source)) {
  717. var index = stackSource.indexOf(source);
  718. if (index !== -1) return stackDest[index];
  719. stackSource.push(source);
  720. stackDest.push(destination);
  721. }
  722. var result;
  723. if (isArray(source)) {
  724. destination.length = 0;
  725. for (var i = 0; i < source.length; i++) {
  726. result = copy(source[i], null, stackSource, stackDest);
  727. if (isObject(source[i])) {
  728. stackSource.push(source[i]);
  729. stackDest.push(result);
  730. }
  731. destination.push(result);
  732. }
  733. } else {
  734. var h = destination.$$hashKey;
  735. if (isArray(destination)) {
  736. destination.length = 0;
  737. } else {
  738. forEach(destination, function(value, key) {
  739. delete destination[key];
  740. });
  741. }
  742. for (var key in source) {
  743. if (source.hasOwnProperty(key)) {
  744. result = copy(source[key], null, stackSource, stackDest);
  745. if (isObject(source[key])) {
  746. stackSource.push(source[key]);
  747. stackDest.push(result);
  748. }
  749. destination[key] = result;
  750. }
  751. }
  752. setHashKey(destination,h);
  753. }
  754. }
  755. return destination;
  756. }
  757. /**
  758. * Creates a shallow copy of an object, an array or a primitive.
  759. *
  760. * Assumes that there are no proto properties for objects.
  761. */
  762. function shallowCopy(src, dst) {
  763. if (isArray(src)) {
  764. dst = dst || [];
  765. for (var i = 0, ii = src.length; i < ii; i++) {
  766. dst[i] = src[i];
  767. }
  768. } else if (isObject(src)) {
  769. dst = dst || {};
  770. for (var key in src) {
  771. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  772. dst[key] = src[key];
  773. }
  774. }
  775. }
  776. return dst || src;
  777. }
  778. /**
  779. * @ngdoc function
  780. * @name angular.equals
  781. * @module ng
  782. * @kind function
  783. *
  784. * @description
  785. * Determines if two objects or two values are equivalent. Supports value types, regular
  786. * expressions, arrays and objects.
  787. *
  788. * Two objects or values are considered equivalent if at least one of the following is true:
  789. *
  790. * * Both objects or values pass `===` comparison.
  791. * * Both objects or values are of the same type and all of their properties are equal by
  792. * comparing them with `angular.equals`.
  793. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  794. * * Both values represent the same regular expression (In JavaScript,
  795. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  796. * representation matches).
  797. *
  798. * During a property comparison, properties of `function` type and properties with names
  799. * that begin with `$` are ignored.
  800. *
  801. * Scope and DOMWindow objects are being compared only by identify (`===`).
  802. *
  803. * @param {*} o1 Object or value to compare.
  804. * @param {*} o2 Object or value to compare.
  805. * @returns {boolean} True if arguments are equal.
  806. */
  807. function equals(o1, o2) {
  808. if (o1 === o2) return true;
  809. if (o1 === null || o2 === null) return false;
  810. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  811. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  812. if (t1 == t2) {
  813. if (t1 == 'object') {
  814. if (isArray(o1)) {
  815. if (!isArray(o2)) return false;
  816. if ((length = o1.length) == o2.length) {
  817. for (key=0; key<length; key++) {
  818. if (!equals(o1[key], o2[key])) return false;
  819. }
  820. return true;
  821. }
  822. } else if (isDate(o1)) {
  823. if (!isDate(o2)) return false;
  824. return equals(o1.getTime(), o2.getTime());
  825. } else if (isRegExp(o1) && isRegExp(o2)) {
  826. return o1.toString() == o2.toString();
  827. } else {
  828. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  829. keySet = {};
  830. for (key in o1) {
  831. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  832. if (!equals(o1[key], o2[key])) return false;
  833. keySet[key] = true;
  834. }
  835. for (key in o2) {
  836. if (!keySet.hasOwnProperty(key) &&
  837. key.charAt(0) !== '$' &&
  838. o2[key] !== undefined &&
  839. !isFunction(o2[key])) return false;
  840. }
  841. return true;
  842. }
  843. }
  844. }
  845. return false;
  846. }
  847. var csp = function() {
  848. if (isDefined(csp.isActive_)) return csp.isActive_;
  849. var active = !!(document.querySelector('[ng-csp]') ||
  850. document.querySelector('[data-ng-csp]'));
  851. if (!active) {
  852. try {
  853. /* jshint -W031, -W054 */
  854. new Function('');
  855. /* jshint +W031, +W054 */
  856. } catch (e) {
  857. active = true;
  858. }
  859. }
  860. return (csp.isActive_ = active);
  861. };
  862. function concat(array1, array2, index) {
  863. return array1.concat(slice.call(array2, index));
  864. }
  865. function sliceArgs(args, startIndex) {
  866. return slice.call(args, startIndex || 0);
  867. }
  868. /* jshint -W101 */
  869. /**
  870. * @ngdoc function
  871. * @name angular.bind
  872. * @module ng
  873. * @kind function
  874. *
  875. * @description
  876. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  877. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  878. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  879. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  880. *
  881. * @param {Object} self Context which `fn` should be evaluated in.
  882. * @param {function()} fn Function to be bound.
  883. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  884. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  885. */
  886. /* jshint +W101 */
  887. function bind(self, fn) {
  888. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  889. if (isFunction(fn) && !(fn instanceof RegExp)) {
  890. return curryArgs.length
  891. ? function() {
  892. return arguments.length
  893. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  894. : fn.apply(self, curryArgs);
  895. }
  896. : function() {
  897. return arguments.length
  898. ? fn.apply(self, arguments)
  899. : fn.call(self);
  900. };
  901. } else {
  902. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  903. return fn;
  904. }
  905. }
  906. function toJsonReplacer(key, value) {
  907. var val = value;
  908. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  909. val = undefined;
  910. } else if (isWindow(value)) {
  911. val = '$WINDOW';
  912. } else if (value && document === value) {
  913. val = '$DOCUMENT';
  914. } else if (isScope(value)) {
  915. val = '$SCOPE';
  916. }
  917. return val;
  918. }
  919. /**
  920. * @ngdoc function
  921. * @name angular.toJson
  922. * @module ng
  923. * @kind function
  924. *
  925. * @description
  926. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  927. * stripped since angular uses this notation internally.
  928. *
  929. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  930. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  931. * @returns {string|undefined} JSON-ified string representing `obj`.
  932. */
  933. function toJson(obj, pretty) {
  934. if (typeof obj === 'undefined') return undefined;
  935. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  936. }
  937. /**
  938. * @ngdoc function
  939. * @name angular.fromJson
  940. * @module ng
  941. * @kind function
  942. *
  943. * @description
  944. * Deserializes a JSON string.
  945. *
  946. * @param {string} json JSON string to deserialize.
  947. * @returns {Object|Array|string|number} Deserialized thingy.
  948. */
  949. function fromJson(json) {
  950. return isString(json)
  951. ? JSON.parse(json)
  952. : json;
  953. }
  954. /**
  955. * @returns {string} Returns the string representation of the element.
  956. */
  957. function startingTag(element) {
  958. element = jqLite(element).clone();
  959. try {
  960. // turns out IE does not let you set .html() on elements which
  961. // are not allowed to have children. So we just ignore it.
  962. element.empty();
  963. } catch (e) {}
  964. var elemHtml = jqLite('<div>').append(element).html();
  965. try {
  966. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  967. elemHtml.
  968. match(/^(<[^>]+>)/)[1].
  969. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  970. } catch (e) {
  971. return lowercase(elemHtml);
  972. }
  973. }
  974. /////////////////////////////////////////////////
  975. /**
  976. * Tries to decode the URI component without throwing an exception.
  977. *
  978. * @private
  979. * @param str value potential URI component to check.
  980. * @returns {boolean} True if `value` can be decoded
  981. * with the decodeURIComponent function.
  982. */
  983. function tryDecodeURIComponent(value) {
  984. try {
  985. return decodeURIComponent(value);
  986. } catch (e) {
  987. // Ignore any invalid uri component
  988. }
  989. }
  990. /**
  991. * Parses an escaped url query string into key-value pairs.
  992. * @returns {Object.<string,boolean|Array>}
  993. */
  994. function parseKeyValue(/**string*/keyValue) {
  995. var obj = {}, key_value, key;
  996. forEach((keyValue || "").split('&'), function(keyValue) {
  997. if (keyValue) {
  998. key_value = keyValue.replace(/\+/g,'%20').split('=');
  999. key = tryDecodeURIComponent(key_value[0]);
  1000. if (isDefined(key)) {
  1001. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1002. if (!hasOwnProperty.call(obj, key)) {
  1003. obj[key] = val;
  1004. } else if (isArray(obj[key])) {
  1005. obj[key].push(val);
  1006. } else {
  1007. obj[key] = [obj[key],val];
  1008. }
  1009. }
  1010. }
  1011. });
  1012. return obj;
  1013. }
  1014. function toKeyValue(obj) {
  1015. var parts = [];
  1016. forEach(obj, function(value, key) {
  1017. if (isArray(value)) {
  1018. forEach(value, function(arrayValue) {
  1019. parts.push(encodeUriQuery(key, true) +
  1020. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1021. });
  1022. } else {
  1023. parts.push(encodeUriQuery(key, true) +
  1024. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1025. }
  1026. });
  1027. return parts.length ? parts.join('&') : '';
  1028. }
  1029. /**
  1030. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1031. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1032. * segments:
  1033. * segment = *pchar
  1034. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1035. * pct-encoded = "%" HEXDIG HEXDIG
  1036. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1037. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1038. * / "*" / "+" / "," / ";" / "="
  1039. */
  1040. function encodeUriSegment(val) {
  1041. return encodeUriQuery(val, true).
  1042. replace(/%26/gi, '&').
  1043. replace(/%3D/gi, '=').
  1044. replace(/%2B/gi, '+');
  1045. }
  1046. /**
  1047. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1048. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1049. * encoded per http://tools.ietf.org/html/rfc3986:
  1050. * query = *( pchar / "/" / "?" )
  1051. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1052. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1053. * pct-encoded = "%" HEXDIG HEXDIG
  1054. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1055. * / "*" / "+" / "," / ";" / "="
  1056. */
  1057. function encodeUriQuery(val, pctEncodeSpaces) {
  1058. return encodeURIComponent(val).
  1059. replace(/%40/gi, '@').
  1060. replace(/%3A/gi, ':').
  1061. replace(/%24/g, '$').
  1062. replace(/%2C/gi, ',').
  1063. replace(/%3B/gi, ';').
  1064. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1065. }
  1066. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1067. function getNgAttribute(element, ngAttr) {
  1068. var attr, i, ii = ngAttrPrefixes.length;
  1069. element = jqLite(element);
  1070. for (i=0; i<ii; ++i) {
  1071. attr = ngAttrPrefixes[i] + ngAttr;
  1072. if (isString(attr = element.attr(attr))) {
  1073. return attr;
  1074. }
  1075. }
  1076. return null;
  1077. }
  1078. /**
  1079. * @ngdoc directive
  1080. * @name ngApp
  1081. * @module ng
  1082. *
  1083. * @element ANY
  1084. * @param {angular.Module} ngApp an optional application
  1085. * {@link angular.module module} name to load.
  1086. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1087. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1088. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1089. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1090. * tracking down the root of these bugs.
  1091. *
  1092. * @description
  1093. *
  1094. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1095. * designates the **root element** of the application and is typically placed near the root element
  1096. * of the page - e.g. on the `<body>` or `<html>` tags.
  1097. *
  1098. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1099. * found in the document will be used to define the root element to auto-bootstrap as an
  1100. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1101. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1102. *
  1103. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1104. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1105. * should contain the application code needed or have dependencies on other modules that will
  1106. * contain the code. See {@link angular.module} for more information.
  1107. *
  1108. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1109. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1110. * would not be resolved to `3`.
  1111. *
  1112. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1113. *
  1114. <example module="ngAppDemo">
  1115. <file name="index.html">
  1116. <div ng-controller="ngAppDemoController">
  1117. I can add: {{a}} + {{b}} = {{ a+b }}
  1118. </div>
  1119. </file>
  1120. <file name="script.js">
  1121. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1122. $scope.a = 1;
  1123. $scope.b = 2;
  1124. });
  1125. </file>
  1126. </example>
  1127. *
  1128. * Using `ngStrictDi`, you would see something like this:
  1129. *
  1130. <example ng-app-included="true">
  1131. <file name="index.html">
  1132. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1133. <div ng-controller="GoodController1">
  1134. I can add: {{a}} + {{b}} = {{ a+b }}
  1135. <p>This renders because the controller does not fail to
  1136. instantiate, by using explicit annotation style (see
  1137. script.js for details)
  1138. </p>
  1139. </div>
  1140. <div ng-controller="GoodController2">
  1141. Name: <input ng-model="name"><br />
  1142. Hello, {{name}}!
  1143. <p>This renders because the controller does not fail to
  1144. instantiate, by using explicit annotation style
  1145. (see script.js for details)
  1146. </p>
  1147. </div>
  1148. <div ng-controller="BadController">
  1149. I can add: {{a}} + {{b}} = {{ a+b }}
  1150. <p>The controller could not be instantiated, due to relying
  1151. on automatic function annotations (which are disabled in
  1152. strict mode). As such, the content of this section is not
  1153. interpolated, and there should be an error in your web console.
  1154. </p>
  1155. </div>
  1156. </div>
  1157. </file>
  1158. <file name="script.js">
  1159. angular.module('ngAppStrictDemo', [])
  1160. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1161. // rather than an explicit annotation
  1162. .controller('BadController', function($scope) {
  1163. $scope.a = 1;
  1164. $scope.b = 2;
  1165. })
  1166. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1167. // due to using explicit annotations using the array style and $inject property, respectively.
  1168. .controller('GoodController1', ['$scope', function($scope) {
  1169. $scope.a = 1;
  1170. $scope.b = 2;
  1171. }])
  1172. .controller('GoodController2', GoodController2);
  1173. function GoodController2($scope) {
  1174. $scope.name = "World";
  1175. }
  1176. GoodController2.$inject = ['$scope'];
  1177. </file>
  1178. <file name="style.css">
  1179. div[ng-controller] {
  1180. margin-bottom: 1em;
  1181. -webkit-border-radius: 4px;
  1182. border-radius: 4px;
  1183. border: 1px solid;
  1184. padding: .5em;
  1185. }
  1186. div[ng-controller^=Good] {
  1187. border-color: #d6e9c6;
  1188. background-color: #dff0d8;
  1189. color: #3c763d;
  1190. }
  1191. div[ng-controller^=Bad] {
  1192. border-color: #ebccd1;
  1193. background-color: #f2dede;
  1194. color: #a94442;
  1195. margin-bottom: 0;
  1196. }
  1197. </file>
  1198. </example>
  1199. */
  1200. function angularInit(element, bootstrap) {
  1201. var appElement,
  1202. module,
  1203. config = {};
  1204. // The element `element` has priority over any other element
  1205. forEach(ngAttrPrefixes, function(prefix) {
  1206. var name = prefix + 'app';
  1207. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1208. appElement = element;
  1209. module = element.getAttribute(name);
  1210. }
  1211. });
  1212. forEach(ngAttrPrefixes, function(prefix) {
  1213. var name = prefix + 'app';
  1214. var candidate;
  1215. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1216. appElement = candidate;
  1217. module = candidate.getAttribute(name);
  1218. }
  1219. });
  1220. if (appElement) {
  1221. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1222. bootstrap(appElement, module ? [module] : [], config);
  1223. }
  1224. }
  1225. /**
  1226. * @ngdoc function
  1227. * @name angular.bootstrap
  1228. * @module ng
  1229. * @description
  1230. * Use this function to manually start up angular application.
  1231. *
  1232. * See: {@link guide/bootstrap Bootstrap}
  1233. *
  1234. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1235. * They must use {@link ng.directive:ngApp ngApp}.
  1236. *
  1237. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1238. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1239. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1240. * multiple instances of Angular try to work on the DOM.
  1241. *
  1242. * ```html
  1243. * <!doctype html>
  1244. * <html>
  1245. * <body>
  1246. * <div ng-controller="WelcomeController">
  1247. * {{greeting}}
  1248. * </div>
  1249. *
  1250. * <script src="angular.js"></script>
  1251. * <script>
  1252. * var app = angular.module('demo', [])
  1253. * .controller('WelcomeController', function($scope) {
  1254. * $scope.greeting = 'Welcome!';
  1255. * });
  1256. * angular.bootstrap(document, ['demo']);
  1257. * </script>
  1258. * </body>
  1259. * </html>
  1260. * ```
  1261. *
  1262. * @param {DOMElement} element DOM element which is the root of angular application.
  1263. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1264. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1265. * function that will be invoked by the injector as a run block.
  1266. * See: {@link angular.module modules}
  1267. * @param {Object=} config an object for defining configuration options for the application. The
  1268. * following keys are supported:
  1269. *
  1270. * - `strictDi`: disable automatic function annotation for the application. This is meant to
  1271. * assist in finding bugs which break minified code.
  1272. *
  1273. * @returns {auto.$injector} Returns the newly created injector for this app.
  1274. */
  1275. function bootstrap(element, modules, config) {
  1276. if (!isObject(config)) config = {};
  1277. var defaultConfig = {
  1278. strictDi: false
  1279. };
  1280. config = extend(defaultConfig, config);
  1281. var doBootstrap = function() {
  1282. element = jqLite(element);
  1283. if (element.injector()) {
  1284. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1285. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1286. throw ngMinErr(
  1287. 'btstrpd',
  1288. "App Already Bootstrapped with this Element '{0}'",
  1289. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1290. }
  1291. modules = modules || [];
  1292. modules.unshift(['$provide', function($provide) {
  1293. $provide.value('$rootElement', element);
  1294. }]);
  1295. if (config.debugInfoEnabled) {
  1296. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1297. modules.push(['$compileProvider', function($compileProvider) {
  1298. $compileProvider.debugInfoEnabled(true);
  1299. }]);
  1300. }
  1301. modules.unshift('ng');
  1302. var injector = createInjector(modules, config.strictDi);
  1303. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1304. function bootstrapApply(scope, element, compile, injector) {
  1305. scope.$apply(function() {
  1306. element.data('$injector', injector);
  1307. compile(element)(scope);
  1308. });
  1309. }]
  1310. );
  1311. return injector;
  1312. };
  1313. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1314. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1315. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1316. config.debugInfoEnabled = true;
  1317. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1318. }
  1319. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1320. return doBootstrap();
  1321. }
  1322. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1323. angular.resumeBootstrap = function(extraModules) {
  1324. forEach(extraModules, function(module) {
  1325. modules.push(module);
  1326. });
  1327. doBootstrap();
  1328. };
  1329. }
  1330. /**
  1331. * @ngdoc function
  1332. * @name angular.reloadWithDebugInfo
  1333. * @module ng
  1334. * @description
  1335. * Use this function to reload the current application with debug information turned on.
  1336. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1337. *
  1338. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1339. */
  1340. function reloadWithDebugInfo() {
  1341. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1342. window.location.reload();
  1343. }
  1344. /**
  1345. * @name angular.getTestability
  1346. * @module ng
  1347. * @description
  1348. * Get the testability service for the instance of Angular on the given
  1349. * element.
  1350. * @param {DOMElement} element DOM element which is the root of angular application.
  1351. */
  1352. function getTestability(rootElement) {
  1353. return angular.element(rootElement).injector().get('$$testability');
  1354. }
  1355. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1356. function snake_case(name, separator) {
  1357. separator = separator || '_';
  1358. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1359. return (pos ? separator : '') + letter.toLowerCase();
  1360. });
  1361. }
  1362. var bindJQueryFired = false;
  1363. var skipDestroyOnNextJQueryCleanData;
  1364. function bindJQuery() {
  1365. var originalCleanData;
  1366. if (bindJQueryFired) {
  1367. return;
  1368. }
  1369. // bind to jQuery if present;
  1370. jQuery = window.jQuery;
  1371. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1372. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1373. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1374. // versions. It will not work for sure with jQuery <1.7, though.
  1375. if (jQuery && jQuery.fn.on) {
  1376. jqLite = jQuery;
  1377. extend(jQuery.fn, {
  1378. scope: JQLitePrototype.scope,
  1379. isolateScope: JQLitePrototype.isolateScope,
  1380. controller: JQLitePrototype.controller,
  1381. injector: JQLitePrototype.injector,
  1382. inheritedData: JQLitePrototype.inheritedData
  1383. });
  1384. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1385. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1386. // the $destroy event on all removed nodes.
  1387. originalCleanData = jQuery.cleanData;
  1388. jQuery.cleanData = function(elems) {
  1389. var events;
  1390. if (!skipDestroyOnNextJQueryCleanData) {
  1391. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1392. events = jQuery._data(elem, "events");
  1393. if (events && events.$destroy) {
  1394. jQuery(elem).triggerHandler('$destroy');
  1395. }
  1396. }
  1397. } else {
  1398. skipDestroyOnNextJQueryCleanData = false;
  1399. }
  1400. originalCleanData(elems);
  1401. };
  1402. } else {
  1403. jqLite = JQLite;
  1404. }
  1405. angular.element = jqLite;
  1406. // Prevent double-proxying.
  1407. bindJQueryFired = true;
  1408. }
  1409. /**
  1410. * throw error if the argument is falsy.
  1411. */
  1412. function assertArg(arg, name, reason) {
  1413. if (!arg) {
  1414. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1415. }
  1416. return arg;
  1417. }
  1418. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1419. if (acceptArrayAnnotation && isArray(arg)) {
  1420. arg = arg[arg.length - 1];
  1421. }
  1422. assertArg(isFunction(arg), name, 'not a function, got ' +
  1423. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1424. return arg;
  1425. }
  1426. /**
  1427. * throw error if the name given is hasOwnProperty
  1428. * @param {String} name the name to test
  1429. * @param {String} context the context in which the name is used, such as module or directive
  1430. */
  1431. function assertNotHasOwnProperty(name, context) {
  1432. if (name === 'hasOwnProperty') {
  1433. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1434. }
  1435. }
  1436. /**
  1437. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1438. * @param {Object} obj starting object
  1439. * @param {String} path path to traverse
  1440. * @param {boolean} [bindFnToScope=true]
  1441. * @returns {Object} value as accessible by path
  1442. */
  1443. //TODO(misko): this function needs to be removed
  1444. function getter(obj, path, bindFnToScope) {
  1445. if (!path) return obj;
  1446. var keys = path.split('.');
  1447. var key;
  1448. var lastInstance = obj;
  1449. var len = keys.length;
  1450. for (var i = 0; i < len; i++) {
  1451. key = keys[i];
  1452. if (obj) {
  1453. obj = (lastInstance = obj)[key];
  1454. }
  1455. }
  1456. if (!bindFnToScope && isFunction(obj)) {
  1457. return bind(lastInstance, obj);
  1458. }
  1459. return obj;
  1460. }
  1461. /**
  1462. * Return the DOM siblings between the first and last node in the given array.
  1463. * @param {Array} array like object
  1464. * @returns {jqLite} jqLite collection containing the nodes
  1465. */
  1466. function getBlockNodes(nodes) {
  1467. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1468. // collection, otherwise update the original collection.
  1469. var node = nodes[0];
  1470. var endNode = nodes[nodes.length - 1];
  1471. var blockNodes = [node];
  1472. do {
  1473. node = node.nextSibling;
  1474. if (!node) break;
  1475. blockNodes.push(node);
  1476. } while (node !== endNode);
  1477. return jqLite(blockNodes);
  1478. }
  1479. /**
  1480. * Creates a new object without a prototype. This object is useful for lookup without having to
  1481. * guard against prototypically inherited properties via hasOwnProperty.
  1482. *
  1483. * Related micro-benchmarks:
  1484. * - http://jsperf.com/object-create2
  1485. * - http://jsperf.com/proto-map-lookup/2
  1486. * - http://jsperf.com/for-in-vs-object-keys2
  1487. *
  1488. * @returns {Object}
  1489. */
  1490. function createMap() {
  1491. return Object.create(null);
  1492. }
  1493. var NODE_TYPE_ELEMENT = 1;
  1494. var NODE_TYPE_TEXT = 3;
  1495. var NODE_TYPE_COMMENT = 8;
  1496. var NODE_TYPE_DOCUMENT = 9;
  1497. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1498. /**
  1499. * @ngdoc type
  1500. * @name angular.Module
  1501. * @module ng
  1502. * @description
  1503. *
  1504. * Interface for configuring angular {@link angular.module modules}.
  1505. */
  1506. function setupModuleLoader(window) {
  1507. var $injectorMinErr = minErr('$injector');
  1508. var ngMinErr = minErr('ng');
  1509. function ensure(obj, name, factory) {
  1510. return obj[name] || (obj[name] = factory());
  1511. }
  1512. var angular = ensure(window, 'angular', Object);
  1513. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1514. angular.$$minErr = angular.$$minErr || minErr;
  1515. return ensure(angular, 'module', function() {
  1516. /** @type {Object.<string, angular.Module>} */
  1517. var modules = {};
  1518. /**
  1519. * @ngdoc function
  1520. * @name angular.module
  1521. * @module ng
  1522. * @description
  1523. *
  1524. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1525. * modules.
  1526. * All modules (angular core or 3rd party) that should be available to an application must be
  1527. * registered using this mechanism.
  1528. *
  1529. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1530. * existing module (the name passed as the first argument to `module`) is retrieved.
  1531. *
  1532. *
  1533. * # Module
  1534. *
  1535. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1536. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1537. *
  1538. * ```js
  1539. * // Create a new module
  1540. * var myModule = angular.module('myModule', []);
  1541. *
  1542. * // register a new service
  1543. * myModule.value('appName', 'MyCoolApp');
  1544. *
  1545. * // configure existing services inside initialization blocks.
  1546. * myModule.config(['$locationProvider', function($locationProvider) {
  1547. * // Configure existing providers
  1548. * $locationProvider.hashPrefix('!');
  1549. * }]);
  1550. * ```
  1551. *
  1552. * Then you can create an injector and load your modules like this:
  1553. *
  1554. * ```js
  1555. * var injector = angular.injector(['ng', 'myModule'])
  1556. * ```
  1557. *
  1558. * However it's more likely that you'll just use
  1559. * {@link ng.directive:ngApp ngApp} or
  1560. * {@link angular.bootstrap} to simplify this process for you.
  1561. *
  1562. * @param {!string} name The name of the module to create or retrieve.
  1563. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1564. * unspecified then the module is being retrieved for further configuration.
  1565. * @param {Function=} configFn Optional configuration function for the module. Same as
  1566. * {@link angular.Module#config Module#config()}.
  1567. * @returns {module} new module with the {@link angular.Module} api.
  1568. */
  1569. return function module(name, requires, configFn) {
  1570. var assertNotHasOwnProperty = function(name, context) {
  1571. if (name === 'hasOwnProperty') {
  1572. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1573. }
  1574. };
  1575. assertNotHasOwnProperty(name, 'module');
  1576. if (requires && modules.hasOwnProperty(name)) {
  1577. modules[name] = null;
  1578. }
  1579. return ensure(modules, name, function() {
  1580. if (!requires) {
  1581. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1582. "the module name or forgot to load it. If registering a module ensure that you " +
  1583. "specify the dependencies as the second argument.", name);
  1584. }
  1585. /** @type {!Array.<Array.<*>>} */
  1586. var invokeQueue = [];
  1587. /** @type {!Array.<Function>} */
  1588. var configBlocks = [];
  1589. /** @type {!Array.<Function>} */
  1590. var runBlocks = [];
  1591. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1592. /** @type {angular.Module} */
  1593. var moduleInstance = {
  1594. // Private state
  1595. _invokeQueue: invokeQueue,
  1596. _configBlocks: configBlocks,
  1597. _runBlocks: runBlocks,
  1598. /**
  1599. * @ngdoc property
  1600. * @name angular.Module#requires
  1601. * @module ng
  1602. *
  1603. * @description
  1604. * Holds the list of modules which the injector will load before the current module is
  1605. * loaded.
  1606. */
  1607. requires: requires,
  1608. /**
  1609. * @ngdoc property
  1610. * @name angular.Module#name
  1611. * @module ng
  1612. *
  1613. * @description
  1614. * Name of the module.
  1615. */
  1616. name: name,
  1617. /**
  1618. * @ngdoc method
  1619. * @name angular.Module#provider
  1620. * @module ng
  1621. * @param {string} name service name
  1622. * @param {Function} providerType Construction function for creating new instance of the
  1623. * service.
  1624. * @description
  1625. * See {@link auto.$provide#provider $provide.provider()}.
  1626. */
  1627. provider: invokeLater('$provide', 'provider'),
  1628. /**
  1629. * @ngdoc method
  1630. * @name angular.Module#factory
  1631. * @module ng
  1632. * @param {string} name service name
  1633. * @param {Function} providerFunction Function for creating new instance of the service.
  1634. * @description
  1635. * See {@link auto.$provide#factory $provide.factory()}.
  1636. */
  1637. factory: invokeLater('$provide', 'factory'),
  1638. /**
  1639. * @ngdoc method
  1640. * @name angular.Module#service
  1641. * @module ng
  1642. * @param {string} name service name
  1643. * @param {Function} constructor A constructor function that will be instantiated.
  1644. * @description
  1645. * See {@link auto.$provide#service $provide.service()}.
  1646. */
  1647. service: invokeLater('$provide', 'service'),
  1648. /**
  1649. * @ngdoc method
  1650. * @name angular.Module#value
  1651. * @module ng
  1652. * @param {string} name service name
  1653. * @param {*} object Service instance object.
  1654. * @description
  1655. * See {@link auto.$provide#value $provide.value()}.
  1656. */
  1657. value: invokeLater('$provide', 'value'),
  1658. /**
  1659. * @ngdoc method
  1660. * @name angular.Module#constant
  1661. * @module ng
  1662. * @param {string} name constant name
  1663. * @param {*} object Constant value.
  1664. * @description
  1665. * Because the constant are fixed, they get applied before other provide methods.
  1666. * See {@link auto.$provide#constant $provide.constant()}.
  1667. */
  1668. constant: invokeLater('$provide', 'constant', 'unshift'),
  1669. /**
  1670. * @ngdoc method
  1671. * @name angular.Module#animation
  1672. * @module ng
  1673. * @param {string} name animation name
  1674. * @param {Function} animationFactory Factory function for creating new instance of an
  1675. * animation.
  1676. * @description
  1677. *
  1678. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1679. *
  1680. *
  1681. * Defines an animation hook that can be later used with
  1682. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1683. *
  1684. * ```js
  1685. * module.animation('.animation-name', function($inject1, $inject2) {
  1686. * return {
  1687. * eventName : function(element, done) {
  1688. * //code to run the animation
  1689. * //once complete, then run done()
  1690. * return function cancellationFunction(element) {
  1691. * //code to cancel the animation
  1692. * }
  1693. * }
  1694. * }
  1695. * })
  1696. * ```
  1697. *
  1698. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1699. * {@link ngAnimate ngAnimate module} for more information.
  1700. */
  1701. animation: invokeLater('$animateProvider', 'register'),
  1702. /**
  1703. * @ngdoc method
  1704. * @name angular.Module#filter
  1705. * @module ng
  1706. * @param {string} name Filter name.
  1707. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1708. * @description
  1709. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1710. */
  1711. filter: invokeLater('$filterProvider', 'register'),
  1712. /**
  1713. * @ngdoc method
  1714. * @name angular.Module#controller
  1715. * @module ng
  1716. * @param {string|Object} name Controller name, or an object map of controllers where the
  1717. * keys are the names and the values are the constructors.
  1718. * @param {Function} constructor Controller constructor function.
  1719. * @description
  1720. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1721. */
  1722. controller: invokeLater('$controllerProvider', 'register'),
  1723. /**
  1724. * @ngdoc method
  1725. * @name angular.Module#directive
  1726. * @module ng
  1727. * @param {string|Object} name Directive name, or an object map of directives where the
  1728. * keys are the names and the values are the factories.
  1729. * @param {Function} directiveFactory Factory function for creating new instance of
  1730. * directives.
  1731. * @description
  1732. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1733. */
  1734. directive: invokeLater('$compileProvider', 'directive'),
  1735. /**
  1736. * @ngdoc method
  1737. * @name angular.Module#config
  1738. * @module ng
  1739. * @param {Function} configFn Execute this function on module load. Useful for service
  1740. * configuration.
  1741. * @description
  1742. * Use this method to register work which needs to be performed on module loading.
  1743. * For more about how to configure services, see
  1744. * {@link providers#provider-recipe Provider Recipe}.
  1745. */
  1746. config: config,
  1747. /**
  1748. * @ngdoc method
  1749. * @name angular.Module#run
  1750. * @module ng
  1751. * @param {Function} initializationFn Execute this function after injector creation.
  1752. * Useful for application initialization.
  1753. * @description
  1754. * Use this method to register work which should be performed when the injector is done
  1755. * loading all modules.
  1756. */
  1757. run: function(block) {
  1758. runBlocks.push(block);
  1759. return this;
  1760. }
  1761. };
  1762. if (configFn) {
  1763. config(configFn);
  1764. }
  1765. return moduleInstance;
  1766. /**
  1767. * @param {string} provider
  1768. * @param {string} method
  1769. * @param {String=} insertMethod
  1770. * @returns {angular.Module}
  1771. */
  1772. function invokeLater(provider, method, insertMethod, queue) {
  1773. if (!queue) queue = invokeQueue;
  1774. return function() {
  1775. queue[insertMethod || 'push']([provider, method, arguments]);
  1776. return moduleInstance;
  1777. };
  1778. }
  1779. });
  1780. };
  1781. });
  1782. }
  1783. /* global angularModule: true,
  1784. version: true,
  1785. $LocaleProvider,
  1786. $CompileProvider,
  1787. htmlAnchorDirective,
  1788. inputDirective,
  1789. inputDirective,
  1790. formDirective,
  1791. scriptDirective,
  1792. selectDirective,
  1793. styleDirective,
  1794. optionDirective,
  1795. ngBindDirective,
  1796. ngBindHtmlDirective,
  1797. ngBindTemplateDirective,
  1798. ngClassDirective,
  1799. ngClassEvenDirective,
  1800. ngClassOddDirective,
  1801. ngCspDirective,
  1802. ngCloakDirective,
  1803. ngControllerDirective,
  1804. ngFormDirective,
  1805. ngHideDirective,
  1806. ngIfDirective,
  1807. ngIncludeDirective,
  1808. ngIncludeFillContentDirective,
  1809. ngInitDirective,
  1810. ngNonBindableDirective,
  1811. ngPluralizeDirective,
  1812. ngRepeatDirective,
  1813. ngShowDirective,
  1814. ngStyleDirective,
  1815. ngSwitchDirective,
  1816. ngSwitchWhenDirective,
  1817. ngSwitchDefaultDirective,
  1818. ngOptionsDirective,
  1819. ngTranscludeDirective,
  1820. ngModelDirective,
  1821. ngListDirective,
  1822. ngChangeDirective,
  1823. patternDirective,
  1824. patternDirective,
  1825. requiredDirective,
  1826. requiredDirective,
  1827. minlengthDirective,
  1828. minlengthDirective,
  1829. maxlengthDirective,
  1830. maxlengthDirective,
  1831. ngValueDirective,
  1832. ngModelOptionsDirective,
  1833. ngAttributeAliasDirectives,
  1834. ngEventDirectives,
  1835. $AnchorScrollProvider,
  1836. $AnimateProvider,
  1837. $BrowserProvider,
  1838. $CacheFactoryProvider,
  1839. $ControllerProvider,
  1840. $DocumentProvider,
  1841. $ExceptionHandlerProvider,
  1842. $FilterProvider,
  1843. $InterpolateProvider,
  1844. $IntervalProvider,
  1845. $HttpProvider,
  1846. $HttpBackendProvider,
  1847. $LocationProvider,
  1848. $LogProvider,
  1849. $ParseProvider,
  1850. $RootScopeProvider,
  1851. $QProvider,
  1852. $$QProvider,
  1853. $$SanitizeUriProvider,
  1854. $SceProvider,
  1855. $SceDelegateProvider,
  1856. $SnifferProvider,
  1857. $TemplateCacheProvider,
  1858. $TemplateRequestProvider,
  1859. $$TestabilityProvider,
  1860. $TimeoutProvider,
  1861. $$RAFProvider,
  1862. $$AsyncCallbackProvider,
  1863. $WindowProvider
  1864. */
  1865. /**
  1866. * @ngdoc object
  1867. * @name angular.version
  1868. * @module ng
  1869. * @description
  1870. * An object that contains information about the current AngularJS version. This object has the
  1871. * following properties:
  1872. *
  1873. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1874. * - `major` – `{number}` – Major version number, such as "0".
  1875. * - `minor` – `{number}` – Minor version number, such as "9".
  1876. * - `dot` – `{number}` – Dot version number, such as "18".
  1877. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1878. */
  1879. var version = {
  1880. full: '1.3.2', // all of these placeholder strings will be replaced by grunt's
  1881. major: 1, // package task
  1882. minor: 3,
  1883. dot: 2,
  1884. codeName: 'cardiovasculatory-magnification'
  1885. };
  1886. function publishExternalAPI(angular) {
  1887. extend(angular, {
  1888. 'bootstrap': bootstrap,
  1889. 'copy': copy,
  1890. 'extend': extend,
  1891. 'equals': equals,
  1892. 'element': jqLite,
  1893. 'forEach': forEach,
  1894. 'injector': createInjector,
  1895. 'noop': noop,
  1896. 'bind': bind,
  1897. 'toJson': toJson,
  1898. 'fromJson': fromJson,
  1899. 'identity': identity,
  1900. 'isUndefined': isUndefined,
  1901. 'isDefined': isDefined,
  1902. 'isString': isString,
  1903. 'isFunction': isFunction,
  1904. 'isObject': isObject,
  1905. 'isNumber': isNumber,
  1906. 'isElement': isElement,
  1907. 'isArray': isArray,
  1908. 'version': version,
  1909. 'isDate': isDate,
  1910. 'lowercase': lowercase,
  1911. 'uppercase': uppercase,
  1912. 'callbacks': {counter: 0},
  1913. 'getTestability': getTestability,
  1914. '$$minErr': minErr,
  1915. '$$csp': csp,
  1916. 'reloadWithDebugInfo': reloadWithDebugInfo
  1917. });
  1918. angularModule = setupModuleLoader(window);
  1919. try {
  1920. angularModule('ngLocale');
  1921. } catch (e) {
  1922. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1923. }
  1924. angularModule('ng', ['ngLocale'], ['$provide',
  1925. function ngModule($provide) {
  1926. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1927. $provide.provider({
  1928. $$sanitizeUri: $$SanitizeUriProvider
  1929. });
  1930. $provide.provider('$compile', $CompileProvider).
  1931. directive({
  1932. a: htmlAnchorDirective,
  1933. input: inputDirective,
  1934. textarea: inputDirective,
  1935. form: formDirective,
  1936. script: scriptDirective,
  1937. select: selectDirective,
  1938. style: styleDirective,
  1939. option: optionDirective,
  1940. ngBind: ngBindDirective,
  1941. ngBindHtml: ngBindHtmlDirective,
  1942. ngBindTemplate: ngBindTemplateDirective,
  1943. ngClass: ngClassDirective,
  1944. ngClassEven: ngClassEvenDirective,
  1945. ngClassOdd: ngClassOddDirective,
  1946. ngCloak: ngCloakDirective,
  1947. ngController: ngControllerDirective,
  1948. ngForm: ngFormDirective,
  1949. ngHide: ngHideDirective,
  1950. ngIf: ngIfDirective,
  1951. ngInclude: ngIncludeDirective,
  1952. ngInit: ngInitDirective,
  1953. ngNonBindable: ngNonBindableDirective,
  1954. ngPluralize: ngPluralizeDirective,
  1955. ngRepeat: ngRepeatDirective,
  1956. ngShow: ngShowDirective,
  1957. ngStyle: ngStyleDirective,
  1958. ngSwitch: ngSwitchDirective,
  1959. ngSwitchWhen: ngSwitchWhenDirective,
  1960. ngSwitchDefault: ngSwitchDefaultDirective,
  1961. ngOptions: ngOptionsDirective,
  1962. ngTransclude: ngTranscludeDirective,
  1963. ngModel: ngModelDirective,
  1964. ngList: ngListDirective,
  1965. ngChange: ngChangeDirective,
  1966. pattern: patternDirective,
  1967. ngPattern: patternDirective,
  1968. required: requiredDirective,
  1969. ngRequired: requiredDirective,
  1970. minlength: minlengthDirective,
  1971. ngMinlength: minlengthDirective,
  1972. maxlength: maxlengthDirective,
  1973. ngMaxlength: maxlengthDirective,
  1974. ngValue: ngValueDirective,
  1975. ngModelOptions: ngModelOptionsDirective
  1976. }).
  1977. directive({
  1978. ngInclude: ngIncludeFillContentDirective
  1979. }).
  1980. directive(ngAttributeAliasDirectives).
  1981. directive(ngEventDirectives);
  1982. $provide.provider({
  1983. $anchorScroll: $AnchorScrollProvider,
  1984. $animate: $AnimateProvider,
  1985. $browser: $BrowserProvider,
  1986. $cacheFactory: $CacheFactoryProvider,
  1987. $controller: $ControllerProvider,
  1988. $document: $DocumentProvider,
  1989. $exceptionHandler: $ExceptionHandlerProvider,
  1990. $filter: $FilterProvider,
  1991. $interpolate: $InterpolateProvider,
  1992. $interval: $IntervalProvider,
  1993. $http: $HttpProvider,
  1994. $httpBackend: $HttpBackendProvider,
  1995. $location: $LocationProvider,
  1996. $log: $LogProvider,
  1997. $parse: $ParseProvider,
  1998. $rootScope: $RootScopeProvider,
  1999. $q: $QProvider,
  2000. $$q: $$QProvider,
  2001. $sce: $SceProvider,
  2002. $sceDelegate: $SceDelegateProvider,
  2003. $sniffer: $SnifferProvider,
  2004. $templateCache: $TemplateCacheProvider,
  2005. $templateRequest: $TemplateRequestProvider,
  2006. $$testability: $$TestabilityProvider,
  2007. $timeout: $TimeoutProvider,
  2008. $window: $WindowProvider,
  2009. $$rAF: $$RAFProvider,
  2010. $$asyncCallback: $$AsyncCallbackProvider
  2011. });
  2012. }
  2013. ]);
  2014. }
  2015. /* global JQLitePrototype: true,
  2016. addEventListenerFn: true,
  2017. removeEventListenerFn: true,
  2018. BOOLEAN_ATTR: true,
  2019. ALIASED_ATTR: true,
  2020. */
  2021. //////////////////////////////////
  2022. //JQLite
  2023. //////////////////////////////////
  2024. /**
  2025. * @ngdoc function
  2026. * @name angular.element
  2027. * @module ng
  2028. * @kind function
  2029. *
  2030. * @description
  2031. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2032. *
  2033. * If jQuery is available, `angular.element` is an alias for the
  2034. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2035. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2036. *
  2037. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2038. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2039. * commonly needed functionality with the goal of having a very small footprint.</div>
  2040. *
  2041. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2042. *
  2043. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2044. * jqLite; they are never raw DOM references.</div>
  2045. *
  2046. * ## Angular's jqLite
  2047. * jqLite provides only the following jQuery methods:
  2048. *
  2049. * - [`addClass()`](http://api.jquery.com/addClass/)
  2050. * - [`after()`](http://api.jquery.com/after/)
  2051. * - [`append()`](http://api.jquery.com/append/)
  2052. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2053. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2054. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2055. * - [`clone()`](http://api.jquery.com/clone/)
  2056. * - [`contents()`](http://api.jquery.com/contents/)
  2057. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
  2058. * - [`data()`](http://api.jquery.com/data/)
  2059. * - [`detach()`](http://api.jquery.com/detach/)
  2060. * - [`empty()`](http://api.jquery.com/empty/)
  2061. * - [`eq()`](http://api.jquery.com/eq/)
  2062. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2063. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2064. * - [`html()`](http://api.jquery.com/html/)
  2065. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2066. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2067. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2068. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2069. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2070. * - [`prepend()`](http://api.jquery.com/prepend/)
  2071. * - [`prop()`](http://api.jquery.com/prop/)
  2072. * - [`ready()`](http://api.jquery.com/ready/)
  2073. * - [`remove()`](http://api.jquery.com/remove/)
  2074. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2075. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2076. * - [`removeData()`](http://api.jquery.com/removeData/)
  2077. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2078. * - [`text()`](http://api.jquery.com/text/)
  2079. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2080. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2081. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2082. * - [`val()`](http://api.jquery.com/val/)
  2083. * - [`wrap()`](http://api.jquery.com/wrap/)
  2084. *
  2085. * ## jQuery/jqLite Extras
  2086. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2087. *
  2088. * ### Events
  2089. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2090. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2091. * element before it is removed.
  2092. *
  2093. * ### Methods
  2094. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2095. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2096. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2097. * `'ngModel'`).
  2098. * - `injector()` - retrieves the injector of the current element or its parent.
  2099. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2100. * element or its parent.
  2101. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2102. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2103. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2104. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2105. * parent element is reached.
  2106. *
  2107. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2108. * @returns {Object} jQuery object.
  2109. */
  2110. JQLite.expando = 'ng339';
  2111. var jqCache = JQLite.cache = {},
  2112. jqId = 1,
  2113. addEventListenerFn = function(element, type, fn) {
  2114. element.addEventListener(type, fn, false);
  2115. },
  2116. removeEventListenerFn = function(element, type, fn) {
  2117. element.removeEventListener(type, fn, false);
  2118. };
  2119. /*
  2120. * !!! This is an undocumented "private" function !!!
  2121. */
  2122. JQLite._data = function(node) {
  2123. //jQuery always returns an object on cache miss
  2124. return this.cache[node[this.expando]] || {};
  2125. };
  2126. function jqNextId() { return ++jqId; }
  2127. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2128. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2129. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2130. var jqLiteMinErr = minErr('jqLite');
  2131. /**
  2132. * Converts snake_case to camelCase.
  2133. * Also there is special case for Moz prefix starting with upper case letter.
  2134. * @param name Name to normalize
  2135. */
  2136. function camelCase(name) {
  2137. return name.
  2138. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2139. return offset ? letter.toUpperCase() : letter;
  2140. }).
  2141. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2142. }
  2143. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2144. var HTML_REGEXP = /<|&#?\w+;/;
  2145. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2146. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2147. var wrapMap = {
  2148. 'option': [1, '<select multiple="multiple">', '</select>'],
  2149. 'thead': [1, '<table>', '</table>'],
  2150. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2151. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2152. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2153. '_default': [0, "", ""]
  2154. };
  2155. wrapMap.optgroup = wrapMap.option;
  2156. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2157. wrapMap.th = wrapMap.td;
  2158. function jqLiteIsTextNode(html) {
  2159. return !HTML_REGEXP.test(html);
  2160. }
  2161. function jqLiteAcceptsData(node) {
  2162. // The window object can accept data but has no nodeType
  2163. // Otherwise we are only interested in elements (1) and documents (9)
  2164. var nodeType = node.nodeType;
  2165. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2166. }
  2167. function jqLiteBuildFragment(html, context) {
  2168. var tmp, tag, wrap,
  2169. fragment = context.createDocumentFragment(),
  2170. nodes = [], i;
  2171. if (jqLiteIsTextNode(html)) {
  2172. // Convert non-html into a text node
  2173. nodes.push(context.createTextNode(html));
  2174. } else {
  2175. // Convert html into DOM nodes
  2176. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2177. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2178. wrap = wrapMap[tag] || wrapMap._default;
  2179. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2180. // Descend through wrappers to the right content
  2181. i = wrap[0];
  2182. while (i--) {
  2183. tmp = tmp.lastChild;
  2184. }
  2185. nodes = concat(nodes, tmp.childNodes);
  2186. tmp = fragment.firstChild;
  2187. tmp.textContent = "";
  2188. }
  2189. // Remove wrapper from fragment
  2190. fragment.textContent = "";
  2191. fragment.innerHTML = ""; // Clear inner HTML
  2192. forEach(nodes, function(node) {
  2193. fragment.appendChild(node);
  2194. });
  2195. return fragment;
  2196. }
  2197. function jqLiteParseHTML(html, context) {
  2198. context = context || document;
  2199. var parsed;
  2200. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2201. return [context.createElement(parsed[1])];
  2202. }
  2203. if ((parsed = jqLiteBuildFragment(html, context))) {
  2204. return parsed.childNodes;
  2205. }
  2206. return [];
  2207. }
  2208. /////////////////////////////////////////////
  2209. function JQLite(element) {
  2210. if (element instanceof JQLite) {
  2211. return element;
  2212. }
  2213. var argIsString;
  2214. if (isString(element)) {
  2215. element = trim(element);
  2216. argIsString = true;
  2217. }
  2218. if (!(this instanceof JQLite)) {
  2219. if (argIsString && element.charAt(0) != '<') {
  2220. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2221. }
  2222. return new JQLite(element);
  2223. }
  2224. if (argIsString) {
  2225. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2226. } else {
  2227. jqLiteAddNodes(this, element);
  2228. }
  2229. }
  2230. function jqLiteClone(element) {
  2231. return element.cloneNode(true);
  2232. }
  2233. function jqLiteDealoc(element, onlyDescendants) {
  2234. if (!onlyDescendants) jqLiteRemoveData(element);
  2235. if (element.querySelectorAll) {
  2236. var descendants = element.querySelectorAll('*');
  2237. for (var i = 0, l = descendants.length; i < l; i++) {
  2238. jqLiteRemoveData(descendants[i]);
  2239. }
  2240. }
  2241. }
  2242. function jqLiteOff(element, type, fn, unsupported) {
  2243. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2244. var expandoStore = jqLiteExpandoStore(element);
  2245. var events = expandoStore && expandoStore.events;
  2246. var handle = expandoStore && expandoStore.handle;
  2247. if (!handle) return; //no listeners registered
  2248. if (!type) {
  2249. for (type in events) {
  2250. if (type !== '$destroy') {
  2251. removeEventListenerFn(element, type, handle);
  2252. }
  2253. delete events[type];
  2254. }
  2255. } else {
  2256. forEach(type.split(' '), function(type) {
  2257. if (isDefined(fn)) {
  2258. var listenerFns = events[type];
  2259. arrayRemove(listenerFns || [], fn);
  2260. if (listenerFns && listenerFns.length > 0) {
  2261. return;
  2262. }
  2263. }
  2264. removeEventListenerFn(element, type, handle);
  2265. delete events[type];
  2266. });
  2267. }
  2268. }
  2269. function jqLiteRemoveData(element, name) {
  2270. var expandoId = element.ng339;
  2271. var expandoStore = expandoId && jqCache[expandoId];
  2272. if (expandoStore) {
  2273. if (name) {
  2274. delete expandoStore.data[name];
  2275. return;
  2276. }
  2277. if (expandoStore.handle) {
  2278. if (expandoStore.events.$destroy) {
  2279. expandoStore.handle({}, '$destroy');
  2280. }
  2281. jqLiteOff(element);
  2282. }
  2283. delete jqCache[expandoId];
  2284. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2285. }
  2286. }
  2287. function jqLiteExpandoStore(element, createIfNecessary) {
  2288. var expandoId = element.ng339,
  2289. expandoStore = expandoId && jqCache[expandoId];
  2290. if (createIfNecessary && !expandoStore) {
  2291. element.ng339 = expandoId = jqNextId();
  2292. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2293. }
  2294. return expandoStore;
  2295. }
  2296. function jqLiteData(element, key, value) {
  2297. if (jqLiteAcceptsData(element)) {
  2298. var isSimpleSetter = isDefined(value);
  2299. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2300. var massGetter = !key;
  2301. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2302. var data = expandoStore && expandoStore.data;
  2303. if (isSimpleSetter) { // data('key', value)
  2304. data[key] = value;
  2305. } else {
  2306. if (massGetter) { // data()
  2307. return data;
  2308. } else {
  2309. if (isSimpleGetter) { // data('key')
  2310. // don't force creation of expandoStore if it doesn't exist yet
  2311. return data && data[key];
  2312. } else { // mass-setter: data({key1: val1, key2: val2})
  2313. extend(data, key);
  2314. }
  2315. }
  2316. }
  2317. }
  2318. }
  2319. function jqLiteHasClass(element, selector) {
  2320. if (!element.getAttribute) return false;
  2321. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2322. indexOf(" " + selector + " ") > -1);
  2323. }
  2324. function jqLiteRemoveClass(element, cssClasses) {
  2325. if (cssClasses && element.setAttribute) {
  2326. forEach(cssClasses.split(' '), function(cssClass) {
  2327. element.setAttribute('class', trim(
  2328. (" " + (element.getAttribute('class') || '') + " ")
  2329. .replace(/[\n\t]/g, " ")
  2330. .replace(" " + trim(cssClass) + " ", " "))
  2331. );
  2332. });
  2333. }
  2334. }
  2335. function jqLiteAddClass(element, cssClasses) {
  2336. if (cssClasses && element.setAttribute) {
  2337. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2338. .replace(/[\n\t]/g, " ");
  2339. forEach(cssClasses.split(' '), function(cssClass) {
  2340. cssClass = trim(cssClass);
  2341. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2342. existingClasses += cssClass + ' ';
  2343. }
  2344. });
  2345. element.setAttribute('class', trim(existingClasses));
  2346. }
  2347. }
  2348. function jqLiteAddNodes(root, elements) {
  2349. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2350. if (elements) {
  2351. // if a Node (the most common case)
  2352. if (elements.nodeType) {
  2353. root[root.length++] = elements;
  2354. } else {
  2355. var length = elements.length;
  2356. // if an Array or NodeList and not a Window
  2357. if (typeof length === 'number' && elements.window !== elements) {
  2358. if (length) {
  2359. for (var i = 0; i < length; i++) {
  2360. root[root.length++] = elements[i];
  2361. }
  2362. }
  2363. } else {
  2364. root[root.length++] = elements;
  2365. }
  2366. }
  2367. }
  2368. }
  2369. function jqLiteController(element, name) {
  2370. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2371. }
  2372. function jqLiteInheritedData(element, name, value) {
  2373. // if element is the document object work with the html element instead
  2374. // this makes $(document).scope() possible
  2375. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2376. element = element.documentElement;
  2377. }
  2378. var names = isArray(name) ? name : [name];
  2379. while (element) {
  2380. for (var i = 0, ii = names.length; i < ii; i++) {
  2381. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2382. }
  2383. // If dealing with a document fragment node with a host element, and no parent, use the host
  2384. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2385. // to lookup parent controllers.
  2386. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2387. }
  2388. }
  2389. function jqLiteEmpty(element) {
  2390. jqLiteDealoc(element, true);
  2391. while (element.firstChild) {
  2392. element.removeChild(element.firstChild);
  2393. }
  2394. }
  2395. function jqLiteRemove(element, keepData) {
  2396. if (!keepData) jqLiteDealoc(element);
  2397. var parent = element.parentNode;
  2398. if (parent) parent.removeChild(element);
  2399. }
  2400. function jqLiteDocumentLoaded(action, win) {
  2401. win = win || window;
  2402. if (win.document.readyState === 'complete') {
  2403. // Force the action to be run async for consistent behaviour
  2404. // from the action's point of view
  2405. // i.e. it will definitely not be in a $apply
  2406. win.setTimeout(action);
  2407. } else {
  2408. // No need to unbind this handler as load is only ever called once
  2409. jqLite(win).on('load', action);
  2410. }
  2411. }
  2412. //////////////////////////////////////////
  2413. // Functions which are declared directly.
  2414. //////////////////////////////////////////
  2415. var JQLitePrototype = JQLite.prototype = {
  2416. ready: function(fn) {
  2417. var fired = false;
  2418. function trigger() {
  2419. if (fired) return;
  2420. fired = true;
  2421. fn();
  2422. }
  2423. // check if document is already loaded
  2424. if (document.readyState === 'complete') {
  2425. setTimeout(trigger);
  2426. } else {
  2427. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2428. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2429. // jshint -W064
  2430. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2431. // jshint +W064
  2432. }
  2433. },
  2434. toString: function() {
  2435. var value = [];
  2436. forEach(this, function(e) { value.push('' + e);});
  2437. return '[' + value.join(', ') + ']';
  2438. },
  2439. eq: function(index) {
  2440. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2441. },
  2442. length: 0,
  2443. push: push,
  2444. sort: [].sort,
  2445. splice: [].splice
  2446. };
  2447. //////////////////////////////////////////
  2448. // Functions iterating getter/setters.
  2449. // these functions return self on setter and
  2450. // value on get.
  2451. //////////////////////////////////////////
  2452. var BOOLEAN_ATTR = {};
  2453. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2454. BOOLEAN_ATTR[lowercase(value)] = value;
  2455. });
  2456. var BOOLEAN_ELEMENTS = {};
  2457. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2458. BOOLEAN_ELEMENTS[value] = true;
  2459. });
  2460. var ALIASED_ATTR = {
  2461. 'ngMinlength': 'minlength',
  2462. 'ngMaxlength': 'maxlength',
  2463. 'ngMin': 'min',
  2464. 'ngMax': 'max',
  2465. 'ngPattern': 'pattern'
  2466. };
  2467. function getBooleanAttrName(element, name) {
  2468. // check dom last since we will most likely fail on name
  2469. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2470. // booleanAttr is here twice to minimize DOM access
  2471. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2472. }
  2473. function getAliasedAttrName(element, name) {
  2474. var nodeName = element.nodeName;
  2475. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2476. }
  2477. forEach({
  2478. data: jqLiteData,
  2479. removeData: jqLiteRemoveData
  2480. }, function(fn, name) {
  2481. JQLite[name] = fn;
  2482. });
  2483. forEach({
  2484. data: jqLiteData,
  2485. inheritedData: jqLiteInheritedData,
  2486. scope: function(element) {
  2487. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2488. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2489. },
  2490. isolateScope: function(element) {
  2491. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2492. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2493. },
  2494. controller: jqLiteController,
  2495. injector: function(element) {
  2496. return jqLiteInheritedData(element, '$injector');
  2497. },
  2498. removeAttr: function(element, name) {
  2499. element.removeAttribute(name);
  2500. },
  2501. hasClass: jqLiteHasClass,
  2502. css: function(element, name, value) {
  2503. name = camelCase(name);
  2504. if (isDefined(value)) {
  2505. element.style[name] = value;
  2506. } else {
  2507. return element.style[name];
  2508. }
  2509. },
  2510. attr: function(element, name, value) {
  2511. var lowercasedName = lowercase(name);
  2512. if (BOOLEAN_ATTR[lowercasedName]) {
  2513. if (isDefined(value)) {
  2514. if (!!value) {
  2515. element[name] = true;
  2516. element.setAttribute(name, lowercasedName);
  2517. } else {
  2518. element[name] = false;
  2519. element.removeAttribute(lowercasedName);
  2520. }
  2521. } else {
  2522. return (element[name] ||
  2523. (element.attributes.getNamedItem(name)|| noop).specified)
  2524. ? lowercasedName
  2525. : undefined;
  2526. }
  2527. } else if (isDefined(value)) {
  2528. element.setAttribute(name, value);
  2529. } else if (element.getAttribute) {
  2530. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2531. // some elements (e.g. Document) don't have get attribute, so return undefined
  2532. var ret = element.getAttribute(name, 2);
  2533. // normalize non-existing attributes to undefined (as jQuery)
  2534. return ret === null ? undefined : ret;
  2535. }
  2536. },
  2537. prop: function(element, name, value) {
  2538. if (isDefined(value)) {
  2539. element[name] = value;
  2540. } else {
  2541. return element[name];
  2542. }
  2543. },
  2544. text: (function() {
  2545. getText.$dv = '';
  2546. return getText;
  2547. function getText(element, value) {
  2548. if (isUndefined(value)) {
  2549. var nodeType = element.nodeType;
  2550. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2551. }
  2552. element.textContent = value;
  2553. }
  2554. })(),
  2555. val: function(element, value) {
  2556. if (isUndefined(value)) {
  2557. if (element.multiple && nodeName_(element) === 'select') {
  2558. var result = [];
  2559. forEach(element.options, function(option) {
  2560. if (option.selected) {
  2561. result.push(option.value || option.text);
  2562. }
  2563. });
  2564. return result.length === 0 ? null : result;
  2565. }
  2566. return element.value;
  2567. }
  2568. element.value = value;
  2569. },
  2570. html: function(element, value) {
  2571. if (isUndefined(value)) {
  2572. return element.innerHTML;
  2573. }
  2574. jqLiteDealoc(element, true);
  2575. element.innerHTML = value;
  2576. },
  2577. empty: jqLiteEmpty
  2578. }, function(fn, name) {
  2579. /**
  2580. * Properties: writes return selection, reads return first value
  2581. */
  2582. JQLite.prototype[name] = function(arg1, arg2) {
  2583. var i, key;
  2584. var nodeCount = this.length;
  2585. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2586. // in a way that survives minification.
  2587. // jqLiteEmpty takes no arguments but is a setter.
  2588. if (fn !== jqLiteEmpty &&
  2589. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2590. if (isObject(arg1)) {
  2591. // we are a write, but the object properties are the key/values
  2592. for (i = 0; i < nodeCount; i++) {
  2593. if (fn === jqLiteData) {
  2594. // data() takes the whole object in jQuery
  2595. fn(this[i], arg1);
  2596. } else {
  2597. for (key in arg1) {
  2598. fn(this[i], key, arg1[key]);
  2599. }
  2600. }
  2601. }
  2602. // return self for chaining
  2603. return this;
  2604. } else {
  2605. // we are a read, so read the first child.
  2606. // TODO: do we still need this?
  2607. var value = fn.$dv;
  2608. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2609. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2610. for (var j = 0; j < jj; j++) {
  2611. var nodeValue = fn(this[j], arg1, arg2);
  2612. value = value ? value + nodeValue : nodeValue;
  2613. }
  2614. return value;
  2615. }
  2616. } else {
  2617. // we are a write, so apply to all children
  2618. for (i = 0; i < nodeCount; i++) {
  2619. fn(this[i], arg1, arg2);
  2620. }
  2621. // return self for chaining
  2622. return this;
  2623. }
  2624. };
  2625. });
  2626. function createEventHandler(element, events) {
  2627. var eventHandler = function(event, type) {
  2628. // jQuery specific api
  2629. event.isDefaultPrevented = function() {
  2630. return event.defaultPrevented;
  2631. };
  2632. var eventFns = events[type || event.type];
  2633. var eventFnsLength = eventFns ? eventFns.length : 0;
  2634. if (!eventFnsLength) return;
  2635. if (isUndefined(event.immediatePropagationStopped)) {
  2636. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2637. event.stopImmediatePropagation = function() {
  2638. event.immediatePropagationStopped = true;
  2639. if (event.stopPropagation) {
  2640. event.stopPropagation();
  2641. }
  2642. if (originalStopImmediatePropagation) {
  2643. originalStopImmediatePropagation.call(event);
  2644. }
  2645. };
  2646. }
  2647. event.isImmediatePropagationStopped = function() {
  2648. return event.immediatePropagationStopped === true;
  2649. };
  2650. // Copy event handlers in case event handlers array is modified during execution.
  2651. if ((eventFnsLength > 1)) {
  2652. eventFns = shallowCopy(eventFns);
  2653. }
  2654. for (var i = 0; i < eventFnsLength; i++) {
  2655. if (!event.isImmediatePropagationStopped()) {
  2656. eventFns[i].call(element, event);
  2657. }
  2658. }
  2659. };
  2660. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2661. // events on `element`
  2662. eventHandler.elem = element;
  2663. return eventHandler;
  2664. }
  2665. //////////////////////////////////////////
  2666. // Functions iterating traversal.
  2667. // These functions chain results into a single
  2668. // selector.
  2669. //////////////////////////////////////////
  2670. forEach({
  2671. removeData: jqLiteRemoveData,
  2672. on: function jqLiteOn(element, type, fn, unsupported) {
  2673. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2674. // Do not add event handlers to non-elements because they will not be cleaned up.
  2675. if (!jqLiteAcceptsData(element)) {
  2676. return;
  2677. }
  2678. var expandoStore = jqLiteExpandoStore(element, true);
  2679. var events = expandoStore.events;
  2680. var handle = expandoStore.handle;
  2681. if (!handle) {
  2682. handle = expandoStore.handle = createEventHandler(element, events);
  2683. }
  2684. // http://jsperf.com/string-indexof-vs-split
  2685. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2686. var i = types.length;
  2687. while (i--) {
  2688. type = types[i];
  2689. var eventFns = events[type];
  2690. if (!eventFns) {
  2691. events[type] = [];
  2692. if (type === 'mouseenter' || type === 'mouseleave') {
  2693. // Refer to jQuery's implementation of mouseenter & mouseleave
  2694. // Read about mouseenter and mouseleave:
  2695. // http://www.quirksmode.org/js/events_mouse.html#link8
  2696. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2697. var target = this, related = event.relatedTarget;
  2698. // For mousenter/leave call the handler if related is outside the target.
  2699. // NB: No relatedTarget if the mouse left/entered the browser window
  2700. if (!related || (related !== target && !target.contains(related))) {
  2701. handle(event, type);
  2702. }
  2703. });
  2704. } else {
  2705. if (type !== '$destroy') {
  2706. addEventListenerFn(element, type, handle);
  2707. }
  2708. }
  2709. eventFns = events[type];
  2710. }
  2711. eventFns.push(fn);
  2712. }
  2713. },
  2714. off: jqLiteOff,
  2715. one: function(element, type, fn) {
  2716. element = jqLite(element);
  2717. //add the listener twice so that when it is called
  2718. //you can remove the original function and still be
  2719. //able to call element.off(ev, fn) normally
  2720. element.on(type, function onFn() {
  2721. element.off(type, fn);
  2722. element.off(type, onFn);
  2723. });
  2724. element.on(type, fn);
  2725. },
  2726. replaceWith: function(element, replaceNode) {
  2727. var index, parent = element.parentNode;
  2728. jqLiteDealoc(element);
  2729. forEach(new JQLite(replaceNode), function(node) {
  2730. if (index) {
  2731. parent.insertBefore(node, index.nextSibling);
  2732. } else {
  2733. parent.replaceChild(node, element);
  2734. }
  2735. index = node;
  2736. });
  2737. },
  2738. children: function(element) {
  2739. var children = [];
  2740. forEach(element.childNodes, function(element) {
  2741. if (element.nodeType === NODE_TYPE_ELEMENT)
  2742. children.push(element);
  2743. });
  2744. return children;
  2745. },
  2746. contents: function(element) {
  2747. return element.contentDocument || element.childNodes || [];
  2748. },
  2749. append: function(element, node) {
  2750. var nodeType = element.nodeType;
  2751. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2752. node = new JQLite(node);
  2753. for (var i = 0, ii = node.length; i < ii; i++) {
  2754. var child = node[i];
  2755. element.appendChild(child);
  2756. }
  2757. },
  2758. prepend: function(element, node) {
  2759. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2760. var index = element.firstChild;
  2761. forEach(new JQLite(node), function(child) {
  2762. element.insertBefore(child, index);
  2763. });
  2764. }
  2765. },
  2766. wrap: function(element, wrapNode) {
  2767. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2768. var parent = element.parentNode;
  2769. if (parent) {
  2770. parent.replaceChild(wrapNode, element);
  2771. }
  2772. wrapNode.appendChild(element);
  2773. },
  2774. remove: jqLiteRemove,
  2775. detach: function(element) {
  2776. jqLiteRemove(element, true);
  2777. },
  2778. after: function(element, newElement) {
  2779. var index = element, parent = element.parentNode;
  2780. newElement = new JQLite(newElement);
  2781. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2782. var node = newElement[i];
  2783. parent.insertBefore(node, index.nextSibling);
  2784. index = node;
  2785. }
  2786. },
  2787. addClass: jqLiteAddClass,
  2788. removeClass: jqLiteRemoveClass,
  2789. toggleClass: function(element, selector, condition) {
  2790. if (selector) {
  2791. forEach(selector.split(' '), function(className) {
  2792. var classCondition = condition;
  2793. if (isUndefined(classCondition)) {
  2794. classCondition = !jqLiteHasClass(element, className);
  2795. }
  2796. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2797. });
  2798. }
  2799. },
  2800. parent: function(element) {
  2801. var parent = element.parentNode;
  2802. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2803. },
  2804. next: function(element) {
  2805. return element.nextElementSibling;
  2806. },
  2807. find: function(element, selector) {
  2808. if (element.getElementsByTagName) {
  2809. return element.getElementsByTagName(selector);
  2810. } else {
  2811. return [];
  2812. }
  2813. },
  2814. clone: jqLiteClone,
  2815. triggerHandler: function(element, event, extraParameters) {
  2816. var dummyEvent, eventFnsCopy, handlerArgs;
  2817. var eventName = event.type || event;
  2818. var expandoStore = jqLiteExpandoStore(element);
  2819. var events = expandoStore && expandoStore.events;
  2820. var eventFns = events && events[eventName];
  2821. if (eventFns) {
  2822. // Create a dummy event to pass to the handlers
  2823. dummyEvent = {
  2824. preventDefault: function() { this.defaultPrevented = true; },
  2825. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2826. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2827. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2828. stopPropagation: noop,
  2829. type: eventName,
  2830. target: element
  2831. };
  2832. // If a custom event was provided then extend our dummy event with it
  2833. if (event.type) {
  2834. dummyEvent = extend(dummyEvent, event);
  2835. }
  2836. // Copy event handlers in case event handlers array is modified during execution.
  2837. eventFnsCopy = shallowCopy(eventFns);
  2838. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2839. forEach(eventFnsCopy, function(fn) {
  2840. if (!dummyEvent.isImmediatePropagationStopped()) {
  2841. fn.apply(element, handlerArgs);
  2842. }
  2843. });
  2844. }
  2845. }
  2846. }, function(fn, name) {
  2847. /**
  2848. * chaining functions
  2849. */
  2850. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2851. var value;
  2852. for (var i = 0, ii = this.length; i < ii; i++) {
  2853. if (isUndefined(value)) {
  2854. value = fn(this[i], arg1, arg2, arg3);
  2855. if (isDefined(value)) {
  2856. // any function which returns a value needs to be wrapped
  2857. value = jqLite(value);
  2858. }
  2859. } else {
  2860. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2861. }
  2862. }
  2863. return isDefined(value) ? value : this;
  2864. };
  2865. // bind legacy bind/unbind to on/off
  2866. JQLite.prototype.bind = JQLite.prototype.on;
  2867. JQLite.prototype.unbind = JQLite.prototype.off;
  2868. });
  2869. /**
  2870. * Computes a hash of an 'obj'.
  2871. * Hash of a:
  2872. * string is string
  2873. * number is number as string
  2874. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2875. * that is also assigned to the $$hashKey property of the object.
  2876. *
  2877. * @param obj
  2878. * @returns {string} hash string such that the same input will have the same hash string.
  2879. * The resulting string key is in 'type:hashKey' format.
  2880. */
  2881. function hashKey(obj, nextUidFn) {
  2882. var key = obj && obj.$$hashKey;
  2883. if (key) {
  2884. if (typeof key === 'function') {
  2885. key = obj.$$hashKey();
  2886. }
  2887. return key;
  2888. }
  2889. var objType = typeof obj;
  2890. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2891. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2892. } else {
  2893. key = objType + ':' + obj;
  2894. }
  2895. return key;
  2896. }
  2897. /**
  2898. * HashMap which can use objects as keys
  2899. */
  2900. function HashMap(array, isolatedUid) {
  2901. if (isolatedUid) {
  2902. var uid = 0;
  2903. this.nextUid = function() {
  2904. return ++uid;
  2905. };
  2906. }
  2907. forEach(array, this.put, this);
  2908. }
  2909. HashMap.prototype = {
  2910. /**
  2911. * Store key value pair
  2912. * @param key key to store can be any type
  2913. * @param value value to store can be any type
  2914. */
  2915. put: function(key, value) {
  2916. this[hashKey(key, this.nextUid)] = value;
  2917. },
  2918. /**
  2919. * @param key
  2920. * @returns {Object} the value for the key
  2921. */
  2922. get: function(key) {
  2923. return this[hashKey(key, this.nextUid)];
  2924. },
  2925. /**
  2926. * Remove the key/value pair
  2927. * @param key
  2928. */
  2929. remove: function(key) {
  2930. var value = this[key = hashKey(key, this.nextUid)];
  2931. delete this[key];
  2932. return value;
  2933. }
  2934. };
  2935. /**
  2936. * @ngdoc function
  2937. * @module ng
  2938. * @name angular.injector
  2939. * @kind function
  2940. *
  2941. * @description
  2942. * Creates an injector object that can be used for retrieving services as well as for
  2943. * dependency injection (see {@link guide/di dependency injection}).
  2944. *
  2945. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2946. * {@link angular.module}. The `ng` module must be explicitly added.
  2947. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2948. *
  2949. * @example
  2950. * Typical usage
  2951. * ```js
  2952. * // create an injector
  2953. * var $injector = angular.injector(['ng']);
  2954. *
  2955. * // use the injector to kick off your application
  2956. * // use the type inference to auto inject arguments, or use implicit injection
  2957. * $injector.invoke(function($rootScope, $compile, $document) {
  2958. * $compile($document)($rootScope);
  2959. * $rootScope.$digest();
  2960. * });
  2961. * ```
  2962. *
  2963. * Sometimes you want to get access to the injector of a currently running Angular app
  2964. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2965. * application has been bootstrapped. You can do this using the extra `injector()` added
  2966. * to JQuery/jqLite elements. See {@link angular.element}.
  2967. *
  2968. * *This is fairly rare but could be the case if a third party library is injecting the
  2969. * markup.*
  2970. *
  2971. * In the following example a new block of HTML containing a `ng-controller`
  2972. * directive is added to the end of the document body by JQuery. We then compile and link
  2973. * it into the current AngularJS scope.
  2974. *
  2975. * ```js
  2976. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2977. * $(document.body).append($div);
  2978. *
  2979. * angular.element(document).injector().invoke(function($compile) {
  2980. * var scope = angular.element($div).scope();
  2981. * $compile($div)(scope);
  2982. * });
  2983. * ```
  2984. */
  2985. /**
  2986. * @ngdoc module
  2987. * @name auto
  2988. * @description
  2989. *
  2990. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2991. */
  2992. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2993. var FN_ARG_SPLIT = /,/;
  2994. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2995. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2996. var $injectorMinErr = minErr('$injector');
  2997. function anonFn(fn) {
  2998. // For anonymous functions, showing at the very least the function signature can help in
  2999. // debugging.
  3000. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3001. args = fnText.match(FN_ARGS);
  3002. if (args) {
  3003. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3004. }
  3005. return 'fn';
  3006. }
  3007. function annotate(fn, strictDi, name) {
  3008. var $inject,
  3009. fnText,
  3010. argDecl,
  3011. last;
  3012. if (typeof fn === 'function') {
  3013. if (!($inject = fn.$inject)) {
  3014. $inject = [];
  3015. if (fn.length) {
  3016. if (strictDi) {
  3017. if (!isString(name) || !name) {
  3018. name = fn.name || anonFn(fn);
  3019. }
  3020. throw $injectorMinErr('strictdi',
  3021. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3022. }
  3023. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3024. argDecl = fnText.match(FN_ARGS);
  3025. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3026. arg.replace(FN_ARG, function(all, underscore, name) {
  3027. $inject.push(name);
  3028. });
  3029. });
  3030. }
  3031. fn.$inject = $inject;
  3032. }
  3033. } else if (isArray(fn)) {
  3034. last = fn.length - 1;
  3035. assertArgFn(fn[last], 'fn');
  3036. $inject = fn.slice(0, last);
  3037. } else {
  3038. assertArgFn(fn, 'fn', true);
  3039. }
  3040. return $inject;
  3041. }
  3042. ///////////////////////////////////////
  3043. /**
  3044. * @ngdoc service
  3045. * @name $injector
  3046. *
  3047. * @description
  3048. *
  3049. * `$injector` is used to retrieve object instances as defined by
  3050. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3051. * and load modules.
  3052. *
  3053. * The following always holds true:
  3054. *
  3055. * ```js
  3056. * var $injector = angular.injector();
  3057. * expect($injector.get('$injector')).toBe($injector);
  3058. * expect($injector.invoke(function($injector) {
  3059. * return $injector;
  3060. * })).toBe($injector);
  3061. * ```
  3062. *
  3063. * # Injection Function Annotation
  3064. *
  3065. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3066. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3067. *
  3068. * ```js
  3069. * // inferred (only works if code not minified/obfuscated)
  3070. * $injector.invoke(function(serviceA){});
  3071. *
  3072. * // annotated
  3073. * function explicit(serviceA) {};
  3074. * explicit.$inject = ['serviceA'];
  3075. * $injector.invoke(explicit);
  3076. *
  3077. * // inline
  3078. * $injector.invoke(['serviceA', function(serviceA){}]);
  3079. * ```
  3080. *
  3081. * ## Inference
  3082. *
  3083. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3084. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  3085. * minification, and obfuscation tools since these tools change the argument names.
  3086. *
  3087. * ## `$inject` Annotation
  3088. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3089. *
  3090. * ## Inline
  3091. * As an array of injection names, where the last item in the array is the function to call.
  3092. */
  3093. /**
  3094. * @ngdoc method
  3095. * @name $injector#get
  3096. *
  3097. * @description
  3098. * Return an instance of the service.
  3099. *
  3100. * @param {string} name The name of the instance to retrieve.
  3101. * @return {*} The instance.
  3102. */
  3103. /**
  3104. * @ngdoc method
  3105. * @name $injector#invoke
  3106. *
  3107. * @description
  3108. * Invoke the method and supply the method arguments from the `$injector`.
  3109. *
  3110. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3111. * {@link guide/di $inject Annotation} rules.
  3112. * @param {Object=} self The `this` for the invoked method.
  3113. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3114. * object first, before the `$injector` is consulted.
  3115. * @returns {*} the value returned by the invoked `fn` function.
  3116. */
  3117. /**
  3118. * @ngdoc method
  3119. * @name $injector#has
  3120. *
  3121. * @description
  3122. * Allows the user to query if the particular service exists.
  3123. *
  3124. * @param {string} name Name of the service to query.
  3125. * @returns {boolean} `true` if injector has given service.
  3126. */
  3127. /**
  3128. * @ngdoc method
  3129. * @name $injector#instantiate
  3130. * @description
  3131. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3132. * operator, and supplies all of the arguments to the constructor function as specified by the
  3133. * constructor annotation.
  3134. *
  3135. * @param {Function} Type Annotated constructor function.
  3136. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3137. * object first, before the `$injector` is consulted.
  3138. * @returns {Object} new instance of `Type`.
  3139. */
  3140. /**
  3141. * @ngdoc method
  3142. * @name $injector#annotate
  3143. *
  3144. * @description
  3145. * Returns an array of service names which the function is requesting for injection. This API is
  3146. * used by the injector to determine which services need to be injected into the function when the
  3147. * function is invoked. There are three ways in which the function can be annotated with the needed
  3148. * dependencies.
  3149. *
  3150. * # Argument names
  3151. *
  3152. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3153. * by converting the function into a string using `toString()` method and extracting the argument
  3154. * names.
  3155. * ```js
  3156. * // Given
  3157. * function MyController($scope, $route) {
  3158. * // ...
  3159. * }
  3160. *
  3161. * // Then
  3162. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3163. * ```
  3164. *
  3165. * This method does not work with code minification / obfuscation. For this reason the following
  3166. * annotation strategies are supported.
  3167. *
  3168. * # The `$inject` property
  3169. *
  3170. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3171. * represent names of services to be injected into the function.
  3172. * ```js
  3173. * // Given
  3174. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3175. * // ...
  3176. * }
  3177. * // Define function dependencies
  3178. * MyController['$inject'] = ['$scope', '$route'];
  3179. *
  3180. * // Then
  3181. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3182. * ```
  3183. *
  3184. * # The array notation
  3185. *
  3186. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3187. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3188. * a way that survives minification is a better choice:
  3189. *
  3190. * ```js
  3191. * // We wish to write this (not minification / obfuscation safe)
  3192. * injector.invoke(function($compile, $rootScope) {
  3193. * // ...
  3194. * });
  3195. *
  3196. * // We are forced to write break inlining
  3197. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3198. * // ...
  3199. * };
  3200. * tmpFn.$inject = ['$compile', '$rootScope'];
  3201. * injector.invoke(tmpFn);
  3202. *
  3203. * // To better support inline function the inline annotation is supported
  3204. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3205. * // ...
  3206. * }]);
  3207. *
  3208. * // Therefore
  3209. * expect(injector.annotate(
  3210. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3211. * ).toEqual(['$compile', '$rootScope']);
  3212. * ```
  3213. *
  3214. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3215. * be retrieved as described above.
  3216. *
  3217. * @returns {Array.<string>} The names of the services which the function requires.
  3218. */
  3219. /**
  3220. * @ngdoc service
  3221. * @name $provide
  3222. *
  3223. * @description
  3224. *
  3225. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3226. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3227. * {@link angular.Module}.
  3228. *
  3229. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3230. * factories** are functions which, in turn, are created by a **service provider**.
  3231. * The **service providers** are constructor functions. When instantiated they must contain a
  3232. * property called `$get`, which holds the **service factory** function.
  3233. *
  3234. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3235. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3236. * function to get the instance of the **service**.
  3237. *
  3238. * Often services have no configuration options and there is no need to add methods to the service
  3239. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3240. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3241. * services without specifying a provider.
  3242. *
  3243. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3244. * {@link auto.$injector $injector}
  3245. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3246. * providers and services.
  3247. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3248. * services, not providers.
  3249. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3250. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3251. * given factory function.
  3252. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3253. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3254. * a new object using the given constructor function.
  3255. *
  3256. * See the individual methods for more information and examples.
  3257. */
  3258. /**
  3259. * @ngdoc method
  3260. * @name $provide#provider
  3261. * @description
  3262. *
  3263. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3264. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3265. * service.
  3266. *
  3267. * Service provider names start with the name of the service they provide followed by `Provider`.
  3268. * For example, the {@link ng.$log $log} service has a provider called
  3269. * {@link ng.$logProvider $logProvider}.
  3270. *
  3271. * Service provider objects can have additional methods which allow configuration of the provider
  3272. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3273. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3274. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3275. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3276. * console or not.
  3277. *
  3278. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3279. 'Provider'` key.
  3280. * @param {(Object|function())} provider If the provider is:
  3281. *
  3282. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3283. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3284. * - `Constructor`: a new instance of the provider will be created using
  3285. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3286. *
  3287. * @returns {Object} registered provider instance
  3288. * @example
  3289. *
  3290. * The following example shows how to create a simple event tracking service and register it using
  3291. * {@link auto.$provide#provider $provide.provider()}.
  3292. *
  3293. * ```js
  3294. * // Define the eventTracker provider
  3295. * function EventTrackerProvider() {
  3296. * var trackingUrl = '/track';
  3297. *
  3298. * // A provider method for configuring where the tracked events should been saved
  3299. * this.setTrackingUrl = function(url) {
  3300. * trackingUrl = url;
  3301. * };
  3302. *
  3303. * // The service factory function
  3304. * this.$get = ['$http', function($http) {
  3305. * var trackedEvents = {};
  3306. * return {
  3307. * // Call this to track an event
  3308. * event: function(event) {
  3309. * var count = trackedEvents[event] || 0;
  3310. * count += 1;
  3311. * trackedEvents[event] = count;
  3312. * return count;
  3313. * },
  3314. * // Call this to save the tracked events to the trackingUrl
  3315. * save: function() {
  3316. * $http.post(trackingUrl, trackedEvents);
  3317. * }
  3318. * };
  3319. * }];
  3320. * }
  3321. *
  3322. * describe('eventTracker', function() {
  3323. * var postSpy;
  3324. *
  3325. * beforeEach(module(function($provide) {
  3326. * // Register the eventTracker provider
  3327. * $provide.provider('eventTracker', EventTrackerProvider);
  3328. * }));
  3329. *
  3330. * beforeEach(module(function(eventTrackerProvider) {
  3331. * // Configure eventTracker provider
  3332. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3333. * }));
  3334. *
  3335. * it('tracks events', inject(function(eventTracker) {
  3336. * expect(eventTracker.event('login')).toEqual(1);
  3337. * expect(eventTracker.event('login')).toEqual(2);
  3338. * }));
  3339. *
  3340. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3341. * postSpy = spyOn($http, 'post');
  3342. * eventTracker.event('login');
  3343. * eventTracker.save();
  3344. * expect(postSpy).toHaveBeenCalled();
  3345. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3346. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3347. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3348. * }));
  3349. * });
  3350. * ```
  3351. */
  3352. /**
  3353. * @ngdoc method
  3354. * @name $provide#factory
  3355. * @description
  3356. *
  3357. * Register a **service factory**, which will be called to return the service instance.
  3358. * This is short for registering a service where its provider consists of only a `$get` property,
  3359. * which is the given service factory function.
  3360. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3361. * configure your service in a provider.
  3362. *
  3363. * @param {string} name The name of the instance.
  3364. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3365. * for `$provide.provider(name, {$get: $getFn})`.
  3366. * @returns {Object} registered provider instance
  3367. *
  3368. * @example
  3369. * Here is an example of registering a service
  3370. * ```js
  3371. * $provide.factory('ping', ['$http', function($http) {
  3372. * return function ping() {
  3373. * return $http.send('/ping');
  3374. * };
  3375. * }]);
  3376. * ```
  3377. * You would then inject and use this service like this:
  3378. * ```js
  3379. * someModule.controller('Ctrl', ['ping', function(ping) {
  3380. * ping();
  3381. * }]);
  3382. * ```
  3383. */
  3384. /**
  3385. * @ngdoc method
  3386. * @name $provide#service
  3387. * @description
  3388. *
  3389. * Register a **service constructor**, which will be invoked with `new` to create the service
  3390. * instance.
  3391. * This is short for registering a service where its provider's `$get` property is the service
  3392. * constructor function that will be used to instantiate the service instance.
  3393. *
  3394. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3395. * as a type/class.
  3396. *
  3397. * @param {string} name The name of the instance.
  3398. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3399. * @returns {Object} registered provider instance
  3400. *
  3401. * @example
  3402. * Here is an example of registering a service using
  3403. * {@link auto.$provide#service $provide.service(class)}.
  3404. * ```js
  3405. * var Ping = function($http) {
  3406. * this.$http = $http;
  3407. * };
  3408. *
  3409. * Ping.$inject = ['$http'];
  3410. *
  3411. * Ping.prototype.send = function() {
  3412. * return this.$http.get('/ping');
  3413. * };
  3414. * $provide.service('ping', Ping);
  3415. * ```
  3416. * You would then inject and use this service like this:
  3417. * ```js
  3418. * someModule.controller('Ctrl', ['ping', function(ping) {
  3419. * ping.send();
  3420. * }]);
  3421. * ```
  3422. */
  3423. /**
  3424. * @ngdoc method
  3425. * @name $provide#value
  3426. * @description
  3427. *
  3428. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3429. * number, an array, an object or a function. This is short for registering a service where its
  3430. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3431. * service**.
  3432. *
  3433. * Value services are similar to constant services, except that they cannot be injected into a
  3434. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3435. * an Angular
  3436. * {@link auto.$provide#decorator decorator}.
  3437. *
  3438. * @param {string} name The name of the instance.
  3439. * @param {*} value The value.
  3440. * @returns {Object} registered provider instance
  3441. *
  3442. * @example
  3443. * Here are some examples of creating value services.
  3444. * ```js
  3445. * $provide.value('ADMIN_USER', 'admin');
  3446. *
  3447. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3448. *
  3449. * $provide.value('halfOf', function(value) {
  3450. * return value / 2;
  3451. * });
  3452. * ```
  3453. */
  3454. /**
  3455. * @ngdoc method
  3456. * @name $provide#constant
  3457. * @description
  3458. *
  3459. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3460. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3461. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3462. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3463. *
  3464. * @param {string} name The name of the constant.
  3465. * @param {*} value The constant value.
  3466. * @returns {Object} registered instance
  3467. *
  3468. * @example
  3469. * Here a some examples of creating constants:
  3470. * ```js
  3471. * $provide.constant('SHARD_HEIGHT', 306);
  3472. *
  3473. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3474. *
  3475. * $provide.constant('double', function(value) {
  3476. * return value * 2;
  3477. * });
  3478. * ```
  3479. */
  3480. /**
  3481. * @ngdoc method
  3482. * @name $provide#decorator
  3483. * @description
  3484. *
  3485. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3486. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3487. * service. The object returned by the decorator may be the original service, or a new service
  3488. * object which replaces or wraps and delegates to the original service.
  3489. *
  3490. * @param {string} name The name of the service to decorate.
  3491. * @param {function()} decorator This function will be invoked when the service needs to be
  3492. * instantiated and should return the decorated service instance. The function is called using
  3493. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3494. * Local injection arguments:
  3495. *
  3496. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3497. * decorated or delegated to.
  3498. *
  3499. * @example
  3500. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3501. * calls to {@link ng.$log#error $log.warn()}.
  3502. * ```js
  3503. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3504. * $delegate.warn = $delegate.error;
  3505. * return $delegate;
  3506. * }]);
  3507. * ```
  3508. */
  3509. function createInjector(modulesToLoad, strictDi) {
  3510. strictDi = (strictDi === true);
  3511. var INSTANTIATING = {},
  3512. providerSuffix = 'Provider',
  3513. path = [],
  3514. loadedModules = new HashMap([], true),
  3515. providerCache = {
  3516. $provide: {
  3517. provider: supportObject(provider),
  3518. factory: supportObject(factory),
  3519. service: supportObject(service),
  3520. value: supportObject(value),
  3521. constant: supportObject(constant),
  3522. decorator: decorator
  3523. }
  3524. },
  3525. providerInjector = (providerCache.$injector =
  3526. createInternalInjector(providerCache, function() {
  3527. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3528. })),
  3529. instanceCache = {},
  3530. instanceInjector = (instanceCache.$injector =
  3531. createInternalInjector(instanceCache, function(servicename) {
  3532. var provider = providerInjector.get(servicename + providerSuffix);
  3533. return instanceInjector.invoke(provider.$get, provider, undefined, servicename);
  3534. }));
  3535. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3536. return instanceInjector;
  3537. ////////////////////////////////////
  3538. // $provider
  3539. ////////////////////////////////////
  3540. function supportObject(delegate) {
  3541. return function(key, value) {
  3542. if (isObject(key)) {
  3543. forEach(key, reverseParams(delegate));
  3544. } else {
  3545. return delegate(key, value);
  3546. }
  3547. };
  3548. }
  3549. function provider(name, provider_) {
  3550. assertNotHasOwnProperty(name, 'service');
  3551. if (isFunction(provider_) || isArray(provider_)) {
  3552. provider_ = providerInjector.instantiate(provider_);
  3553. }
  3554. if (!provider_.$get) {
  3555. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3556. }
  3557. return providerCache[name + providerSuffix] = provider_;
  3558. }
  3559. function enforceReturnValue(name, factory) {
  3560. return function enforcedReturnValue() {
  3561. var result = instanceInjector.invoke(factory, this, undefined, name);
  3562. if (isUndefined(result)) {
  3563. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3564. }
  3565. return result;
  3566. };
  3567. }
  3568. function factory(name, factoryFn, enforce) {
  3569. return provider(name, {
  3570. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3571. });
  3572. }
  3573. function service(name, constructor) {
  3574. return factory(name, ['$injector', function($injector) {
  3575. return $injector.instantiate(constructor);
  3576. }]);
  3577. }
  3578. function value(name, val) { return factory(name, valueFn(val), false); }
  3579. function constant(name, value) {
  3580. assertNotHasOwnProperty(name, 'constant');
  3581. providerCache[name] = value;
  3582. instanceCache[name] = value;
  3583. }
  3584. function decorator(serviceName, decorFn) {
  3585. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3586. orig$get = origProvider.$get;
  3587. origProvider.$get = function() {
  3588. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3589. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3590. };
  3591. }
  3592. ////////////////////////////////////
  3593. // Module Loading
  3594. ////////////////////////////////////
  3595. function loadModules(modulesToLoad) {
  3596. var runBlocks = [], moduleFn;
  3597. forEach(modulesToLoad, function(module) {
  3598. if (loadedModules.get(module)) return;
  3599. loadedModules.put(module, true);
  3600. function runInvokeQueue(queue) {
  3601. var i, ii;
  3602. for (i = 0, ii = queue.length; i < ii; i++) {
  3603. var invokeArgs = queue[i],
  3604. provider = providerInjector.get(invokeArgs[0]);
  3605. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3606. }
  3607. }
  3608. try {
  3609. if (isString(module)) {
  3610. moduleFn = angularModule(module);
  3611. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3612. runInvokeQueue(moduleFn._invokeQueue);
  3613. runInvokeQueue(moduleFn._configBlocks);
  3614. } else if (isFunction(module)) {
  3615. runBlocks.push(providerInjector.invoke(module));
  3616. } else if (isArray(module)) {
  3617. runBlocks.push(providerInjector.invoke(module));
  3618. } else {
  3619. assertArgFn(module, 'module');
  3620. }
  3621. } catch (e) {
  3622. if (isArray(module)) {
  3623. module = module[module.length - 1];
  3624. }
  3625. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3626. // Safari & FF's stack traces don't contain error.message content
  3627. // unlike those of Chrome and IE
  3628. // So if stack doesn't contain message, we create a new string that contains both.
  3629. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3630. /* jshint -W022 */
  3631. e = e.message + '\n' + e.stack;
  3632. }
  3633. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3634. module, e.stack || e.message || e);
  3635. }
  3636. });
  3637. return runBlocks;
  3638. }
  3639. ////////////////////////////////////
  3640. // internal Injector
  3641. ////////////////////////////////////
  3642. function createInternalInjector(cache, factory) {
  3643. function getService(serviceName) {
  3644. if (cache.hasOwnProperty(serviceName)) {
  3645. if (cache[serviceName] === INSTANTIATING) {
  3646. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3647. serviceName + ' <- ' + path.join(' <- '));
  3648. }
  3649. return cache[serviceName];
  3650. } else {
  3651. try {
  3652. path.unshift(serviceName);
  3653. cache[serviceName] = INSTANTIATING;
  3654. return cache[serviceName] = factory(serviceName);
  3655. } catch (err) {
  3656. if (cache[serviceName] === INSTANTIATING) {
  3657. delete cache[serviceName];
  3658. }
  3659. throw err;
  3660. } finally {
  3661. path.shift();
  3662. }
  3663. }
  3664. }
  3665. function invoke(fn, self, locals, serviceName) {
  3666. if (typeof locals === 'string') {
  3667. serviceName = locals;
  3668. locals = null;
  3669. }
  3670. var args = [],
  3671. $inject = annotate(fn, strictDi, serviceName),
  3672. length, i,
  3673. key;
  3674. for (i = 0, length = $inject.length; i < length; i++) {
  3675. key = $inject[i];
  3676. if (typeof key !== 'string') {
  3677. throw $injectorMinErr('itkn',
  3678. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3679. }
  3680. args.push(
  3681. locals && locals.hasOwnProperty(key)
  3682. ? locals[key]
  3683. : getService(key)
  3684. );
  3685. }
  3686. if (isArray(fn)) {
  3687. fn = fn[length];
  3688. }
  3689. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3690. // #5388
  3691. return fn.apply(self, args);
  3692. }
  3693. function instantiate(Type, locals, serviceName) {
  3694. var Constructor = function() {},
  3695. instance, returnedValue;
  3696. // Check if Type is annotated and use just the given function at n-1 as parameter
  3697. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3698. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3699. instance = new Constructor();
  3700. returnedValue = invoke(Type, instance, locals, serviceName);
  3701. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3702. }
  3703. return {
  3704. invoke: invoke,
  3705. instantiate: instantiate,
  3706. get: getService,
  3707. annotate: annotate,
  3708. has: function(name) {
  3709. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3710. }
  3711. };
  3712. }
  3713. }
  3714. createInjector.$$annotate = annotate;
  3715. /**
  3716. * @ngdoc provider
  3717. * @name $anchorScrollProvider
  3718. *
  3719. * @description
  3720. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3721. * {@link ng.$location#hash $location.hash()} changes.
  3722. */
  3723. function $AnchorScrollProvider() {
  3724. var autoScrollingEnabled = true;
  3725. /**
  3726. * @ngdoc method
  3727. * @name $anchorScrollProvider#disableAutoScrolling
  3728. *
  3729. * @description
  3730. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically will detect changes to
  3731. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3732. * Use this method to disable automatic scrolling.
  3733. *
  3734. * If automatic scrolling is disabled, one must explicitly call
  3735. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3736. * current hash.
  3737. */
  3738. this.disableAutoScrolling = function() {
  3739. autoScrollingEnabled = false;
  3740. };
  3741. /**
  3742. * @ngdoc service
  3743. * @name $anchorScroll
  3744. * @kind function
  3745. * @requires $window
  3746. * @requires $location
  3747. * @requires $rootScope
  3748. *
  3749. * @description
  3750. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3751. * scrolls to the related element, according to the rules specified in the
  3752. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3753. *
  3754. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3755. * match any anchor whenever it changes. This can be disabled by calling
  3756. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3757. *
  3758. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3759. * vertical scroll-offset (either fixed or dynamic).
  3760. *
  3761. * @property {(number|function|jqLite)} yOffset
  3762. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3763. * positioned elements at the top of the page, such as navbars, headers etc.
  3764. *
  3765. * `yOffset` can be specified in various ways:
  3766. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3767. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3768. * a number representing the offset (in pixels).<br /><br />
  3769. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3770. * the top of the page to the element's bottom will be used as offset.<br />
  3771. * **Note**: The element will be taken into account only as long as its `position` is set to
  3772. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3773. * their height and/or positioning according to the viewport's size.
  3774. *
  3775. * <br />
  3776. * <div class="alert alert-warning">
  3777. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3778. * not some child element.
  3779. * </div>
  3780. *
  3781. * @example
  3782. <example module="anchorScrollExample">
  3783. <file name="index.html">
  3784. <div id="scrollArea" ng-controller="ScrollController">
  3785. <a ng-click="gotoBottom()">Go to bottom</a>
  3786. <a id="bottom"></a> You're at the bottom!
  3787. </div>
  3788. </file>
  3789. <file name="script.js">
  3790. angular.module('anchorScrollExample', [])
  3791. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3792. function ($scope, $location, $anchorScroll) {
  3793. $scope.gotoBottom = function() {
  3794. // set the location.hash to the id of
  3795. // the element you wish to scroll to.
  3796. $location.hash('bottom');
  3797. // call $anchorScroll()
  3798. $anchorScroll();
  3799. };
  3800. }]);
  3801. </file>
  3802. <file name="style.css">
  3803. #scrollArea {
  3804. height: 280px;
  3805. overflow: auto;
  3806. }
  3807. #bottom {
  3808. display: block;
  3809. margin-top: 2000px;
  3810. }
  3811. </file>
  3812. </example>
  3813. *
  3814. * <hr />
  3815. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3816. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3817. *
  3818. * @example
  3819. <example module="anchorScrollOffsetExample">
  3820. <file name="index.html">
  3821. <div class="fixed-header" ng-controller="headerCtrl">
  3822. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3823. Go to anchor {{x}}
  3824. </a>
  3825. </div>
  3826. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3827. Anchor {{x}} of 5
  3828. </div>
  3829. </file>
  3830. <file name="script.js">
  3831. angular.module('anchorScrollOffsetExample', [])
  3832. .run(['$anchorScroll', function($anchorScroll) {
  3833. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3834. }])
  3835. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3836. function ($anchorScroll, $location, $scope) {
  3837. $scope.gotoAnchor = function(x) {
  3838. var newHash = 'anchor' + x;
  3839. if ($location.hash() !== newHash) {
  3840. // set the $location.hash to `newHash` and
  3841. // $anchorScroll will automatically scroll to it
  3842. $location.hash('anchor' + x);
  3843. } else {
  3844. // call $anchorScroll() explicitly,
  3845. // since $location.hash hasn't changed
  3846. $anchorScroll();
  3847. }
  3848. };
  3849. }
  3850. ]);
  3851. </file>
  3852. <file name="style.css">
  3853. body {
  3854. padding-top: 50px;
  3855. }
  3856. .anchor {
  3857. border: 2px dashed DarkOrchid;
  3858. padding: 10px 10px 200px 10px;
  3859. }
  3860. .fixed-header {
  3861. background-color: rgba(0, 0, 0, 0.2);
  3862. height: 50px;
  3863. position: fixed;
  3864. top: 0; left: 0; right: 0;
  3865. }
  3866. .fixed-header > a {
  3867. display: inline-block;
  3868. margin: 5px 15px;
  3869. }
  3870. </file>
  3871. </example>
  3872. */
  3873. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3874. var document = $window.document;
  3875. // Helper function to get first anchor from a NodeList
  3876. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3877. // and working in all supported browsers.)
  3878. function getFirstAnchor(list) {
  3879. var result = null;
  3880. Array.prototype.some.call(list, function(element) {
  3881. if (nodeName_(element) === 'a') {
  3882. result = element;
  3883. return true;
  3884. }
  3885. });
  3886. return result;
  3887. }
  3888. function getYOffset() {
  3889. var offset = scroll.yOffset;
  3890. if (isFunction(offset)) {
  3891. offset = offset();
  3892. } else if (isElement(offset)) {
  3893. var elem = offset[0];
  3894. var style = $window.getComputedStyle(elem);
  3895. if (style.position !== 'fixed') {
  3896. offset = 0;
  3897. } else {
  3898. offset = elem.getBoundingClientRect().bottom;
  3899. }
  3900. } else if (!isNumber(offset)) {
  3901. offset = 0;
  3902. }
  3903. return offset;
  3904. }
  3905. function scrollTo(elem) {
  3906. if (elem) {
  3907. elem.scrollIntoView();
  3908. var offset = getYOffset();
  3909. if (offset) {
  3910. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3911. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3912. // top of the viewport.
  3913. //
  3914. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3915. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3916. // way down the page.
  3917. //
  3918. // This is often the case for elements near the bottom of the page.
  3919. //
  3920. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3921. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3922. // desired position.
  3923. var elemTop = elem.getBoundingClientRect().top;
  3924. $window.scrollBy(0, elemTop - offset);
  3925. }
  3926. } else {
  3927. $window.scrollTo(0, 0);
  3928. }
  3929. }
  3930. function scroll() {
  3931. var hash = $location.hash(), elm;
  3932. // empty hash, scroll to the top of the page
  3933. if (!hash) scrollTo(null);
  3934. // element with given id
  3935. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  3936. // first anchor with given name :-D
  3937. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  3938. // no element and hash == 'top', scroll to the top of the page
  3939. else if (hash === 'top') scrollTo(null);
  3940. }
  3941. // does not scroll when user clicks on anchor link that is currently on
  3942. // (no url change, no $location.hash() change), browser native does scroll
  3943. if (autoScrollingEnabled) {
  3944. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3945. function autoScrollWatchAction(newVal, oldVal) {
  3946. // skip the initial scroll if $location.hash is empty
  3947. if (newVal === oldVal && newVal === '') return;
  3948. jqLiteDocumentLoaded(function() {
  3949. $rootScope.$evalAsync(scroll);
  3950. });
  3951. });
  3952. }
  3953. return scroll;
  3954. }];
  3955. }
  3956. var $animateMinErr = minErr('$animate');
  3957. /**
  3958. * @ngdoc provider
  3959. * @name $animateProvider
  3960. *
  3961. * @description
  3962. * Default implementation of $animate that doesn't perform any animations, instead just
  3963. * synchronously performs DOM
  3964. * updates and calls done() callbacks.
  3965. *
  3966. * In order to enable animations the ngAnimate module has to be loaded.
  3967. *
  3968. * To see the functional implementation check out src/ngAnimate/animate.js
  3969. */
  3970. var $AnimateProvider = ['$provide', function($provide) {
  3971. this.$$selectors = {};
  3972. /**
  3973. * @ngdoc method
  3974. * @name $animateProvider#register
  3975. *
  3976. * @description
  3977. * Registers a new injectable animation factory function. The factory function produces the
  3978. * animation object which contains callback functions for each event that is expected to be
  3979. * animated.
  3980. *
  3981. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3982. * must be called once the element animation is complete. If a function is returned then the
  3983. * animation service will use this function to cancel the animation whenever a cancel event is
  3984. * triggered.
  3985. *
  3986. *
  3987. * ```js
  3988. * return {
  3989. * eventFn : function(element, done) {
  3990. * //code to run the animation
  3991. * //once complete, then run done()
  3992. * return function cancellationFunction() {
  3993. * //code to cancel the animation
  3994. * }
  3995. * }
  3996. * }
  3997. * ```
  3998. *
  3999. * @param {string} name The name of the animation.
  4000. * @param {Function} factory The factory function that will be executed to return the animation
  4001. * object.
  4002. */
  4003. this.register = function(name, factory) {
  4004. var key = name + '-animation';
  4005. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4006. "Expecting class selector starting with '.' got '{0}'.", name);
  4007. this.$$selectors[name.substr(1)] = key;
  4008. $provide.factory(key, factory);
  4009. };
  4010. /**
  4011. * @ngdoc method
  4012. * @name $animateProvider#classNameFilter
  4013. *
  4014. * @description
  4015. * Sets and/or returns the CSS class regular expression that is checked when performing
  4016. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4017. * therefore enable $animate to attempt to perform an animation on any element.
  4018. * When setting the classNameFilter value, animations will only be performed on elements
  4019. * that successfully match the filter expression. This in turn can boost performance
  4020. * for low-powered devices as well as applications containing a lot of structural operations.
  4021. * @param {RegExp=} expression The className expression which will be checked against all animations
  4022. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4023. */
  4024. this.classNameFilter = function(expression) {
  4025. if (arguments.length === 1) {
  4026. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4027. }
  4028. return this.$$classNameFilter;
  4029. };
  4030. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4031. var currentDefer;
  4032. function runAnimationPostDigest(fn) {
  4033. var cancelFn, defer = $$q.defer();
  4034. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4035. cancelFn && cancelFn();
  4036. };
  4037. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4038. cancelFn = fn(function ngAnimateNotifyComplete() {
  4039. defer.resolve();
  4040. });
  4041. });
  4042. return defer.promise;
  4043. }
  4044. function resolveElementClasses(element, classes) {
  4045. var toAdd = [], toRemove = [];
  4046. var hasClasses = createMap();
  4047. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4048. hasClasses[className] = true;
  4049. });
  4050. forEach(classes, function(status, className) {
  4051. var hasClass = hasClasses[className];
  4052. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4053. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4054. // the most recent class manipulation (via $animate) was to add the class, and the
  4055. // element does not currently have the class, the class is scheduled to be added.
  4056. if (status === false && hasClass) {
  4057. toRemove.push(className);
  4058. } else if (status === true && !hasClass) {
  4059. toAdd.push(className);
  4060. }
  4061. });
  4062. return (toAdd.length + toRemove.length) > 0 &&
  4063. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4064. }
  4065. function cachedClassManipulation(cache, classes, op) {
  4066. for (var i=0, ii = classes.length; i < ii; ++i) {
  4067. var className = classes[i];
  4068. cache[className] = op;
  4069. }
  4070. }
  4071. function asyncPromise() {
  4072. // only serve one instance of a promise in order to save CPU cycles
  4073. if (!currentDefer) {
  4074. currentDefer = $$q.defer();
  4075. $$asyncCallback(function() {
  4076. currentDefer.resolve();
  4077. currentDefer = null;
  4078. });
  4079. }
  4080. return currentDefer.promise;
  4081. }
  4082. function applyStyles(element, options) {
  4083. if (angular.isObject(options)) {
  4084. var styles = extend(options.from || {}, options.to || {});
  4085. element.css(styles);
  4086. }
  4087. }
  4088. /**
  4089. *
  4090. * @ngdoc service
  4091. * @name $animate
  4092. * @description The $animate service provides rudimentary DOM manipulation functions to
  4093. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4094. * This service is the core service used by the ngAnimate $animator service which provides
  4095. * high-level animation hooks for CSS and JavaScript.
  4096. *
  4097. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4098. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4099. * manipulation operations.
  4100. *
  4101. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4102. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4103. * page}.
  4104. */
  4105. return {
  4106. animate: function(element, from, to) {
  4107. applyStyles(element, { from: from, to: to });
  4108. return asyncPromise();
  4109. },
  4110. /**
  4111. *
  4112. * @ngdoc method
  4113. * @name $animate#enter
  4114. * @kind function
  4115. * @description Inserts the element into the DOM either after the `after` element or
  4116. * as the first child within the `parent` element. When the function is called a promise
  4117. * is returned that will be resolved at a later time.
  4118. * @param {DOMElement} element the element which will be inserted into the DOM
  4119. * @param {DOMElement} parent the parent element which will append the element as
  4120. * a child (if the after element is not present)
  4121. * @param {DOMElement} after the sibling element which will append the element
  4122. * after itself
  4123. * @param {object=} options an optional collection of styles that will be applied to the element.
  4124. * @return {Promise} the animation callback promise
  4125. */
  4126. enter: function(element, parent, after, options) {
  4127. applyStyles(element, options);
  4128. after ? after.after(element)
  4129. : parent.prepend(element);
  4130. return asyncPromise();
  4131. },
  4132. /**
  4133. *
  4134. * @ngdoc method
  4135. * @name $animate#leave
  4136. * @kind function
  4137. * @description Removes the element from the DOM. When the function is called a promise
  4138. * is returned that will be resolved at a later time.
  4139. * @param {DOMElement} element the element which will be removed from the DOM
  4140. * @param {object=} options an optional collection of options that will be applied to the element.
  4141. * @return {Promise} the animation callback promise
  4142. */
  4143. leave: function(element, options) {
  4144. element.remove();
  4145. return asyncPromise();
  4146. },
  4147. /**
  4148. *
  4149. * @ngdoc method
  4150. * @name $animate#move
  4151. * @kind function
  4152. * @description Moves the position of the provided element within the DOM to be placed
  4153. * either after the `after` element or inside of the `parent` element. When the function
  4154. * is called a promise is returned that will be resolved at a later time.
  4155. *
  4156. * @param {DOMElement} element the element which will be moved around within the
  4157. * DOM
  4158. * @param {DOMElement} parent the parent element where the element will be
  4159. * inserted into (if the after element is not present)
  4160. * @param {DOMElement} after the sibling element where the element will be
  4161. * positioned next to
  4162. * @param {object=} options an optional collection of options that will be applied to the element.
  4163. * @return {Promise} the animation callback promise
  4164. */
  4165. move: function(element, parent, after, options) {
  4166. // Do not remove element before insert. Removing will cause data associated with the
  4167. // element to be dropped. Insert will implicitly do the remove.
  4168. return this.enter(element, parent, after, options);
  4169. },
  4170. /**
  4171. *
  4172. * @ngdoc method
  4173. * @name $animate#addClass
  4174. * @kind function
  4175. * @description Adds the provided className CSS class value to the provided element.
  4176. * When the function is called a promise is returned that will be resolved at a later time.
  4177. * @param {DOMElement} element the element which will have the className value
  4178. * added to it
  4179. * @param {string} className the CSS class which will be added to the element
  4180. * @param {object=} options an optional collection of options that will be applied to the element.
  4181. * @return {Promise} the animation callback promise
  4182. */
  4183. addClass: function(element, className, options) {
  4184. return this.setClass(element, className, [], options);
  4185. },
  4186. $$addClassImmediately: function(element, className, options) {
  4187. element = jqLite(element);
  4188. className = !isString(className)
  4189. ? (isArray(className) ? className.join(' ') : '')
  4190. : className;
  4191. forEach(element, function(element) {
  4192. jqLiteAddClass(element, className);
  4193. });
  4194. applyStyles(element, options);
  4195. return asyncPromise();
  4196. },
  4197. /**
  4198. *
  4199. * @ngdoc method
  4200. * @name $animate#removeClass
  4201. * @kind function
  4202. * @description Removes the provided className CSS class value from the provided element.
  4203. * When the function is called a promise is returned that will be resolved at a later time.
  4204. * @param {DOMElement} element the element which will have the className value
  4205. * removed from it
  4206. * @param {string} className the CSS class which will be removed from the element
  4207. * @param {object=} options an optional collection of options that will be applied to the element.
  4208. * @return {Promise} the animation callback promise
  4209. */
  4210. removeClass: function(element, className, options) {
  4211. return this.setClass(element, [], className, options);
  4212. },
  4213. $$removeClassImmediately: function(element, className, options) {
  4214. element = jqLite(element);
  4215. className = !isString(className)
  4216. ? (isArray(className) ? className.join(' ') : '')
  4217. : className;
  4218. forEach(element, function(element) {
  4219. jqLiteRemoveClass(element, className);
  4220. });
  4221. applyStyles(element, options);
  4222. return asyncPromise();
  4223. },
  4224. /**
  4225. *
  4226. * @ngdoc method
  4227. * @name $animate#setClass
  4228. * @kind function
  4229. * @description Adds and/or removes the given CSS classes to and from the element.
  4230. * When the function is called a promise is returned that will be resolved at a later time.
  4231. * @param {DOMElement} element the element which will have its CSS classes changed
  4232. * removed from it
  4233. * @param {string} add the CSS classes which will be added to the element
  4234. * @param {string} remove the CSS class which will be removed from the element
  4235. * @param {object=} options an optional collection of options that will be applied to the element.
  4236. * @return {Promise} the animation callback promise
  4237. */
  4238. setClass: function(element, add, remove, options) {
  4239. var self = this;
  4240. var STORAGE_KEY = '$$animateClasses';
  4241. var createdCache = false;
  4242. element = jqLite(element);
  4243. var cache = element.data(STORAGE_KEY);
  4244. if (!cache) {
  4245. cache = {
  4246. classes: {},
  4247. options: options
  4248. };
  4249. createdCache = true;
  4250. } else if (options && cache.options) {
  4251. cache.options = angular.extend(cache.options || {}, options);
  4252. }
  4253. var classes = cache.classes;
  4254. add = isArray(add) ? add : add.split(' ');
  4255. remove = isArray(remove) ? remove : remove.split(' ');
  4256. cachedClassManipulation(classes, add, true);
  4257. cachedClassManipulation(classes, remove, false);
  4258. if (createdCache) {
  4259. cache.promise = runAnimationPostDigest(function(done) {
  4260. var cache = element.data(STORAGE_KEY);
  4261. element.removeData(STORAGE_KEY);
  4262. // in the event that the element is removed before postDigest
  4263. // is run then the cache will be undefined and there will be
  4264. // no need anymore to add or remove and of the element classes
  4265. if (cache) {
  4266. var classes = resolveElementClasses(element, cache.classes);
  4267. if (classes) {
  4268. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4269. }
  4270. }
  4271. done();
  4272. });
  4273. element.data(STORAGE_KEY, cache);
  4274. }
  4275. return cache.promise;
  4276. },
  4277. $$setClassImmediately: function(element, add, remove, options) {
  4278. add && this.$$addClassImmediately(element, add);
  4279. remove && this.$$removeClassImmediately(element, remove);
  4280. applyStyles(element, options);
  4281. return asyncPromise();
  4282. },
  4283. enabled: noop,
  4284. cancel: noop
  4285. };
  4286. }];
  4287. }];
  4288. function $$AsyncCallbackProvider() {
  4289. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4290. return $$rAF.supported
  4291. ? function(fn) { return $$rAF(fn); }
  4292. : function(fn) {
  4293. return $timeout(fn, 0, false);
  4294. };
  4295. }];
  4296. }
  4297. /* global stripHash: true */
  4298. /**
  4299. * ! This is a private undocumented service !
  4300. *
  4301. * @name $browser
  4302. * @requires $log
  4303. * @description
  4304. * This object has two goals:
  4305. *
  4306. * - hide all the global state in the browser caused by the window object
  4307. * - abstract away all the browser specific features and inconsistencies
  4308. *
  4309. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4310. * service, which can be used for convenient testing of the application without the interaction with
  4311. * the real browser apis.
  4312. */
  4313. /**
  4314. * @param {object} window The global window object.
  4315. * @param {object} document jQuery wrapped document.
  4316. * @param {function()} XHR XMLHttpRequest constructor.
  4317. * @param {object} $log console.log or an object with the same interface.
  4318. * @param {object} $sniffer $sniffer service
  4319. */
  4320. function Browser(window, document, $log, $sniffer) {
  4321. var self = this,
  4322. rawDocument = document[0],
  4323. location = window.location,
  4324. history = window.history,
  4325. setTimeout = window.setTimeout,
  4326. clearTimeout = window.clearTimeout,
  4327. pendingDeferIds = {};
  4328. self.isMock = false;
  4329. var outstandingRequestCount = 0;
  4330. var outstandingRequestCallbacks = [];
  4331. // TODO(vojta): remove this temporary api
  4332. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4333. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4334. /**
  4335. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4336. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4337. */
  4338. function completeOutstandingRequest(fn) {
  4339. try {
  4340. fn.apply(null, sliceArgs(arguments, 1));
  4341. } finally {
  4342. outstandingRequestCount--;
  4343. if (outstandingRequestCount === 0) {
  4344. while (outstandingRequestCallbacks.length) {
  4345. try {
  4346. outstandingRequestCallbacks.pop()();
  4347. } catch (e) {
  4348. $log.error(e);
  4349. }
  4350. }
  4351. }
  4352. }
  4353. }
  4354. /**
  4355. * @private
  4356. * Note: this method is used only by scenario runner
  4357. * TODO(vojta): prefix this method with $$ ?
  4358. * @param {function()} callback Function that will be called when no outstanding request
  4359. */
  4360. self.notifyWhenNoOutstandingRequests = function(callback) {
  4361. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4362. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4363. // regular poller would result in flaky tests.
  4364. forEach(pollFns, function(pollFn) { pollFn(); });
  4365. if (outstandingRequestCount === 0) {
  4366. callback();
  4367. } else {
  4368. outstandingRequestCallbacks.push(callback);
  4369. }
  4370. };
  4371. //////////////////////////////////////////////////////////////
  4372. // Poll Watcher API
  4373. //////////////////////////////////////////////////////////////
  4374. var pollFns = [],
  4375. pollTimeout;
  4376. /**
  4377. * @name $browser#addPollFn
  4378. *
  4379. * @param {function()} fn Poll function to add
  4380. *
  4381. * @description
  4382. * Adds a function to the list of functions that poller periodically executes,
  4383. * and starts polling if not started yet.
  4384. *
  4385. * @returns {function()} the added function
  4386. */
  4387. self.addPollFn = function(fn) {
  4388. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4389. pollFns.push(fn);
  4390. return fn;
  4391. };
  4392. /**
  4393. * @param {number} interval How often should browser call poll functions (ms)
  4394. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4395. *
  4396. * @description
  4397. * Configures the poller to run in the specified intervals, using the specified
  4398. * setTimeout fn and kicks it off.
  4399. */
  4400. function startPoller(interval, setTimeout) {
  4401. (function check() {
  4402. forEach(pollFns, function(pollFn) { pollFn(); });
  4403. pollTimeout = setTimeout(check, interval);
  4404. })();
  4405. }
  4406. //////////////////////////////////////////////////////////////
  4407. // URL API
  4408. //////////////////////////////////////////////////////////////
  4409. var cachedState, lastHistoryState,
  4410. lastBrowserUrl = location.href,
  4411. baseElement = document.find('base'),
  4412. reloadLocation = null;
  4413. cacheState();
  4414. lastHistoryState = cachedState;
  4415. /**
  4416. * @name $browser#url
  4417. *
  4418. * @description
  4419. * GETTER:
  4420. * Without any argument, this method just returns current value of location.href.
  4421. *
  4422. * SETTER:
  4423. * With at least one argument, this method sets url to new value.
  4424. * If html5 history api supported, pushState/replaceState is used, otherwise
  4425. * location.href/location.replace is used.
  4426. * Returns its own instance to allow chaining
  4427. *
  4428. * NOTE: this api is intended for use only by the $location service. Please use the
  4429. * {@link ng.$location $location service} to change url.
  4430. *
  4431. * @param {string} url New url (when used as setter)
  4432. * @param {boolean=} replace Should new url replace current history record?
  4433. * @param {object=} state object to use with pushState/replaceState
  4434. */
  4435. self.url = function(url, replace, state) {
  4436. // In modern browsers `history.state` is `null` by default; treating it separately
  4437. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4438. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4439. if (isUndefined(state)) {
  4440. state = null;
  4441. }
  4442. // Android Browser BFCache causes location, history reference to become stale.
  4443. if (location !== window.location) location = window.location;
  4444. if (history !== window.history) history = window.history;
  4445. // setter
  4446. if (url) {
  4447. var sameState = lastHistoryState === state;
  4448. // Don't change anything if previous and current URLs and states match. This also prevents
  4449. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4450. // See https://github.com/angular/angular.js/commit/ffb2701
  4451. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4452. return;
  4453. }
  4454. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4455. lastBrowserUrl = url;
  4456. lastHistoryState = state;
  4457. // Don't use history API if only the hash changed
  4458. // due to a bug in IE10/IE11 which leads
  4459. // to not firing a `hashchange` nor `popstate` event
  4460. // in some cases (see #9143).
  4461. if ($sniffer.history && (!sameBase || !sameState)) {
  4462. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4463. cacheState();
  4464. // Do the assignment again so that those two variables are referentially identical.
  4465. lastHistoryState = cachedState;
  4466. } else {
  4467. if (!sameBase) {
  4468. reloadLocation = url;
  4469. }
  4470. if (replace) {
  4471. location.replace(url);
  4472. } else {
  4473. location.href = url;
  4474. }
  4475. }
  4476. return self;
  4477. // getter
  4478. } else {
  4479. // - reloadLocation is needed as browsers don't allow to read out
  4480. // the new location.href if a reload happened.
  4481. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4482. return reloadLocation || location.href.replace(/%27/g,"'");
  4483. }
  4484. };
  4485. /**
  4486. * @name $browser#state
  4487. *
  4488. * @description
  4489. * This method is a getter.
  4490. *
  4491. * Return history.state or null if history.state is undefined.
  4492. *
  4493. * @returns {object} state
  4494. */
  4495. self.state = function() {
  4496. return cachedState;
  4497. };
  4498. var urlChangeListeners = [],
  4499. urlChangeInit = false;
  4500. function cacheStateAndFireUrlChange() {
  4501. cacheState();
  4502. fireUrlChange();
  4503. }
  4504. // This variable should be used *only* inside the cacheState function.
  4505. var lastCachedState = null;
  4506. function cacheState() {
  4507. // This should be the only place in $browser where `history.state` is read.
  4508. cachedState = window.history.state;
  4509. cachedState = isUndefined(cachedState) ? null : cachedState;
  4510. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4511. if (equals(cachedState, lastCachedState)) {
  4512. cachedState = lastCachedState;
  4513. }
  4514. lastCachedState = cachedState;
  4515. }
  4516. function fireUrlChange() {
  4517. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4518. return;
  4519. }
  4520. lastBrowserUrl = self.url();
  4521. lastHistoryState = cachedState;
  4522. forEach(urlChangeListeners, function(listener) {
  4523. listener(self.url(), cachedState);
  4524. });
  4525. }
  4526. /**
  4527. * @name $browser#onUrlChange
  4528. *
  4529. * @description
  4530. * Register callback function that will be called, when url changes.
  4531. *
  4532. * It's only called when the url is changed from outside of angular:
  4533. * - user types different url into address bar
  4534. * - user clicks on history (forward/back) button
  4535. * - user clicks on a link
  4536. *
  4537. * It's not called when url is changed by $browser.url() method
  4538. *
  4539. * The listener gets called with new url as parameter.
  4540. *
  4541. * NOTE: this api is intended for use only by the $location service. Please use the
  4542. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4543. *
  4544. * @param {function(string)} listener Listener function to be called when url changes.
  4545. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4546. */
  4547. self.onUrlChange = function(callback) {
  4548. // TODO(vojta): refactor to use node's syntax for events
  4549. if (!urlChangeInit) {
  4550. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4551. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4552. // changed by push/replaceState
  4553. // html5 history api - popstate event
  4554. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4555. // hashchange event
  4556. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4557. urlChangeInit = true;
  4558. }
  4559. urlChangeListeners.push(callback);
  4560. return callback;
  4561. };
  4562. /**
  4563. * Checks whether the url has changed outside of Angular.
  4564. * Needs to be exported to be able to check for changes that have been done in sync,
  4565. * as hashchange/popstate events fire in async.
  4566. */
  4567. self.$$checkUrlChange = fireUrlChange;
  4568. //////////////////////////////////////////////////////////////
  4569. // Misc API
  4570. //////////////////////////////////////////////////////////////
  4571. /**
  4572. * @name $browser#baseHref
  4573. *
  4574. * @description
  4575. * Returns current <base href>
  4576. * (always relative - without domain)
  4577. *
  4578. * @returns {string} The current base href
  4579. */
  4580. self.baseHref = function() {
  4581. var href = baseElement.attr('href');
  4582. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4583. };
  4584. //////////////////////////////////////////////////////////////
  4585. // Cookies API
  4586. //////////////////////////////////////////////////////////////
  4587. var lastCookies = {};
  4588. var lastCookieString = '';
  4589. var cookiePath = self.baseHref();
  4590. function safeDecodeURIComponent(str) {
  4591. try {
  4592. return decodeURIComponent(str);
  4593. } catch (e) {
  4594. return str;
  4595. }
  4596. }
  4597. /**
  4598. * @name $browser#cookies
  4599. *
  4600. * @param {string=} name Cookie name
  4601. * @param {string=} value Cookie value
  4602. *
  4603. * @description
  4604. * The cookies method provides a 'private' low level access to browser cookies.
  4605. * It is not meant to be used directly, use the $cookie service instead.
  4606. *
  4607. * The return values vary depending on the arguments that the method was called with as follows:
  4608. *
  4609. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4610. * it
  4611. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4612. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4613. * way)
  4614. *
  4615. * @returns {Object} Hash of all cookies (if called without any parameter)
  4616. */
  4617. self.cookies = function(name, value) {
  4618. var cookieLength, cookieArray, cookie, i, index;
  4619. if (name) {
  4620. if (value === undefined) {
  4621. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4622. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4623. } else {
  4624. if (isString(value)) {
  4625. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4626. ';path=' + cookiePath).length + 1;
  4627. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4628. // - 300 cookies
  4629. // - 20 cookies per unique domain
  4630. // - 4096 bytes per cookie
  4631. if (cookieLength > 4096) {
  4632. $log.warn("Cookie '"+ name +
  4633. "' possibly not set or overflowed because it was too large ("+
  4634. cookieLength + " > 4096 bytes)!");
  4635. }
  4636. }
  4637. }
  4638. } else {
  4639. if (rawDocument.cookie !== lastCookieString) {
  4640. lastCookieString = rawDocument.cookie;
  4641. cookieArray = lastCookieString.split("; ");
  4642. lastCookies = {};
  4643. for (i = 0; i < cookieArray.length; i++) {
  4644. cookie = cookieArray[i];
  4645. index = cookie.indexOf('=');
  4646. if (index > 0) { //ignore nameless cookies
  4647. name = safeDecodeURIComponent(cookie.substring(0, index));
  4648. // the first value that is seen for a cookie is the most
  4649. // specific one. values for the same cookie name that
  4650. // follow are for less specific paths.
  4651. if (lastCookies[name] === undefined) {
  4652. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4653. }
  4654. }
  4655. }
  4656. }
  4657. return lastCookies;
  4658. }
  4659. };
  4660. /**
  4661. * @name $browser#defer
  4662. * @param {function()} fn A function, who's execution should be deferred.
  4663. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4664. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4665. *
  4666. * @description
  4667. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4668. *
  4669. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4670. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4671. * via `$browser.defer.flush()`.
  4672. *
  4673. */
  4674. self.defer = function(fn, delay) {
  4675. var timeoutId;
  4676. outstandingRequestCount++;
  4677. timeoutId = setTimeout(function() {
  4678. delete pendingDeferIds[timeoutId];
  4679. completeOutstandingRequest(fn);
  4680. }, delay || 0);
  4681. pendingDeferIds[timeoutId] = true;
  4682. return timeoutId;
  4683. };
  4684. /**
  4685. * @name $browser#defer.cancel
  4686. *
  4687. * @description
  4688. * Cancels a deferred task identified with `deferId`.
  4689. *
  4690. * @param {*} deferId Token returned by the `$browser.defer` function.
  4691. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4692. * canceled.
  4693. */
  4694. self.defer.cancel = function(deferId) {
  4695. if (pendingDeferIds[deferId]) {
  4696. delete pendingDeferIds[deferId];
  4697. clearTimeout(deferId);
  4698. completeOutstandingRequest(noop);
  4699. return true;
  4700. }
  4701. return false;
  4702. };
  4703. }
  4704. function $BrowserProvider() {
  4705. this.$get = ['$window', '$log', '$sniffer', '$document',
  4706. function($window, $log, $sniffer, $document) {
  4707. return new Browser($window, $document, $log, $sniffer);
  4708. }];
  4709. }
  4710. /**
  4711. * @ngdoc service
  4712. * @name $cacheFactory
  4713. *
  4714. * @description
  4715. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4716. * them.
  4717. *
  4718. * ```js
  4719. *
  4720. * var cache = $cacheFactory('cacheId');
  4721. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4722. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4723. *
  4724. * cache.put("key", "value");
  4725. * cache.put("another key", "another value");
  4726. *
  4727. * // We've specified no options on creation
  4728. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4729. *
  4730. * ```
  4731. *
  4732. *
  4733. * @param {string} cacheId Name or id of the newly created cache.
  4734. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4735. *
  4736. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4737. *
  4738. * @returns {object} Newly created cache object with the following set of methods:
  4739. *
  4740. * - `{object}` `info()` — Returns id, size, and options of cache.
  4741. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4742. * it.
  4743. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4744. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4745. * - `{void}` `removeAll()` — Removes all cached values.
  4746. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4747. *
  4748. * @example
  4749. <example module="cacheExampleApp">
  4750. <file name="index.html">
  4751. <div ng-controller="CacheController">
  4752. <input ng-model="newCacheKey" placeholder="Key">
  4753. <input ng-model="newCacheValue" placeholder="Value">
  4754. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4755. <p ng-if="keys.length">Cached Values</p>
  4756. <div ng-repeat="key in keys">
  4757. <span ng-bind="key"></span>
  4758. <span>: </span>
  4759. <b ng-bind="cache.get(key)"></b>
  4760. </div>
  4761. <p>Cache Info</p>
  4762. <div ng-repeat="(key, value) in cache.info()">
  4763. <span ng-bind="key"></span>
  4764. <span>: </span>
  4765. <b ng-bind="value"></b>
  4766. </div>
  4767. </div>
  4768. </file>
  4769. <file name="script.js">
  4770. angular.module('cacheExampleApp', []).
  4771. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4772. $scope.keys = [];
  4773. $scope.cache = $cacheFactory('cacheId');
  4774. $scope.put = function(key, value) {
  4775. if ($scope.cache.get(key) === undefined) {
  4776. $scope.keys.push(key);
  4777. }
  4778. $scope.cache.put(key, value === undefined ? null : value);
  4779. };
  4780. }]);
  4781. </file>
  4782. <file name="style.css">
  4783. p {
  4784. margin: 10px 0 3px;
  4785. }
  4786. </file>
  4787. </example>
  4788. */
  4789. function $CacheFactoryProvider() {
  4790. this.$get = function() {
  4791. var caches = {};
  4792. function cacheFactory(cacheId, options) {
  4793. if (cacheId in caches) {
  4794. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4795. }
  4796. var size = 0,
  4797. stats = extend({}, options, {id: cacheId}),
  4798. data = {},
  4799. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4800. lruHash = {},
  4801. freshEnd = null,
  4802. staleEnd = null;
  4803. /**
  4804. * @ngdoc type
  4805. * @name $cacheFactory.Cache
  4806. *
  4807. * @description
  4808. * A cache object used to store and retrieve data, primarily used by
  4809. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4810. * templates and other data.
  4811. *
  4812. * ```js
  4813. * angular.module('superCache')
  4814. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4815. * return $cacheFactory('super-cache');
  4816. * }]);
  4817. * ```
  4818. *
  4819. * Example test:
  4820. *
  4821. * ```js
  4822. * it('should behave like a cache', inject(function(superCache) {
  4823. * superCache.put('key', 'value');
  4824. * superCache.put('another key', 'another value');
  4825. *
  4826. * expect(superCache.info()).toEqual({
  4827. * id: 'super-cache',
  4828. * size: 2
  4829. * });
  4830. *
  4831. * superCache.remove('another key');
  4832. * expect(superCache.get('another key')).toBeUndefined();
  4833. *
  4834. * superCache.removeAll();
  4835. * expect(superCache.info()).toEqual({
  4836. * id: 'super-cache',
  4837. * size: 0
  4838. * });
  4839. * }));
  4840. * ```
  4841. */
  4842. return caches[cacheId] = {
  4843. /**
  4844. * @ngdoc method
  4845. * @name $cacheFactory.Cache#put
  4846. * @kind function
  4847. *
  4848. * @description
  4849. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4850. * retrieved later, and incrementing the size of the cache if the key was not already
  4851. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4852. * entries from the set.
  4853. *
  4854. * It will not insert undefined values into the cache.
  4855. *
  4856. * @param {string} key the key under which the cached data is stored.
  4857. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4858. * will not be stored.
  4859. * @returns {*} the value stored.
  4860. */
  4861. put: function(key, value) {
  4862. if (capacity < Number.MAX_VALUE) {
  4863. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4864. refresh(lruEntry);
  4865. }
  4866. if (isUndefined(value)) return;
  4867. if (!(key in data)) size++;
  4868. data[key] = value;
  4869. if (size > capacity) {
  4870. this.remove(staleEnd.key);
  4871. }
  4872. return value;
  4873. },
  4874. /**
  4875. * @ngdoc method
  4876. * @name $cacheFactory.Cache#get
  4877. * @kind function
  4878. *
  4879. * @description
  4880. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4881. *
  4882. * @param {string} key the key of the data to be retrieved
  4883. * @returns {*} the value stored.
  4884. */
  4885. get: function(key) {
  4886. if (capacity < Number.MAX_VALUE) {
  4887. var lruEntry = lruHash[key];
  4888. if (!lruEntry) return;
  4889. refresh(lruEntry);
  4890. }
  4891. return data[key];
  4892. },
  4893. /**
  4894. * @ngdoc method
  4895. * @name $cacheFactory.Cache#remove
  4896. * @kind function
  4897. *
  4898. * @description
  4899. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4900. *
  4901. * @param {string} key the key of the entry to be removed
  4902. */
  4903. remove: function(key) {
  4904. if (capacity < Number.MAX_VALUE) {
  4905. var lruEntry = lruHash[key];
  4906. if (!lruEntry) return;
  4907. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4908. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4909. link(lruEntry.n,lruEntry.p);
  4910. delete lruHash[key];
  4911. }
  4912. delete data[key];
  4913. size--;
  4914. },
  4915. /**
  4916. * @ngdoc method
  4917. * @name $cacheFactory.Cache#removeAll
  4918. * @kind function
  4919. *
  4920. * @description
  4921. * Clears the cache object of any entries.
  4922. */
  4923. removeAll: function() {
  4924. data = {};
  4925. size = 0;
  4926. lruHash = {};
  4927. freshEnd = staleEnd = null;
  4928. },
  4929. /**
  4930. * @ngdoc method
  4931. * @name $cacheFactory.Cache#destroy
  4932. * @kind function
  4933. *
  4934. * @description
  4935. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4936. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4937. */
  4938. destroy: function() {
  4939. data = null;
  4940. stats = null;
  4941. lruHash = null;
  4942. delete caches[cacheId];
  4943. },
  4944. /**
  4945. * @ngdoc method
  4946. * @name $cacheFactory.Cache#info
  4947. * @kind function
  4948. *
  4949. * @description
  4950. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4951. *
  4952. * @returns {object} an object with the following properties:
  4953. * <ul>
  4954. * <li>**id**: the id of the cache instance</li>
  4955. * <li>**size**: the number of entries kept in the cache instance</li>
  4956. * <li>**...**: any additional properties from the options object when creating the
  4957. * cache.</li>
  4958. * </ul>
  4959. */
  4960. info: function() {
  4961. return extend({}, stats, {size: size});
  4962. }
  4963. };
  4964. /**
  4965. * makes the `entry` the freshEnd of the LRU linked list
  4966. */
  4967. function refresh(entry) {
  4968. if (entry != freshEnd) {
  4969. if (!staleEnd) {
  4970. staleEnd = entry;
  4971. } else if (staleEnd == entry) {
  4972. staleEnd = entry.n;
  4973. }
  4974. link(entry.n, entry.p);
  4975. link(entry, freshEnd);
  4976. freshEnd = entry;
  4977. freshEnd.n = null;
  4978. }
  4979. }
  4980. /**
  4981. * bidirectionally links two entries of the LRU linked list
  4982. */
  4983. function link(nextEntry, prevEntry) {
  4984. if (nextEntry != prevEntry) {
  4985. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4986. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4987. }
  4988. }
  4989. }
  4990. /**
  4991. * @ngdoc method
  4992. * @name $cacheFactory#info
  4993. *
  4994. * @description
  4995. * Get information about all the caches that have been created
  4996. *
  4997. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4998. */
  4999. cacheFactory.info = function() {
  5000. var info = {};
  5001. forEach(caches, function(cache, cacheId) {
  5002. info[cacheId] = cache.info();
  5003. });
  5004. return info;
  5005. };
  5006. /**
  5007. * @ngdoc method
  5008. * @name $cacheFactory#get
  5009. *
  5010. * @description
  5011. * Get access to a cache object by the `cacheId` used when it was created.
  5012. *
  5013. * @param {string} cacheId Name or id of a cache to access.
  5014. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5015. */
  5016. cacheFactory.get = function(cacheId) {
  5017. return caches[cacheId];
  5018. };
  5019. return cacheFactory;
  5020. };
  5021. }
  5022. /**
  5023. * @ngdoc service
  5024. * @name $templateCache
  5025. *
  5026. * @description
  5027. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5028. * can load templates directly into the cache in a `script` tag, or by consuming the
  5029. * `$templateCache` service directly.
  5030. *
  5031. * Adding via the `script` tag:
  5032. *
  5033. * ```html
  5034. * <script type="text/ng-template" id="templateId.html">
  5035. * <p>This is the content of the template</p>
  5036. * </script>
  5037. * ```
  5038. *
  5039. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5040. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5041. * element with ng-app attribute), otherwise the template will be ignored.
  5042. *
  5043. * Adding via the $templateCache service:
  5044. *
  5045. * ```js
  5046. * var myApp = angular.module('myApp', []);
  5047. * myApp.run(function($templateCache) {
  5048. * $templateCache.put('templateId.html', 'This is the content of the template');
  5049. * });
  5050. * ```
  5051. *
  5052. * To retrieve the template later, simply use it in your HTML:
  5053. * ```html
  5054. * <div ng-include=" 'templateId.html' "></div>
  5055. * ```
  5056. *
  5057. * or get it via Javascript:
  5058. * ```js
  5059. * $templateCache.get('templateId.html')
  5060. * ```
  5061. *
  5062. * See {@link ng.$cacheFactory $cacheFactory}.
  5063. *
  5064. */
  5065. function $TemplateCacheProvider() {
  5066. this.$get = ['$cacheFactory', function($cacheFactory) {
  5067. return $cacheFactory('templates');
  5068. }];
  5069. }
  5070. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5071. *
  5072. * DOM-related variables:
  5073. *
  5074. * - "node" - DOM Node
  5075. * - "element" - DOM Element or Node
  5076. * - "$node" or "$element" - jqLite-wrapped node or element
  5077. *
  5078. *
  5079. * Compiler related stuff:
  5080. *
  5081. * - "linkFn" - linking fn of a single directive
  5082. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5083. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5084. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5085. */
  5086. /**
  5087. * @ngdoc service
  5088. * @name $compile
  5089. * @kind function
  5090. *
  5091. * @description
  5092. * Compiles an HTML string or DOM into a template and produces a template function, which
  5093. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5094. *
  5095. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5096. * {@link ng.$compileProvider#directive directives}.
  5097. *
  5098. * <div class="alert alert-warning">
  5099. * **Note:** This document is an in-depth reference of all directive options.
  5100. * For a gentle introduction to directives with examples of common use cases,
  5101. * see the {@link guide/directive directive guide}.
  5102. * </div>
  5103. *
  5104. * ## Comprehensive Directive API
  5105. *
  5106. * There are many different options for a directive.
  5107. *
  5108. * The difference resides in the return value of the factory function.
  5109. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5110. * or just the `postLink` function (all other properties will have the default values).
  5111. *
  5112. * <div class="alert alert-success">
  5113. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5114. * </div>
  5115. *
  5116. * Here's an example directive declared with a Directive Definition Object:
  5117. *
  5118. * ```js
  5119. * var myModule = angular.module(...);
  5120. *
  5121. * myModule.directive('directiveName', function factory(injectables) {
  5122. * var directiveDefinitionObject = {
  5123. * priority: 0,
  5124. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5125. * // or
  5126. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5127. * transclude: false,
  5128. * restrict: 'A',
  5129. * templateNamespace: 'html',
  5130. * scope: false,
  5131. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5132. * controllerAs: 'stringAlias',
  5133. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5134. * compile: function compile(tElement, tAttrs, transclude) {
  5135. * return {
  5136. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5137. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5138. * }
  5139. * // or
  5140. * // return function postLink( ... ) { ... }
  5141. * },
  5142. * // or
  5143. * // link: {
  5144. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5145. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5146. * // }
  5147. * // or
  5148. * // link: function postLink( ... ) { ... }
  5149. * };
  5150. * return directiveDefinitionObject;
  5151. * });
  5152. * ```
  5153. *
  5154. * <div class="alert alert-warning">
  5155. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5156. * </div>
  5157. *
  5158. * Therefore the above can be simplified as:
  5159. *
  5160. * ```js
  5161. * var myModule = angular.module(...);
  5162. *
  5163. * myModule.directive('directiveName', function factory(injectables) {
  5164. * var directiveDefinitionObject = {
  5165. * link: function postLink(scope, iElement, iAttrs) { ... }
  5166. * };
  5167. * return directiveDefinitionObject;
  5168. * // or
  5169. * // return function postLink(scope, iElement, iAttrs) { ... }
  5170. * });
  5171. * ```
  5172. *
  5173. *
  5174. *
  5175. * ### Directive Definition Object
  5176. *
  5177. * The directive definition object provides instructions to the {@link ng.$compile
  5178. * compiler}. The attributes are:
  5179. *
  5180. * #### `multiElement`
  5181. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5182. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5183. * together as the directive elements. It is recomended that this feature be used on directives
  5184. * which are not strictly behavioural (such as {@link ngClick}), and which
  5185. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5186. *
  5187. * #### `priority`
  5188. * When there are multiple directives defined on a single DOM element, sometimes it
  5189. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5190. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5191. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5192. * are also run in priority order, but post-link functions are run in reverse order. The order
  5193. * of directives with the same priority is undefined. The default priority is `0`.
  5194. *
  5195. * #### `terminal`
  5196. * If set to true then the current `priority` will be the last set of directives
  5197. * which will execute (any directives at the current priority will still execute
  5198. * as the order of execution on same `priority` is undefined). Note that expressions
  5199. * and other directives used in the directive's template will also be excluded from execution.
  5200. *
  5201. * #### `scope`
  5202. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5203. * same element request a new scope, only one new scope is created. The new scope rule does not
  5204. * apply for the root of the template since the root of the template always gets a new scope.
  5205. *
  5206. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5207. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5208. * when creating reusable components, which should not accidentally read or modify data in the
  5209. * parent scope.
  5210. *
  5211. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5212. * derived from the parent scope. These local properties are useful for aliasing values for
  5213. * templates. Locals definition is a hash of local scope property to its source:
  5214. *
  5215. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5216. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5217. * attribute name is assumed to be the same as the local name.
  5218. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5219. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5220. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5221. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5222. * component scope).
  5223. *
  5224. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5225. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5226. * name is specified then the attribute name is assumed to be the same as the local name.
  5227. * Given `<widget my-attr="parentModel">` and widget definition of
  5228. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5229. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5230. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5231. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5232. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5233. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5234. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5235. *
  5236. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5237. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5238. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5239. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5240. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5241. * pass data from the isolated scope via an expression to the parent scope, this can be
  5242. * done by passing a map of local variable names and values into the expression wrapper fn.
  5243. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5244. * by calling the `localFn` as `localFn({amount: 22})`.
  5245. *
  5246. *
  5247. * #### `bindToController`
  5248. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController` will
  5249. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5250. * is instantiated, the initial values of the isolate scope bindings are already available.
  5251. *
  5252. * #### `controller`
  5253. * Controller constructor function. The controller is instantiated before the
  5254. * pre-linking phase and it is shared with other directives (see
  5255. * `require` attribute). This allows the directives to communicate with each other and augment
  5256. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5257. *
  5258. * * `$scope` - Current scope associated with the element
  5259. * * `$element` - Current element
  5260. * * `$attrs` - Current attributes object for the element
  5261. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5262. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5263. * * `scope`: optional argument to override the scope.
  5264. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5265. * * `futureParentElement`:
  5266. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5267. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5268. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5269. * and when the `cloneLinkinFn` is passed,
  5270. * as those elements need to created and cloned in a special way when they are defined outside their
  5271. * usual containers (e.g. like `<svg>`).
  5272. * * See also the `directive.templateNamespace` property.
  5273. *
  5274. *
  5275. * #### `require`
  5276. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5277. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5278. * injected argument will be an array in corresponding order. If no such directive can be
  5279. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  5280. *
  5281. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5282. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5283. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5284. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5285. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5286. * `null` to the `link` fn if not found.
  5287. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5288. * `null` to the `link` fn if not found.
  5289. *
  5290. *
  5291. * #### `controllerAs`
  5292. * Controller alias at the directive scope. An alias for the controller so it
  5293. * can be referenced at the directive template. The directive needs to define a scope for this
  5294. * configuration to be used. Useful in the case when directive is used as component.
  5295. *
  5296. *
  5297. * #### `restrict`
  5298. * String of subset of `EACM` which restricts the directive to a specific directive
  5299. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5300. *
  5301. * * `E` - Element name (default): `<my-directive></my-directive>`
  5302. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5303. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5304. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5305. *
  5306. *
  5307. * #### `templateNamespace`
  5308. * String representing the document type used by the markup in the template.
  5309. * AngularJS needs this information as those elements need to be created and cloned
  5310. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5311. *
  5312. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5313. * top-level elements such as `<svg>` or `<math>`.
  5314. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5315. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5316. *
  5317. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5318. *
  5319. * #### `template`
  5320. * HTML markup that may:
  5321. * * Replace the contents of the directive's element (default).
  5322. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5323. * * Wrap the contents of the directive's element (if `transclude` is true).
  5324. *
  5325. * Value may be:
  5326. *
  5327. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5328. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5329. * function api below) and returns a string value.
  5330. *
  5331. *
  5332. * #### `templateUrl`
  5333. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5334. *
  5335. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5336. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5337. * sibling and parent elements as though this element had not contained any directives.
  5338. *
  5339. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5340. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5341. * case when only one deeply nested directive has `templateUrl`.
  5342. *
  5343. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5344. *
  5345. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5346. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5347. * a string value representing the url. In either case, the template URL is passed through {@link
  5348. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5349. *
  5350. *
  5351. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5352. * specify what the template should replace. Defaults to `false`.
  5353. *
  5354. * * `true` - the template will replace the directive's element.
  5355. * * `false` - the template will replace the contents of the directive's element.
  5356. *
  5357. * The replacement process migrates all of the attributes / classes from the old element to the new
  5358. * one. See the {@link guide/directive#template-expanding-directive
  5359. * Directives Guide} for an example.
  5360. *
  5361. * There are very few scenarios where element replacement is required for the application function,
  5362. * the main one being reusable custom components that are used within SVG contexts
  5363. * (because SVG doesn't work with custom elements in the DOM tree).
  5364. *
  5365. * #### `transclude`
  5366. * Extract the contents of the element where the directive appears and make it available to the directive.
  5367. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5368. * {@link $compile#transclusion Transclusion} section below.
  5369. *
  5370. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5371. * directive's element or the entire element:
  5372. *
  5373. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5374. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5375. * element that defined at a lower priority than this directive. When used, the `template`
  5376. * property is ignored.
  5377. *
  5378. *
  5379. * #### `compile`
  5380. *
  5381. * ```js
  5382. * function compile(tElement, tAttrs, transclude) { ... }
  5383. * ```
  5384. *
  5385. * The compile function deals with transforming the template DOM. Since most directives do not do
  5386. * template transformation, it is not used often. The compile function takes the following arguments:
  5387. *
  5388. * * `tElement` - template element - The element where the directive has been declared. It is
  5389. * safe to do template transformation on the element and child elements only.
  5390. *
  5391. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5392. * between all directive compile functions.
  5393. *
  5394. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5395. *
  5396. * <div class="alert alert-warning">
  5397. * **Note:** The template instance and the link instance may be different objects if the template has
  5398. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5399. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5400. * should be done in a linking function rather than in a compile function.
  5401. * </div>
  5402. * <div class="alert alert-warning">
  5403. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5404. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5405. * stack overflow errors.
  5406. *
  5407. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5408. * a directive's template instead of relying on automatic template compilation via `template` or
  5409. * `templateUrl` declaration or manual compilation inside the compile function.
  5410. * </div>
  5411. *
  5412. * <div class="alert alert-error">
  5413. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5414. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5415. * to the link function instead.
  5416. * </div>
  5417. * A compile function can have a return value which can be either a function or an object.
  5418. *
  5419. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5420. * `link` property of the config object when the compile function is empty.
  5421. *
  5422. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5423. * control when a linking function should be called during the linking phase. See info about
  5424. * pre-linking and post-linking functions below.
  5425. *
  5426. *
  5427. * #### `link`
  5428. * This property is used only if the `compile` property is not defined.
  5429. *
  5430. * ```js
  5431. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5432. * ```
  5433. *
  5434. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5435. * executed after the template has been cloned. This is where most of the directive logic will be
  5436. * put.
  5437. *
  5438. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5439. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5440. *
  5441. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5442. * manipulate the children of the element only in `postLink` function since the children have
  5443. * already been linked.
  5444. *
  5445. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5446. * between all directive linking functions.
  5447. *
  5448. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5449. * element defines a controller. The controller is shared among all the directives, which allows
  5450. * the directives to use the controllers as a communication channel.
  5451. *
  5452. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5453. * This is the same as the `$transclude`
  5454. * parameter of directive controllers, see there for details.
  5455. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5456. *
  5457. * #### Pre-linking function
  5458. *
  5459. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5460. * compiler linking function will fail to locate the correct elements for linking.
  5461. *
  5462. * #### Post-linking function
  5463. *
  5464. * Executed after the child elements are linked.
  5465. *
  5466. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5467. * and linked since they are waiting for their template to load asynchronously and their own
  5468. * compilation and linking has been suspended until that occurs.
  5469. *
  5470. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5471. * for their async templates to be resolved.
  5472. *
  5473. *
  5474. * ### Transclusion
  5475. *
  5476. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5477. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5478. * scope from where they were taken.
  5479. *
  5480. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5481. * original contents of a directive's element into a specified place in the template of the directive.
  5482. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5483. * content has access to the properties on the scope from which it was taken, even if the directive
  5484. * has isolated scope.
  5485. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5486. *
  5487. * This makes it possible for the widget to have private state for its template, while the transcluded
  5488. * content has access to its originating scope.
  5489. *
  5490. * <div class="alert alert-warning">
  5491. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5492. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5493. * Testing Transclusion Directives}.
  5494. * </div>
  5495. *
  5496. * #### Transclusion Functions
  5497. *
  5498. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5499. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5500. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5501. *
  5502. * <div class="alert alert-info">
  5503. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5504. * ngTransclude will deal with it for us.
  5505. * </div>
  5506. *
  5507. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5508. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5509. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5510. *
  5511. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5512. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5513. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5514. *
  5515. * <div class="alert alert-info">
  5516. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5517. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5518. * </div>
  5519. *
  5520. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5521. * attach function**:
  5522. *
  5523. * ```js
  5524. * var transcludedContent, transclusionScope;
  5525. *
  5526. * $transclude(function(clone, scope) {
  5527. * element.append(clone);
  5528. * transcludedContent = clone;
  5529. * transclusionScope = scope;
  5530. * });
  5531. * ```
  5532. *
  5533. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5534. * associated transclusion scope:
  5535. *
  5536. * ```js
  5537. * transcludedContent.remove();
  5538. * transclusionScope.$destroy();
  5539. * ```
  5540. *
  5541. * <div class="alert alert-info">
  5542. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5543. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5544. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5545. * </div>
  5546. *
  5547. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5548. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5549. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5550. *
  5551. *
  5552. * #### Transclusion Scopes
  5553. *
  5554. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5555. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5556. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5557. * was taken.
  5558. *
  5559. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5560. * like this:
  5561. *
  5562. * ```html
  5563. * <div ng-app>
  5564. * <div isolate>
  5565. * <div transclusion>
  5566. * </div>
  5567. * </div>
  5568. * </div>
  5569. * ```
  5570. *
  5571. * The `$parent` scope hierarchy will look like this:
  5572. *
  5573. * ```
  5574. * - $rootScope
  5575. * - isolate
  5576. * - transclusion
  5577. * ```
  5578. *
  5579. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5580. *
  5581. * ```
  5582. * - $rootScope
  5583. * - transclusion
  5584. * - isolate
  5585. * ```
  5586. *
  5587. *
  5588. * ### Attributes
  5589. *
  5590. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5591. * `link()` or `compile()` functions. It has a variety of uses.
  5592. *
  5593. * accessing *Normalized attribute names:*
  5594. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5595. * the attributes object allows for normalized access to
  5596. * the attributes.
  5597. *
  5598. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5599. * object which allows the directives to use the attributes object as inter directive
  5600. * communication.
  5601. *
  5602. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5603. * allowing other directives to read the interpolated value.
  5604. *
  5605. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5606. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5607. * the only way to easily get the actual value because during the linking phase the interpolation
  5608. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5609. *
  5610. * ```js
  5611. * function linkingFn(scope, elm, attrs, ctrl) {
  5612. * // get the attribute value
  5613. * console.log(attrs.ngModel);
  5614. *
  5615. * // change the attribute
  5616. * attrs.$set('ngModel', 'new value');
  5617. *
  5618. * // observe changes to interpolated attribute
  5619. * attrs.$observe('ngModel', function(value) {
  5620. * console.log('ngModel has changed value to ' + value);
  5621. * });
  5622. * }
  5623. * ```
  5624. *
  5625. * ## Example
  5626. *
  5627. * <div class="alert alert-warning">
  5628. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5629. * to illustrate how `$compile` works.
  5630. * </div>
  5631. *
  5632. <example module="compileExample">
  5633. <file name="index.html">
  5634. <script>
  5635. angular.module('compileExample', [], function($compileProvider) {
  5636. // configure new 'compile' directive by passing a directive
  5637. // factory function. The factory function injects the '$compile'
  5638. $compileProvider.directive('compile', function($compile) {
  5639. // directive factory creates a link function
  5640. return function(scope, element, attrs) {
  5641. scope.$watch(
  5642. function(scope) {
  5643. // watch the 'compile' expression for changes
  5644. return scope.$eval(attrs.compile);
  5645. },
  5646. function(value) {
  5647. // when the 'compile' expression changes
  5648. // assign it into the current DOM
  5649. element.html(value);
  5650. // compile the new DOM and link it to the current
  5651. // scope.
  5652. // NOTE: we only compile .childNodes so that
  5653. // we don't get into infinite loop compiling ourselves
  5654. $compile(element.contents())(scope);
  5655. }
  5656. );
  5657. };
  5658. });
  5659. })
  5660. .controller('GreeterController', ['$scope', function($scope) {
  5661. $scope.name = 'Angular';
  5662. $scope.html = 'Hello {{name}}';
  5663. }]);
  5664. </script>
  5665. <div ng-controller="GreeterController">
  5666. <input ng-model="name"> <br>
  5667. <textarea ng-model="html"></textarea> <br>
  5668. <div compile="html"></div>
  5669. </div>
  5670. </file>
  5671. <file name="protractor.js" type="protractor">
  5672. it('should auto compile', function() {
  5673. var textarea = $('textarea');
  5674. var output = $('div[compile]');
  5675. // The initial state reads 'Hello Angular'.
  5676. expect(output.getText()).toBe('Hello Angular');
  5677. textarea.clear();
  5678. textarea.sendKeys('{{name}}!');
  5679. expect(output.getText()).toBe('Angular!');
  5680. });
  5681. </file>
  5682. </example>
  5683. *
  5684. *
  5685. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5686. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  5687. *
  5688. * <div class="alert alert-error">
  5689. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  5690. * e.g. will not use the right outer scope. Please pass the transclude function as a
  5691. * `parentBoundTranscludeFn` to the link function instead.
  5692. * </div>
  5693. *
  5694. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5695. * root element(s), not their children)
  5696. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  5697. * (a DOM element/tree) to a scope. Where:
  5698. *
  5699. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5700. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5701. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5702. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5703. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5704. *
  5705. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5706. * * `scope` - is the current scope with which the linking function is working with.
  5707. *
  5708. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  5709. * keys may be used to control linking behavior:
  5710. *
  5711. * * `parentBoundTranscludeFn` - the transclude function made available to
  5712. * directives; if given, it will be passed through to the link functions of
  5713. * directives found in `element` during compilation.
  5714. * * `transcludeControllers` - an object hash with keys that map controller names
  5715. * to controller instances; if given, it will make the controllers
  5716. * available to directives.
  5717. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  5718. * the cloned elements; only needed for transcludes that are allowed to contain non html
  5719. * elements (e.g. SVG elements). See also the directive.controller property.
  5720. *
  5721. * Calling the linking function returns the element of the template. It is either the original
  5722. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5723. *
  5724. * After linking the view is not updated until after a call to $digest which typically is done by
  5725. * Angular automatically.
  5726. *
  5727. * If you need access to the bound view, there are two ways to do it:
  5728. *
  5729. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5730. * before you send them to the compiler and keep this reference around.
  5731. * ```js
  5732. * var element = $compile('<p>{{total}}</p>')(scope);
  5733. * ```
  5734. *
  5735. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5736. * example would not point to the clone, but rather to the original template that was cloned. In
  5737. * this case, you can access the clone via the cloneAttachFn:
  5738. * ```js
  5739. * var templateElement = angular.element('<p>{{total}}</p>'),
  5740. * scope = ....;
  5741. *
  5742. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5743. * //attach the clone to DOM document at the right place
  5744. * });
  5745. *
  5746. * //now we have reference to the cloned DOM via `clonedElement`
  5747. * ```
  5748. *
  5749. *
  5750. * For information on how the compiler works, see the
  5751. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5752. */
  5753. var $compileMinErr = minErr('$compile');
  5754. /**
  5755. * @ngdoc provider
  5756. * @name $compileProvider
  5757. *
  5758. * @description
  5759. */
  5760. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5761. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5762. var hasDirectives = {},
  5763. Suffix = 'Directive',
  5764. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  5765. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  5766. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5767. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5768. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5769. // The assumption is that future DOM event attribute names will begin with
  5770. // 'on' and be composed of only English letters.
  5771. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5772. function parseIsolateBindings(scope, directiveName) {
  5773. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  5774. var bindings = {};
  5775. forEach(scope, function(definition, scopeName) {
  5776. var match = definition.match(LOCAL_REGEXP);
  5777. if (!match) {
  5778. throw $compileMinErr('iscp',
  5779. "Invalid isolate scope definition for directive '{0}'." +
  5780. " Definition: {... {1}: '{2}' ...}",
  5781. directiveName, scopeName, definition);
  5782. }
  5783. bindings[scopeName] = {
  5784. mode: match[1][0],
  5785. collection: match[2] === '*',
  5786. optional: match[3] === '?',
  5787. attrName: match[4] || scopeName
  5788. };
  5789. });
  5790. return bindings;
  5791. }
  5792. /**
  5793. * @ngdoc method
  5794. * @name $compileProvider#directive
  5795. * @kind function
  5796. *
  5797. * @description
  5798. * Register a new directive with the compiler.
  5799. *
  5800. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5801. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5802. * names and the values are the factories.
  5803. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5804. * {@link guide/directive} for more info.
  5805. * @returns {ng.$compileProvider} Self for chaining.
  5806. */
  5807. this.directive = function registerDirective(name, directiveFactory) {
  5808. assertNotHasOwnProperty(name, 'directive');
  5809. if (isString(name)) {
  5810. assertArg(directiveFactory, 'directiveFactory');
  5811. if (!hasDirectives.hasOwnProperty(name)) {
  5812. hasDirectives[name] = [];
  5813. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5814. function($injector, $exceptionHandler) {
  5815. var directives = [];
  5816. forEach(hasDirectives[name], function(directiveFactory, index) {
  5817. try {
  5818. var directive = $injector.invoke(directiveFactory);
  5819. if (isFunction(directive)) {
  5820. directive = { compile: valueFn(directive) };
  5821. } else if (!directive.compile && directive.link) {
  5822. directive.compile = valueFn(directive.link);
  5823. }
  5824. directive.priority = directive.priority || 0;
  5825. directive.index = index;
  5826. directive.name = directive.name || name;
  5827. directive.require = directive.require || (directive.controller && directive.name);
  5828. directive.restrict = directive.restrict || 'EA';
  5829. if (isObject(directive.scope)) {
  5830. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5831. }
  5832. directives.push(directive);
  5833. } catch (e) {
  5834. $exceptionHandler(e);
  5835. }
  5836. });
  5837. return directives;
  5838. }]);
  5839. }
  5840. hasDirectives[name].push(directiveFactory);
  5841. } else {
  5842. forEach(name, reverseParams(registerDirective));
  5843. }
  5844. return this;
  5845. };
  5846. /**
  5847. * @ngdoc method
  5848. * @name $compileProvider#aHrefSanitizationWhitelist
  5849. * @kind function
  5850. *
  5851. * @description
  5852. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5853. * urls during a[href] sanitization.
  5854. *
  5855. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5856. *
  5857. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5858. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5859. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5860. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5861. *
  5862. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5863. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5864. * chaining otherwise.
  5865. */
  5866. this.aHrefSanitizationWhitelist = function(regexp) {
  5867. if (isDefined(regexp)) {
  5868. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5869. return this;
  5870. } else {
  5871. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5872. }
  5873. };
  5874. /**
  5875. * @ngdoc method
  5876. * @name $compileProvider#imgSrcSanitizationWhitelist
  5877. * @kind function
  5878. *
  5879. * @description
  5880. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5881. * urls during img[src] sanitization.
  5882. *
  5883. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5884. *
  5885. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5886. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5887. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5888. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5889. *
  5890. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5891. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5892. * chaining otherwise.
  5893. */
  5894. this.imgSrcSanitizationWhitelist = function(regexp) {
  5895. if (isDefined(regexp)) {
  5896. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5897. return this;
  5898. } else {
  5899. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5900. }
  5901. };
  5902. /**
  5903. * @ngdoc method
  5904. * @name $compileProvider#debugInfoEnabled
  5905. *
  5906. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  5907. * current debugInfoEnabled state
  5908. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  5909. *
  5910. * @kind function
  5911. *
  5912. * @description
  5913. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  5914. * binding information and a reference to the current scope on to DOM elements.
  5915. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  5916. * * `ng-binding` CSS class
  5917. * * `$binding` data property containing an array of the binding expressions
  5918. *
  5919. * You may want to use this in production for a significant performance boost. See
  5920. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  5921. *
  5922. * The default value is true.
  5923. */
  5924. var debugInfoEnabled = true;
  5925. this.debugInfoEnabled = function(enabled) {
  5926. if (isDefined(enabled)) {
  5927. debugInfoEnabled = enabled;
  5928. return this;
  5929. }
  5930. return debugInfoEnabled;
  5931. };
  5932. this.$get = [
  5933. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  5934. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5935. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  5936. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5937. var Attributes = function(element, attributesToCopy) {
  5938. if (attributesToCopy) {
  5939. var keys = Object.keys(attributesToCopy);
  5940. var i, l, key;
  5941. for (i = 0, l = keys.length; i < l; i++) {
  5942. key = keys[i];
  5943. this[key] = attributesToCopy[key];
  5944. }
  5945. } else {
  5946. this.$attr = {};
  5947. }
  5948. this.$$element = element;
  5949. };
  5950. Attributes.prototype = {
  5951. $normalize: directiveNormalize,
  5952. /**
  5953. * @ngdoc method
  5954. * @name $compile.directive.Attributes#$addClass
  5955. * @kind function
  5956. *
  5957. * @description
  5958. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5959. * are enabled then an animation will be triggered for the class addition.
  5960. *
  5961. * @param {string} classVal The className value that will be added to the element
  5962. */
  5963. $addClass: function(classVal) {
  5964. if (classVal && classVal.length > 0) {
  5965. $animate.addClass(this.$$element, classVal);
  5966. }
  5967. },
  5968. /**
  5969. * @ngdoc method
  5970. * @name $compile.directive.Attributes#$removeClass
  5971. * @kind function
  5972. *
  5973. * @description
  5974. * Removes the CSS class value specified by the classVal parameter from the element. If
  5975. * animations are enabled then an animation will be triggered for the class removal.
  5976. *
  5977. * @param {string} classVal The className value that will be removed from the element
  5978. */
  5979. $removeClass: function(classVal) {
  5980. if (classVal && classVal.length > 0) {
  5981. $animate.removeClass(this.$$element, classVal);
  5982. }
  5983. },
  5984. /**
  5985. * @ngdoc method
  5986. * @name $compile.directive.Attributes#$updateClass
  5987. * @kind function
  5988. *
  5989. * @description
  5990. * Adds and removes the appropriate CSS class values to the element based on the difference
  5991. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5992. *
  5993. * @param {string} newClasses The current CSS className value
  5994. * @param {string} oldClasses The former CSS className value
  5995. */
  5996. $updateClass: function(newClasses, oldClasses) {
  5997. var toAdd = tokenDifference(newClasses, oldClasses);
  5998. if (toAdd && toAdd.length) {
  5999. $animate.addClass(this.$$element, toAdd);
  6000. }
  6001. var toRemove = tokenDifference(oldClasses, newClasses);
  6002. if (toRemove && toRemove.length) {
  6003. $animate.removeClass(this.$$element, toRemove);
  6004. }
  6005. },
  6006. /**
  6007. * Set a normalized attribute on the element in a way such that all directives
  6008. * can share the attribute. This function properly handles boolean attributes.
  6009. * @param {string} key Normalized key. (ie ngAttribute)
  6010. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6011. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6012. * Defaults to true.
  6013. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6014. */
  6015. $set: function(key, value, writeAttr, attrName) {
  6016. // TODO: decide whether or not to throw an error if "class"
  6017. //is set through this function since it may cause $updateClass to
  6018. //become unstable.
  6019. var node = this.$$element[0],
  6020. booleanKey = getBooleanAttrName(node, key),
  6021. aliasedKey = getAliasedAttrName(node, key),
  6022. observer = key,
  6023. nodeName;
  6024. if (booleanKey) {
  6025. this.$$element.prop(key, value);
  6026. attrName = booleanKey;
  6027. } else if (aliasedKey) {
  6028. this[aliasedKey] = value;
  6029. observer = aliasedKey;
  6030. }
  6031. this[key] = value;
  6032. // translate normalized key to actual key
  6033. if (attrName) {
  6034. this.$attr[key] = attrName;
  6035. } else {
  6036. attrName = this.$attr[key];
  6037. if (!attrName) {
  6038. this.$attr[key] = attrName = snake_case(key, '-');
  6039. }
  6040. }
  6041. nodeName = nodeName_(this.$$element);
  6042. if ((nodeName === 'a' && key === 'href') ||
  6043. (nodeName === 'img' && key === 'src')) {
  6044. // sanitize a[href] and img[src] values
  6045. this[key] = value = $$sanitizeUri(value, key === 'src');
  6046. } else if (nodeName === 'img' && key === 'srcset') {
  6047. // sanitize img[srcset] values
  6048. var result = "";
  6049. // first check if there are spaces because it's not the same pattern
  6050. var trimmedSrcset = trim(value);
  6051. // ( 999x ,| 999w ,| ,|, )
  6052. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6053. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6054. // split srcset into tuple of uri and descriptor except for the last item
  6055. var rawUris = trimmedSrcset.split(pattern);
  6056. // for each tuples
  6057. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6058. for (var i=0; i<nbrUrisWith2parts; i++) {
  6059. var innerIdx = i*2;
  6060. // sanitize the uri
  6061. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6062. // add the descriptor
  6063. result += (" " + trim(rawUris[innerIdx+1]));
  6064. }
  6065. // split the last item into uri and descriptor
  6066. var lastTuple = trim(rawUris[i*2]).split(/\s/);
  6067. // sanitize the last uri
  6068. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6069. // and add the last descriptor if any
  6070. if (lastTuple.length === 2) {
  6071. result += (" " + trim(lastTuple[1]));
  6072. }
  6073. this[key] = value = result;
  6074. }
  6075. if (writeAttr !== false) {
  6076. if (value === null || value === undefined) {
  6077. this.$$element.removeAttr(attrName);
  6078. } else {
  6079. this.$$element.attr(attrName, value);
  6080. }
  6081. }
  6082. // fire observers
  6083. var $$observers = this.$$observers;
  6084. $$observers && forEach($$observers[observer], function(fn) {
  6085. try {
  6086. fn(value);
  6087. } catch (e) {
  6088. $exceptionHandler(e);
  6089. }
  6090. });
  6091. },
  6092. /**
  6093. * @ngdoc method
  6094. * @name $compile.directive.Attributes#$observe
  6095. * @kind function
  6096. *
  6097. * @description
  6098. * Observes an interpolated attribute.
  6099. *
  6100. * The observer function will be invoked once during the next `$digest` following
  6101. * compilation. The observer is then invoked whenever the interpolated value
  6102. * changes.
  6103. *
  6104. * @param {string} key Normalized key. (ie ngAttribute) .
  6105. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6106. the interpolated value of the attribute changes.
  6107. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6108. * @returns {function()} Returns a deregistration function for this observer.
  6109. */
  6110. $observe: function(key, fn) {
  6111. var attrs = this,
  6112. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6113. listeners = ($$observers[key] || ($$observers[key] = []));
  6114. listeners.push(fn);
  6115. $rootScope.$evalAsync(function() {
  6116. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6117. // no one registered attribute interpolation function, so lets call it manually
  6118. fn(attrs[key]);
  6119. }
  6120. });
  6121. return function() {
  6122. arrayRemove(listeners, fn);
  6123. };
  6124. }
  6125. };
  6126. function safeAddClass($element, className) {
  6127. try {
  6128. $element.addClass(className);
  6129. } catch (e) {
  6130. // ignore, since it means that we are trying to set class on
  6131. // SVG element, where class name is read-only.
  6132. }
  6133. }
  6134. var startSymbol = $interpolate.startSymbol(),
  6135. endSymbol = $interpolate.endSymbol(),
  6136. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6137. ? identity
  6138. : function denormalizeTemplate(template) {
  6139. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6140. },
  6141. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6142. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6143. var bindings = $element.data('$binding') || [];
  6144. if (isArray(binding)) {
  6145. bindings = bindings.concat(binding);
  6146. } else {
  6147. bindings.push(binding);
  6148. }
  6149. $element.data('$binding', bindings);
  6150. } : noop;
  6151. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6152. safeAddClass($element, 'ng-binding');
  6153. } : noop;
  6154. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6155. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6156. $element.data(dataName, scope);
  6157. } : noop;
  6158. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6159. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6160. } : noop;
  6161. return compile;
  6162. //================================
  6163. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6164. previousCompileContext) {
  6165. if (!($compileNodes instanceof jqLite)) {
  6166. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6167. // modify it.
  6168. $compileNodes = jqLite($compileNodes);
  6169. }
  6170. // We can not compile top level text elements since text nodes can be merged and we will
  6171. // not be able to attach scope data to them, so we will wrap them in <span>
  6172. forEach($compileNodes, function(node, index) {
  6173. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6174. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6175. }
  6176. });
  6177. var compositeLinkFn =
  6178. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6179. maxPriority, ignoreDirective, previousCompileContext);
  6180. compile.$$addScopeClass($compileNodes);
  6181. var namespace = null;
  6182. return function publicLinkFn(scope, cloneConnectFn, options) {
  6183. assertArg(scope, 'scope');
  6184. options = options || {};
  6185. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6186. transcludeControllers = options.transcludeControllers,
  6187. futureParentElement = options.futureParentElement;
  6188. // When `parentBoundTranscludeFn` is passed, it is a
  6189. // `controllersBoundTransclude` function (it was previously passed
  6190. // as `transclude` to directive.link) so we must unwrap it to get
  6191. // its `boundTranscludeFn`
  6192. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6193. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6194. }
  6195. if (!namespace) {
  6196. namespace = detectNamespaceForChildElements(futureParentElement);
  6197. }
  6198. var $linkNode;
  6199. if (namespace !== 'html') {
  6200. // When using a directive with replace:true and templateUrl the $compileNodes
  6201. // (or a child element inside of them)
  6202. // might change, so we need to recreate the namespace adapted compileNodes
  6203. // for call to the link function.
  6204. // Note: This will already clone the nodes...
  6205. $linkNode = jqLite(
  6206. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6207. );
  6208. } else if (cloneConnectFn) {
  6209. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6210. // and sometimes changes the structure of the DOM.
  6211. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6212. } else {
  6213. $linkNode = $compileNodes;
  6214. }
  6215. if (transcludeControllers) {
  6216. for (var controllerName in transcludeControllers) {
  6217. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6218. }
  6219. }
  6220. compile.$$addScopeInfo($linkNode, scope);
  6221. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6222. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6223. return $linkNode;
  6224. };
  6225. }
  6226. function detectNamespaceForChildElements(parentElement) {
  6227. // TODO: Make this detect MathML as well...
  6228. var node = parentElement && parentElement[0];
  6229. if (!node) {
  6230. return 'html';
  6231. } else {
  6232. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg': 'html';
  6233. }
  6234. }
  6235. /**
  6236. * Compile function matches each node in nodeList against the directives. Once all directives
  6237. * for a particular node are collected their compile functions are executed. The compile
  6238. * functions return values - the linking functions - are combined into a composite linking
  6239. * function, which is the a linking function for the node.
  6240. *
  6241. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6242. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6243. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6244. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6245. * the rootElement must be set the jqLite collection of the compile root. This is
  6246. * needed so that the jqLite collection items can be replaced with widgets.
  6247. * @param {number=} maxPriority Max directive priority.
  6248. * @returns {Function} A composite linking function of all of the matched directives or null.
  6249. */
  6250. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6251. previousCompileContext) {
  6252. var linkFns = [],
  6253. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6254. for (var i = 0; i < nodeList.length; i++) {
  6255. attrs = new Attributes();
  6256. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6257. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6258. ignoreDirective);
  6259. nodeLinkFn = (directives.length)
  6260. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6261. null, [], [], previousCompileContext)
  6262. : null;
  6263. if (nodeLinkFn && nodeLinkFn.scope) {
  6264. compile.$$addScopeClass(attrs.$$element);
  6265. }
  6266. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6267. !(childNodes = nodeList[i].childNodes) ||
  6268. !childNodes.length)
  6269. ? null
  6270. : compileNodes(childNodes,
  6271. nodeLinkFn ? (
  6272. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6273. && nodeLinkFn.transclude) : transcludeFn);
  6274. if (nodeLinkFn || childLinkFn) {
  6275. linkFns.push(i, nodeLinkFn, childLinkFn);
  6276. linkFnFound = true;
  6277. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6278. }
  6279. //use the previous context only for the first element in the virtual group
  6280. previousCompileContext = null;
  6281. }
  6282. // return a linking function if we have found anything, null otherwise
  6283. return linkFnFound ? compositeLinkFn : null;
  6284. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6285. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6286. var stableNodeList;
  6287. if (nodeLinkFnFound) {
  6288. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6289. // offsets don't get screwed up
  6290. var nodeListLength = nodeList.length;
  6291. stableNodeList = new Array(nodeListLength);
  6292. // create a sparse array by only copying the elements which have a linkFn
  6293. for (i = 0; i < linkFns.length; i+=3) {
  6294. idx = linkFns[i];
  6295. stableNodeList[idx] = nodeList[idx];
  6296. }
  6297. } else {
  6298. stableNodeList = nodeList;
  6299. }
  6300. for (i = 0, ii = linkFns.length; i < ii;) {
  6301. node = stableNodeList[linkFns[i++]];
  6302. nodeLinkFn = linkFns[i++];
  6303. childLinkFn = linkFns[i++];
  6304. if (nodeLinkFn) {
  6305. if (nodeLinkFn.scope) {
  6306. childScope = scope.$new();
  6307. compile.$$addScopeInfo(jqLite(node), childScope);
  6308. } else {
  6309. childScope = scope;
  6310. }
  6311. if (nodeLinkFn.transcludeOnThisElement) {
  6312. childBoundTranscludeFn = createBoundTranscludeFn(
  6313. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6314. nodeLinkFn.elementTranscludeOnThisElement);
  6315. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6316. childBoundTranscludeFn = parentBoundTranscludeFn;
  6317. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6318. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6319. } else {
  6320. childBoundTranscludeFn = null;
  6321. }
  6322. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6323. } else if (childLinkFn) {
  6324. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6325. }
  6326. }
  6327. }
  6328. }
  6329. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6330. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6331. if (!transcludedScope) {
  6332. transcludedScope = scope.$new(false, containingScope);
  6333. transcludedScope.$$transcluded = true;
  6334. }
  6335. return transcludeFn(transcludedScope, cloneFn, {
  6336. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6337. transcludeControllers: controllers,
  6338. futureParentElement: futureParentElement
  6339. });
  6340. };
  6341. return boundTranscludeFn;
  6342. }
  6343. /**
  6344. * Looks for directives on the given node and adds them to the directive collection which is
  6345. * sorted.
  6346. *
  6347. * @param node Node to search.
  6348. * @param directives An array to which the directives are added to. This array is sorted before
  6349. * the function returns.
  6350. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6351. * @param {number=} maxPriority Max directive priority.
  6352. */
  6353. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6354. var nodeType = node.nodeType,
  6355. attrsMap = attrs.$attr,
  6356. match,
  6357. className;
  6358. switch (nodeType) {
  6359. case NODE_TYPE_ELEMENT: /* Element */
  6360. // use the node name: <directive>
  6361. addDirective(directives,
  6362. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6363. // iterate over the attributes
  6364. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6365. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6366. var attrStartName = false;
  6367. var attrEndName = false;
  6368. attr = nAttrs[j];
  6369. name = attr.name;
  6370. value = trim(attr.value);
  6371. // support ngAttr attribute binding
  6372. ngAttrName = directiveNormalize(name);
  6373. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6374. name = snake_case(ngAttrName.substr(6), '-');
  6375. }
  6376. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6377. if (directiveIsMultiElement(directiveNName)) {
  6378. if (ngAttrName === directiveNName + 'Start') {
  6379. attrStartName = name;
  6380. attrEndName = name.substr(0, name.length - 5) + 'end';
  6381. name = name.substr(0, name.length - 6);
  6382. }
  6383. }
  6384. nName = directiveNormalize(name.toLowerCase());
  6385. attrsMap[nName] = name;
  6386. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6387. attrs[nName] = value;
  6388. if (getBooleanAttrName(node, nName)) {
  6389. attrs[nName] = true; // presence means true
  6390. }
  6391. }
  6392. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6393. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6394. attrEndName);
  6395. }
  6396. // use class as directive
  6397. className = node.className;
  6398. if (isString(className) && className !== '') {
  6399. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6400. nName = directiveNormalize(match[2]);
  6401. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6402. attrs[nName] = trim(match[3]);
  6403. }
  6404. className = className.substr(match.index + match[0].length);
  6405. }
  6406. }
  6407. break;
  6408. case NODE_TYPE_TEXT: /* Text Node */
  6409. addTextInterpolateDirective(directives, node.nodeValue);
  6410. break;
  6411. case NODE_TYPE_COMMENT: /* Comment */
  6412. try {
  6413. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6414. if (match) {
  6415. nName = directiveNormalize(match[1]);
  6416. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6417. attrs[nName] = trim(match[2]);
  6418. }
  6419. }
  6420. } catch (e) {
  6421. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6422. // comment's node value.
  6423. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6424. }
  6425. break;
  6426. }
  6427. directives.sort(byPriority);
  6428. return directives;
  6429. }
  6430. /**
  6431. * Given a node with an directive-start it collects all of the siblings until it finds
  6432. * directive-end.
  6433. * @param node
  6434. * @param attrStart
  6435. * @param attrEnd
  6436. * @returns {*}
  6437. */
  6438. function groupScan(node, attrStart, attrEnd) {
  6439. var nodes = [];
  6440. var depth = 0;
  6441. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6442. do {
  6443. if (!node) {
  6444. throw $compileMinErr('uterdir',
  6445. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6446. attrStart, attrEnd);
  6447. }
  6448. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6449. if (node.hasAttribute(attrStart)) depth++;
  6450. if (node.hasAttribute(attrEnd)) depth--;
  6451. }
  6452. nodes.push(node);
  6453. node = node.nextSibling;
  6454. } while (depth > 0);
  6455. } else {
  6456. nodes.push(node);
  6457. }
  6458. return jqLite(nodes);
  6459. }
  6460. /**
  6461. * Wrapper for linking function which converts normal linking function into a grouped
  6462. * linking function.
  6463. * @param linkFn
  6464. * @param attrStart
  6465. * @param attrEnd
  6466. * @returns {Function}
  6467. */
  6468. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6469. return function(scope, element, attrs, controllers, transcludeFn) {
  6470. element = groupScan(element[0], attrStart, attrEnd);
  6471. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6472. };
  6473. }
  6474. /**
  6475. * Once the directives have been collected, their compile functions are executed. This method
  6476. * is responsible for inlining directive templates as well as terminating the application
  6477. * of the directives if the terminal directive has been reached.
  6478. *
  6479. * @param {Array} directives Array of collected directives to execute their compile function.
  6480. * this needs to be pre-sorted by priority order.
  6481. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6482. * @param {Object} templateAttrs The shared attribute function
  6483. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6484. * scope argument is auto-generated to the new
  6485. * child of the transcluded parent scope.
  6486. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6487. * argument has the root jqLite array so that we can replace nodes
  6488. * on it.
  6489. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6490. * compiling the transclusion.
  6491. * @param {Array.<Function>} preLinkFns
  6492. * @param {Array.<Function>} postLinkFns
  6493. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6494. * node
  6495. * @returns {Function} linkFn
  6496. */
  6497. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6498. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6499. previousCompileContext) {
  6500. previousCompileContext = previousCompileContext || {};
  6501. var terminalPriority = -Number.MAX_VALUE,
  6502. newScopeDirective,
  6503. controllerDirectives = previousCompileContext.controllerDirectives,
  6504. controllers,
  6505. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6506. templateDirective = previousCompileContext.templateDirective,
  6507. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6508. hasTranscludeDirective = false,
  6509. hasTemplate = false,
  6510. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6511. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6512. directive,
  6513. directiveName,
  6514. $template,
  6515. replaceDirective = originalReplaceDirective,
  6516. childTranscludeFn = transcludeFn,
  6517. linkFn,
  6518. directiveValue;
  6519. // executes all directives on the current element
  6520. for (var i = 0, ii = directives.length; i < ii; i++) {
  6521. directive = directives[i];
  6522. var attrStart = directive.$$start;
  6523. var attrEnd = directive.$$end;
  6524. // collect multiblock sections
  6525. if (attrStart) {
  6526. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6527. }
  6528. $template = undefined;
  6529. if (terminalPriority > directive.priority) {
  6530. break; // prevent further processing of directives
  6531. }
  6532. if (directiveValue = directive.scope) {
  6533. // skip the check for directives with async templates, we'll check the derived sync
  6534. // directive when the template arrives
  6535. if (!directive.templateUrl) {
  6536. if (isObject(directiveValue)) {
  6537. // This directive is trying to add an isolated scope.
  6538. // Check that there is no scope of any kind already
  6539. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6540. directive, $compileNode);
  6541. newIsolateScopeDirective = directive;
  6542. } else {
  6543. // This directive is trying to add a child scope.
  6544. // Check that there is no isolated scope already
  6545. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6546. $compileNode);
  6547. }
  6548. }
  6549. newScopeDirective = newScopeDirective || directive;
  6550. }
  6551. directiveName = directive.name;
  6552. if (!directive.templateUrl && directive.controller) {
  6553. directiveValue = directive.controller;
  6554. controllerDirectives = controllerDirectives || {};
  6555. assertNoDuplicate("'" + directiveName + "' controller",
  6556. controllerDirectives[directiveName], directive, $compileNode);
  6557. controllerDirectives[directiveName] = directive;
  6558. }
  6559. if (directiveValue = directive.transclude) {
  6560. hasTranscludeDirective = true;
  6561. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6562. // This option should only be used by directives that know how to safely handle element transclusion,
  6563. // where the transcluded nodes are added or replaced after linking.
  6564. if (!directive.$$tlb) {
  6565. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6566. nonTlbTranscludeDirective = directive;
  6567. }
  6568. if (directiveValue == 'element') {
  6569. hasElementTranscludeDirective = true;
  6570. terminalPriority = directive.priority;
  6571. $template = $compileNode;
  6572. $compileNode = templateAttrs.$$element =
  6573. jqLite(document.createComment(' ' + directiveName + ': ' +
  6574. templateAttrs[directiveName] + ' '));
  6575. compileNode = $compileNode[0];
  6576. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6577. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6578. replaceDirective && replaceDirective.name, {
  6579. // Don't pass in:
  6580. // - controllerDirectives - otherwise we'll create duplicates controllers
  6581. // - newIsolateScopeDirective or templateDirective - combining templates with
  6582. // element transclusion doesn't make sense.
  6583. //
  6584. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6585. // on the same element more than once.
  6586. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6587. });
  6588. } else {
  6589. $template = jqLite(jqLiteClone(compileNode)).contents();
  6590. $compileNode.empty(); // clear contents
  6591. childTranscludeFn = compile($template, transcludeFn);
  6592. }
  6593. }
  6594. if (directive.template) {
  6595. hasTemplate = true;
  6596. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6597. templateDirective = directive;
  6598. directiveValue = (isFunction(directive.template))
  6599. ? directive.template($compileNode, templateAttrs)
  6600. : directive.template;
  6601. directiveValue = denormalizeTemplate(directiveValue);
  6602. if (directive.replace) {
  6603. replaceDirective = directive;
  6604. if (jqLiteIsTextNode(directiveValue)) {
  6605. $template = [];
  6606. } else {
  6607. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6608. }
  6609. compileNode = $template[0];
  6610. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6611. throw $compileMinErr('tplrt',
  6612. "Template for directive '{0}' must have exactly one root element. {1}",
  6613. directiveName, '');
  6614. }
  6615. replaceWith(jqCollection, $compileNode, compileNode);
  6616. var newTemplateAttrs = {$attr: {}};
  6617. // combine directives from the original node and from the template:
  6618. // - take the array of directives for this element
  6619. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6620. // - collect directives from the template and sort them by priority
  6621. // - combine directives as: processed + template + unprocessed
  6622. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6623. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6624. if (newIsolateScopeDirective) {
  6625. markDirectivesAsIsolate(templateDirectives);
  6626. }
  6627. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6628. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6629. ii = directives.length;
  6630. } else {
  6631. $compileNode.html(directiveValue);
  6632. }
  6633. }
  6634. if (directive.templateUrl) {
  6635. hasTemplate = true;
  6636. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6637. templateDirective = directive;
  6638. if (directive.replace) {
  6639. replaceDirective = directive;
  6640. }
  6641. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6642. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6643. controllerDirectives: controllerDirectives,
  6644. newIsolateScopeDirective: newIsolateScopeDirective,
  6645. templateDirective: templateDirective,
  6646. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6647. });
  6648. ii = directives.length;
  6649. } else if (directive.compile) {
  6650. try {
  6651. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6652. if (isFunction(linkFn)) {
  6653. addLinkFns(null, linkFn, attrStart, attrEnd);
  6654. } else if (linkFn) {
  6655. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6656. }
  6657. } catch (e) {
  6658. $exceptionHandler(e, startingTag($compileNode));
  6659. }
  6660. }
  6661. if (directive.terminal) {
  6662. nodeLinkFn.terminal = true;
  6663. terminalPriority = Math.max(terminalPriority, directive.priority);
  6664. }
  6665. }
  6666. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6667. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6668. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6669. nodeLinkFn.templateOnThisElement = hasTemplate;
  6670. nodeLinkFn.transclude = childTranscludeFn;
  6671. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6672. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6673. return nodeLinkFn;
  6674. ////////////////////
  6675. function addLinkFns(pre, post, attrStart, attrEnd) {
  6676. if (pre) {
  6677. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6678. pre.require = directive.require;
  6679. pre.directiveName = directiveName;
  6680. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6681. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6682. }
  6683. preLinkFns.push(pre);
  6684. }
  6685. if (post) {
  6686. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6687. post.require = directive.require;
  6688. post.directiveName = directiveName;
  6689. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6690. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6691. }
  6692. postLinkFns.push(post);
  6693. }
  6694. }
  6695. function getControllers(directiveName, require, $element, elementControllers) {
  6696. var value, retrievalMethod = 'data', optional = false;
  6697. var $searchElement = $element;
  6698. var match;
  6699. if (isString(require)) {
  6700. match = require.match(REQUIRE_PREFIX_REGEXP);
  6701. require = require.substring(match[0].length);
  6702. if (match[3]) {
  6703. if (match[1]) match[3] = null;
  6704. else match[1] = match[3];
  6705. }
  6706. if (match[1] === '^') {
  6707. retrievalMethod = 'inheritedData';
  6708. } else if (match[1] === '^^') {
  6709. retrievalMethod = 'inheritedData';
  6710. $searchElement = $element.parent();
  6711. }
  6712. if (match[2] === '?') {
  6713. optional = true;
  6714. }
  6715. value = null;
  6716. if (elementControllers && retrievalMethod === 'data') {
  6717. if (value = elementControllers[require]) {
  6718. value = value.instance;
  6719. }
  6720. }
  6721. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6722. if (!value && !optional) {
  6723. throw $compileMinErr('ctreq',
  6724. "Controller '{0}', required by directive '{1}', can't be found!",
  6725. require, directiveName);
  6726. }
  6727. return value || null;
  6728. } else if (isArray(require)) {
  6729. value = [];
  6730. forEach(require, function(require) {
  6731. value.push(getControllers(directiveName, require, $element, elementControllers));
  6732. });
  6733. }
  6734. return value;
  6735. }
  6736. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6737. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6738. attrs;
  6739. if (compileNode === linkNode) {
  6740. attrs = templateAttrs;
  6741. $element = templateAttrs.$$element;
  6742. } else {
  6743. $element = jqLite(linkNode);
  6744. attrs = new Attributes($element, templateAttrs);
  6745. }
  6746. if (newIsolateScopeDirective) {
  6747. isolateScope = scope.$new(true);
  6748. }
  6749. if (boundTranscludeFn) {
  6750. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  6751. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  6752. transcludeFn = controllersBoundTransclude;
  6753. transcludeFn.$$boundTransclude = boundTranscludeFn;
  6754. }
  6755. if (controllerDirectives) {
  6756. // TODO: merge `controllers` and `elementControllers` into single object.
  6757. controllers = {};
  6758. elementControllers = {};
  6759. forEach(controllerDirectives, function(directive) {
  6760. var locals = {
  6761. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6762. $element: $element,
  6763. $attrs: attrs,
  6764. $transclude: transcludeFn
  6765. }, controllerInstance;
  6766. controller = directive.controller;
  6767. if (controller == '@') {
  6768. controller = attrs[directive.name];
  6769. }
  6770. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6771. // For directives with element transclusion the element is a comment,
  6772. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6773. // clean up (http://bugs.jquery.com/ticket/8335).
  6774. // Instead, we save the controllers for the element in a local hash and attach to .data
  6775. // later, once we have the actual element.
  6776. elementControllers[directive.name] = controllerInstance;
  6777. if (!hasElementTranscludeDirective) {
  6778. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6779. }
  6780. controllers[directive.name] = controllerInstance;
  6781. });
  6782. }
  6783. if (newIsolateScopeDirective) {
  6784. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6785. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6786. compile.$$addScopeClass($element, true);
  6787. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6788. var isolateBindingContext = isolateScope;
  6789. if (isolateScopeController && isolateScopeController.identifier &&
  6790. newIsolateScopeDirective.bindToController === true) {
  6791. isolateBindingContext = isolateScopeController.instance;
  6792. }
  6793. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6794. var attrName = definition.attrName,
  6795. optional = definition.optional,
  6796. mode = definition.mode, // @, =, or &
  6797. lastValue,
  6798. parentGet, parentSet, compare;
  6799. switch (mode) {
  6800. case '@':
  6801. attrs.$observe(attrName, function(value) {
  6802. isolateBindingContext[scopeName] = value;
  6803. });
  6804. attrs.$$observers[attrName].$$scope = scope;
  6805. if (attrs[attrName]) {
  6806. // If the attribute has been provided then we trigger an interpolation to ensure
  6807. // the value is there for use in the link fn
  6808. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6809. }
  6810. break;
  6811. case '=':
  6812. if (optional && !attrs[attrName]) {
  6813. return;
  6814. }
  6815. parentGet = $parse(attrs[attrName]);
  6816. if (parentGet.literal) {
  6817. compare = equals;
  6818. } else {
  6819. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  6820. }
  6821. parentSet = parentGet.assign || function() {
  6822. // reset the change, or we will throw this exception on every $digest
  6823. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6824. throw $compileMinErr('nonassign',
  6825. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6826. attrs[attrName], newIsolateScopeDirective.name);
  6827. };
  6828. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6829. var parentValueWatch = function parentValueWatch(parentValue) {
  6830. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6831. // we are out of sync and need to copy
  6832. if (!compare(parentValue, lastValue)) {
  6833. // parent changed and it has precedence
  6834. isolateBindingContext[scopeName] = parentValue;
  6835. } else {
  6836. // if the parent can be assigned then do so
  6837. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6838. }
  6839. }
  6840. return lastValue = parentValue;
  6841. };
  6842. parentValueWatch.$stateful = true;
  6843. var unwatch;
  6844. if (definition.collection) {
  6845. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  6846. } else {
  6847. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6848. }
  6849. isolateScope.$on('$destroy', unwatch);
  6850. break;
  6851. case '&':
  6852. parentGet = $parse(attrs[attrName]);
  6853. isolateBindingContext[scopeName] = function(locals) {
  6854. return parentGet(scope, locals);
  6855. };
  6856. break;
  6857. }
  6858. });
  6859. }
  6860. if (controllers) {
  6861. forEach(controllers, function(controller) {
  6862. controller();
  6863. });
  6864. controllers = null;
  6865. }
  6866. // PRELINKING
  6867. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  6868. linkFn = preLinkFns[i];
  6869. invokeLinkFn(linkFn,
  6870. linkFn.isolateScope ? isolateScope : scope,
  6871. $element,
  6872. attrs,
  6873. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6874. transcludeFn
  6875. );
  6876. }
  6877. // RECURSION
  6878. // We only pass the isolate scope, if the isolate directive has a template,
  6879. // otherwise the child elements do not belong to the isolate directive.
  6880. var scopeToChild = scope;
  6881. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6882. scopeToChild = isolateScope;
  6883. }
  6884. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6885. // POSTLINKING
  6886. for (i = postLinkFns.length - 1; i >= 0; i--) {
  6887. linkFn = postLinkFns[i];
  6888. invokeLinkFn(linkFn,
  6889. linkFn.isolateScope ? isolateScope : scope,
  6890. $element,
  6891. attrs,
  6892. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6893. transcludeFn
  6894. );
  6895. }
  6896. // This is the function that is injected as `$transclude`.
  6897. // Note: all arguments are optional!
  6898. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  6899. var transcludeControllers;
  6900. // No scope passed in:
  6901. if (!isScope(scope)) {
  6902. futureParentElement = cloneAttachFn;
  6903. cloneAttachFn = scope;
  6904. scope = undefined;
  6905. }
  6906. if (hasElementTranscludeDirective) {
  6907. transcludeControllers = elementControllers;
  6908. }
  6909. if (!futureParentElement) {
  6910. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  6911. }
  6912. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  6913. }
  6914. }
  6915. }
  6916. function markDirectivesAsIsolate(directives) {
  6917. // mark all directives as needing isolate scope.
  6918. for (var j = 0, jj = directives.length; j < jj; j++) {
  6919. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6920. }
  6921. }
  6922. /**
  6923. * looks up the directive and decorates it with exception handling and proper parameters. We
  6924. * call this the boundDirective.
  6925. *
  6926. * @param {string} name name of the directive to look up.
  6927. * @param {string} location The directive must be found in specific format.
  6928. * String containing any of theses characters:
  6929. *
  6930. * * `E`: element name
  6931. * * `A': attribute
  6932. * * `C`: class
  6933. * * `M`: comment
  6934. * @returns {boolean} true if directive was added.
  6935. */
  6936. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6937. endAttrName) {
  6938. if (name === ignoreDirective) return null;
  6939. var match = null;
  6940. if (hasDirectives.hasOwnProperty(name)) {
  6941. for (var directive, directives = $injector.get(name + Suffix),
  6942. i = 0, ii = directives.length; i<ii; i++) {
  6943. try {
  6944. directive = directives[i];
  6945. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  6946. directive.restrict.indexOf(location) != -1) {
  6947. if (startAttrName) {
  6948. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6949. }
  6950. tDirectives.push(directive);
  6951. match = directive;
  6952. }
  6953. } catch (e) { $exceptionHandler(e); }
  6954. }
  6955. }
  6956. return match;
  6957. }
  6958. /**
  6959. * looks up the directive and returns true if it is a multi-element directive,
  6960. * and therefore requires DOM nodes between -start and -end markers to be grouped
  6961. * together.
  6962. *
  6963. * @param {string} name name of the directive to look up.
  6964. * @returns true if directive was registered as multi-element.
  6965. */
  6966. function directiveIsMultiElement(name) {
  6967. if (hasDirectives.hasOwnProperty(name)) {
  6968. for (var directive, directives = $injector.get(name + Suffix),
  6969. i = 0, ii = directives.length; i<ii; i++) {
  6970. directive = directives[i];
  6971. if (directive.multiElement) {
  6972. return true;
  6973. }
  6974. }
  6975. }
  6976. return false;
  6977. }
  6978. /**
  6979. * When the element is replaced with HTML template then the new attributes
  6980. * on the template need to be merged with the existing attributes in the DOM.
  6981. * The desired effect is to have both of the attributes present.
  6982. *
  6983. * @param {object} dst destination attributes (original DOM)
  6984. * @param {object} src source attributes (from the directive template)
  6985. */
  6986. function mergeTemplateAttributes(dst, src) {
  6987. var srcAttr = src.$attr,
  6988. dstAttr = dst.$attr,
  6989. $element = dst.$$element;
  6990. // reapply the old attributes to the new element
  6991. forEach(dst, function(value, key) {
  6992. if (key.charAt(0) != '$') {
  6993. if (src[key] && src[key] !== value) {
  6994. value += (key === 'style' ? ';' : ' ') + src[key];
  6995. }
  6996. dst.$set(key, value, true, srcAttr[key]);
  6997. }
  6998. });
  6999. // copy the new attributes on the old attrs object
  7000. forEach(src, function(value, key) {
  7001. if (key == 'class') {
  7002. safeAddClass($element, value);
  7003. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7004. } else if (key == 'style') {
  7005. $element.attr('style', $element.attr('style') + ';' + value);
  7006. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7007. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7008. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7009. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7010. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7011. dst[key] = value;
  7012. dstAttr[key] = srcAttr[key];
  7013. }
  7014. });
  7015. }
  7016. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7017. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7018. var linkQueue = [],
  7019. afterTemplateNodeLinkFn,
  7020. afterTemplateChildLinkFn,
  7021. beforeTemplateCompileNode = $compileNode[0],
  7022. origAsyncDirective = directives.shift(),
  7023. // The fact that we have to copy and patch the directive seems wrong!
  7024. derivedSyncDirective = extend({}, origAsyncDirective, {
  7025. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7026. }),
  7027. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7028. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7029. : origAsyncDirective.templateUrl,
  7030. templateNamespace = origAsyncDirective.templateNamespace;
  7031. $compileNode.empty();
  7032. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7033. .then(function(content) {
  7034. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7035. content = denormalizeTemplate(content);
  7036. if (origAsyncDirective.replace) {
  7037. if (jqLiteIsTextNode(content)) {
  7038. $template = [];
  7039. } else {
  7040. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7041. }
  7042. compileNode = $template[0];
  7043. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7044. throw $compileMinErr('tplrt',
  7045. "Template for directive '{0}' must have exactly one root element. {1}",
  7046. origAsyncDirective.name, templateUrl);
  7047. }
  7048. tempTemplateAttrs = {$attr: {}};
  7049. replaceWith($rootElement, $compileNode, compileNode);
  7050. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7051. if (isObject(origAsyncDirective.scope)) {
  7052. markDirectivesAsIsolate(templateDirectives);
  7053. }
  7054. directives = templateDirectives.concat(directives);
  7055. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7056. } else {
  7057. compileNode = beforeTemplateCompileNode;
  7058. $compileNode.html(content);
  7059. }
  7060. directives.unshift(derivedSyncDirective);
  7061. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7062. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7063. previousCompileContext);
  7064. forEach($rootElement, function(node, i) {
  7065. if (node == compileNode) {
  7066. $rootElement[i] = $compileNode[0];
  7067. }
  7068. });
  7069. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7070. while (linkQueue.length) {
  7071. var scope = linkQueue.shift(),
  7072. beforeTemplateLinkNode = linkQueue.shift(),
  7073. linkRootElement = linkQueue.shift(),
  7074. boundTranscludeFn = linkQueue.shift(),
  7075. linkNode = $compileNode[0];
  7076. if (scope.$$destroyed) continue;
  7077. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7078. var oldClasses = beforeTemplateLinkNode.className;
  7079. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7080. origAsyncDirective.replace)) {
  7081. // it was cloned therefore we have to clone as well.
  7082. linkNode = jqLiteClone(compileNode);
  7083. }
  7084. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7085. // Copy in CSS classes from original node
  7086. safeAddClass(jqLite(linkNode), oldClasses);
  7087. }
  7088. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7089. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7090. } else {
  7091. childBoundTranscludeFn = boundTranscludeFn;
  7092. }
  7093. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7094. childBoundTranscludeFn);
  7095. }
  7096. linkQueue = null;
  7097. });
  7098. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7099. var childBoundTranscludeFn = boundTranscludeFn;
  7100. if (scope.$$destroyed) return;
  7101. if (linkQueue) {
  7102. linkQueue.push(scope);
  7103. linkQueue.push(node);
  7104. linkQueue.push(rootElement);
  7105. linkQueue.push(childBoundTranscludeFn);
  7106. } else {
  7107. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7108. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7109. }
  7110. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7111. }
  7112. };
  7113. }
  7114. /**
  7115. * Sorting function for bound directives.
  7116. */
  7117. function byPriority(a, b) {
  7118. var diff = b.priority - a.priority;
  7119. if (diff !== 0) return diff;
  7120. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7121. return a.index - b.index;
  7122. }
  7123. function assertNoDuplicate(what, previousDirective, directive, element) {
  7124. if (previousDirective) {
  7125. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7126. previousDirective.name, directive.name, what, startingTag(element));
  7127. }
  7128. }
  7129. function addTextInterpolateDirective(directives, text) {
  7130. var interpolateFn = $interpolate(text, true);
  7131. if (interpolateFn) {
  7132. directives.push({
  7133. priority: 0,
  7134. compile: function textInterpolateCompileFn(templateNode) {
  7135. var templateNodeParent = templateNode.parent(),
  7136. hasCompileParent = !!templateNodeParent.length;
  7137. // When transcluding a template that has bindings in the root
  7138. // we don't have a parent and thus need to add the class during linking fn.
  7139. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7140. return function textInterpolateLinkFn(scope, node) {
  7141. var parent = node.parent();
  7142. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7143. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7144. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7145. node[0].nodeValue = value;
  7146. });
  7147. };
  7148. }
  7149. });
  7150. }
  7151. }
  7152. function wrapTemplate(type, template) {
  7153. type = lowercase(type || 'html');
  7154. switch (type) {
  7155. case 'svg':
  7156. case 'math':
  7157. var wrapper = document.createElement('div');
  7158. wrapper.innerHTML = '<'+type+'>'+template+'</'+type+'>';
  7159. return wrapper.childNodes[0].childNodes;
  7160. default:
  7161. return template;
  7162. }
  7163. }
  7164. function getTrustedContext(node, attrNormalizedName) {
  7165. if (attrNormalizedName == "srcdoc") {
  7166. return $sce.HTML;
  7167. }
  7168. var tag = nodeName_(node);
  7169. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7170. if (attrNormalizedName == "xlinkHref" ||
  7171. (tag == "form" && attrNormalizedName == "action") ||
  7172. (tag != "img" && (attrNormalizedName == "src" ||
  7173. attrNormalizedName == "ngSrc"))) {
  7174. return $sce.RESOURCE_URL;
  7175. }
  7176. }
  7177. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7178. var interpolateFn = $interpolate(value, true);
  7179. // no interpolation found -> ignore
  7180. if (!interpolateFn) return;
  7181. if (name === "multiple" && nodeName_(node) === "select") {
  7182. throw $compileMinErr("selmulti",
  7183. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7184. startingTag(node));
  7185. }
  7186. directives.push({
  7187. priority: 100,
  7188. compile: function() {
  7189. return {
  7190. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7191. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7192. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7193. throw $compileMinErr('nodomevents',
  7194. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7195. "ng- versions (such as ng-click instead of onclick) instead.");
  7196. }
  7197. // If the attribute was removed, then we are done
  7198. if (!attr[name]) {
  7199. return;
  7200. }
  7201. // we need to interpolate again, in case the attribute value has been updated
  7202. // (e.g. by another directive's compile function)
  7203. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name),
  7204. ALL_OR_NOTHING_ATTRS[name] || allOrNothing);
  7205. // if attribute was updated so that there is no interpolation going on we don't want to
  7206. // register any observers
  7207. if (!interpolateFn) return;
  7208. // initialize attr object so that it's ready in case we need the value for isolate
  7209. // scope initialization, otherwise the value would not be available from isolate
  7210. // directive's linking fn during linking phase
  7211. attr[name] = interpolateFn(scope);
  7212. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7213. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7214. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7215. //special case for class attribute addition + removal
  7216. //so that class changes can tap into the animation
  7217. //hooks provided by the $animate service. Be sure to
  7218. //skip animations when the first digest occurs (when
  7219. //both the new and the old values are the same) since
  7220. //the CSS classes are the non-interpolated values
  7221. if (name === 'class' && newValue != oldValue) {
  7222. attr.$updateClass(newValue, oldValue);
  7223. } else {
  7224. attr.$set(name, newValue);
  7225. }
  7226. });
  7227. }
  7228. };
  7229. }
  7230. });
  7231. }
  7232. /**
  7233. * This is a special jqLite.replaceWith, which can replace items which
  7234. * have no parents, provided that the containing jqLite collection is provided.
  7235. *
  7236. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7237. * in the root of the tree.
  7238. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7239. * the shell, but replace its DOM node reference.
  7240. * @param {Node} newNode The new DOM node.
  7241. */
  7242. function replaceWith($rootElement, elementsToRemove, newNode) {
  7243. var firstElementToRemove = elementsToRemove[0],
  7244. removeCount = elementsToRemove.length,
  7245. parent = firstElementToRemove.parentNode,
  7246. i, ii;
  7247. if ($rootElement) {
  7248. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7249. if ($rootElement[i] == firstElementToRemove) {
  7250. $rootElement[i++] = newNode;
  7251. for (var j = i, j2 = j + removeCount - 1,
  7252. jj = $rootElement.length;
  7253. j < jj; j++, j2++) {
  7254. if (j2 < jj) {
  7255. $rootElement[j] = $rootElement[j2];
  7256. } else {
  7257. delete $rootElement[j];
  7258. }
  7259. }
  7260. $rootElement.length -= removeCount - 1;
  7261. // If the replaced element is also the jQuery .context then replace it
  7262. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7263. // http://api.jquery.com/context/
  7264. if ($rootElement.context === firstElementToRemove) {
  7265. $rootElement.context = newNode;
  7266. }
  7267. break;
  7268. }
  7269. }
  7270. }
  7271. if (parent) {
  7272. parent.replaceChild(newNode, firstElementToRemove);
  7273. }
  7274. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7275. var fragment = document.createDocumentFragment();
  7276. fragment.appendChild(firstElementToRemove);
  7277. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7278. // data here because there's no public interface in jQuery to do that and copying over
  7279. // event listeners (which is the main use of private data) wouldn't work anyway.
  7280. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7281. // Remove data of the replaced element. We cannot just call .remove()
  7282. // on the element it since that would deallocate scope that is needed
  7283. // for the new node. Instead, remove the data "manually".
  7284. if (!jQuery) {
  7285. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7286. } else {
  7287. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7288. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7289. // the scope to be trashed and we do need the very same scope to work with the new
  7290. // element. However, we cannot just cache the non-patched version and use it here as
  7291. // that would break if another library patches the method after Angular does (one
  7292. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7293. // skipped this one time.
  7294. skipDestroyOnNextJQueryCleanData = true;
  7295. jQuery.cleanData([firstElementToRemove]);
  7296. }
  7297. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7298. var element = elementsToRemove[k];
  7299. jqLite(element).remove(); // must do this way to clean up expando
  7300. fragment.appendChild(element);
  7301. delete elementsToRemove[k];
  7302. }
  7303. elementsToRemove[0] = newNode;
  7304. elementsToRemove.length = 1;
  7305. }
  7306. function cloneAndAnnotateFn(fn, annotation) {
  7307. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7308. }
  7309. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7310. try {
  7311. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7312. } catch (e) {
  7313. $exceptionHandler(e, startingTag($element));
  7314. }
  7315. }
  7316. }];
  7317. }
  7318. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7319. /**
  7320. * Converts all accepted directives format into proper directive name.
  7321. * All of these will become 'myDirective':
  7322. * my:Directive
  7323. * my-directive
  7324. * x-my-directive
  7325. * data-my:directive
  7326. *
  7327. * Also there is special case for Moz prefix starting with upper case letter.
  7328. * @param name Name to normalize
  7329. */
  7330. function directiveNormalize(name) {
  7331. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7332. }
  7333. /**
  7334. * @ngdoc type
  7335. * @name $compile.directive.Attributes
  7336. *
  7337. * @description
  7338. * A shared object between directive compile / linking functions which contains normalized DOM
  7339. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7340. * needed since all of these are treated as equivalent in Angular:
  7341. *
  7342. * ```
  7343. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7344. * ```
  7345. */
  7346. /**
  7347. * @ngdoc property
  7348. * @name $compile.directive.Attributes#$attr
  7349. *
  7350. * @description
  7351. * A map of DOM element attribute names to the normalized name. This is
  7352. * needed to do reverse lookup from normalized name back to actual name.
  7353. */
  7354. /**
  7355. * @ngdoc method
  7356. * @name $compile.directive.Attributes#$set
  7357. * @kind function
  7358. *
  7359. * @description
  7360. * Set DOM element attribute value.
  7361. *
  7362. *
  7363. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7364. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7365. * property to the original name.
  7366. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7367. */
  7368. /**
  7369. * Closure compiler type information
  7370. */
  7371. function nodesetLinkingFn(
  7372. /* angular.Scope */ scope,
  7373. /* NodeList */ nodeList,
  7374. /* Element */ rootElement,
  7375. /* function(Function) */ boundTranscludeFn
  7376. ) {}
  7377. function directiveLinkingFn(
  7378. /* nodesetLinkingFn */ nodesetLinkingFn,
  7379. /* angular.Scope */ scope,
  7380. /* Node */ node,
  7381. /* Element */ rootElement,
  7382. /* function(Function) */ boundTranscludeFn
  7383. ) {}
  7384. function tokenDifference(str1, str2) {
  7385. var values = '',
  7386. tokens1 = str1.split(/\s+/),
  7387. tokens2 = str2.split(/\s+/);
  7388. outer:
  7389. for (var i = 0; i < tokens1.length; i++) {
  7390. var token = tokens1[i];
  7391. for (var j = 0; j < tokens2.length; j++) {
  7392. if (token == tokens2[j]) continue outer;
  7393. }
  7394. values += (values.length > 0 ? ' ' : '') + token;
  7395. }
  7396. return values;
  7397. }
  7398. function removeComments(jqNodes) {
  7399. jqNodes = jqLite(jqNodes);
  7400. var i = jqNodes.length;
  7401. if (i <= 1) {
  7402. return jqNodes;
  7403. }
  7404. while (i--) {
  7405. var node = jqNodes[i];
  7406. if (node.nodeType === NODE_TYPE_COMMENT) {
  7407. splice.call(jqNodes, i, 1);
  7408. }
  7409. }
  7410. return jqNodes;
  7411. }
  7412. /**
  7413. * @ngdoc provider
  7414. * @name $controllerProvider
  7415. * @description
  7416. * The {@link ng.$controller $controller service} is used by Angular to create new
  7417. * controllers.
  7418. *
  7419. * This provider allows controller registration via the
  7420. * {@link ng.$controllerProvider#register register} method.
  7421. */
  7422. function $ControllerProvider() {
  7423. var controllers = {},
  7424. globals = false,
  7425. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7426. /**
  7427. * @ngdoc method
  7428. * @name $controllerProvider#register
  7429. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7430. * the names and the values are the constructors.
  7431. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7432. * annotations in the array notation).
  7433. */
  7434. this.register = function(name, constructor) {
  7435. assertNotHasOwnProperty(name, 'controller');
  7436. if (isObject(name)) {
  7437. extend(controllers, name);
  7438. } else {
  7439. controllers[name] = constructor;
  7440. }
  7441. };
  7442. /**
  7443. * @ngdoc method
  7444. * @name $controllerProvider#allowGlobals
  7445. * @description If called, allows `$controller` to find controller constructors on `window`
  7446. */
  7447. this.allowGlobals = function() {
  7448. globals = true;
  7449. };
  7450. this.$get = ['$injector', '$window', function($injector, $window) {
  7451. /**
  7452. * @ngdoc service
  7453. * @name $controller
  7454. * @requires $injector
  7455. *
  7456. * @param {Function|string} constructor If called with a function then it's considered to be the
  7457. * controller constructor function. Otherwise it's considered to be a string which is used
  7458. * to retrieve the controller constructor using the following steps:
  7459. *
  7460. * * check if a controller with given name is registered via `$controllerProvider`
  7461. * * check if evaluating the string on the current scope returns a constructor
  7462. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7463. * `window` object (not recommended)
  7464. *
  7465. * @param {Object} locals Injection locals for Controller.
  7466. * @return {Object} Instance of given controller.
  7467. *
  7468. * @description
  7469. * `$controller` service is responsible for instantiating controllers.
  7470. *
  7471. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7472. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7473. */
  7474. return function(expression, locals, later, ident) {
  7475. // PRIVATE API:
  7476. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7477. // If true, $controller will allocate the object with the correct
  7478. // prototype chain, but will not invoke the controller until a returned
  7479. // callback is invoked.
  7480. // param `ident` --- An optional label which overrides the label parsed from the controller
  7481. // expression, if any.
  7482. var instance, match, constructor, identifier;
  7483. later = later === true;
  7484. if (ident && isString(ident)) {
  7485. identifier = ident;
  7486. }
  7487. if (isString(expression)) {
  7488. match = expression.match(CNTRL_REG),
  7489. constructor = match[1],
  7490. identifier = identifier || match[3];
  7491. expression = controllers.hasOwnProperty(constructor)
  7492. ? controllers[constructor]
  7493. : getter(locals.$scope, constructor, true) ||
  7494. (globals ? getter($window, constructor, true) : undefined);
  7495. assertArgFn(expression, constructor, true);
  7496. }
  7497. if (later) {
  7498. // Instantiate controller later:
  7499. // This machinery is used to create an instance of the object before calling the
  7500. // controller's constructor itself.
  7501. //
  7502. // This allows properties to be added to the controller before the constructor is
  7503. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7504. //
  7505. // This feature is not intended for use by applications, and is thus not documented
  7506. // publicly.
  7507. var Constructor = function() {};
  7508. Constructor.prototype = (isArray(expression) ?
  7509. expression[expression.length - 1] : expression).prototype;
  7510. instance = new Constructor();
  7511. if (identifier) {
  7512. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7513. }
  7514. return extend(function() {
  7515. $injector.invoke(expression, instance, locals, constructor);
  7516. return instance;
  7517. }, {
  7518. instance: instance,
  7519. identifier: identifier
  7520. });
  7521. }
  7522. instance = $injector.instantiate(expression, locals, constructor);
  7523. if (identifier) {
  7524. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7525. }
  7526. return instance;
  7527. };
  7528. function addIdentifier(locals, identifier, instance, name) {
  7529. if (!(locals && isObject(locals.$scope))) {
  7530. throw minErr('$controller')('noscp',
  7531. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7532. name, identifier);
  7533. }
  7534. locals.$scope[identifier] = instance;
  7535. }
  7536. }];
  7537. }
  7538. /**
  7539. * @ngdoc service
  7540. * @name $document
  7541. * @requires $window
  7542. *
  7543. * @description
  7544. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7545. *
  7546. * @example
  7547. <example module="documentExample">
  7548. <file name="index.html">
  7549. <div ng-controller="ExampleController">
  7550. <p>$document title: <b ng-bind="title"></b></p>
  7551. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7552. </div>
  7553. </file>
  7554. <file name="script.js">
  7555. angular.module('documentExample', [])
  7556. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7557. $scope.title = $document[0].title;
  7558. $scope.windowTitle = angular.element(window.document)[0].title;
  7559. }]);
  7560. </file>
  7561. </example>
  7562. */
  7563. function $DocumentProvider() {
  7564. this.$get = ['$window', function(window) {
  7565. return jqLite(window.document);
  7566. }];
  7567. }
  7568. /**
  7569. * @ngdoc service
  7570. * @name $exceptionHandler
  7571. * @requires ng.$log
  7572. *
  7573. * @description
  7574. * Any uncaught exception in angular expressions is delegated to this service.
  7575. * The default implementation simply delegates to `$log.error` which logs it into
  7576. * the browser console.
  7577. *
  7578. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7579. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7580. *
  7581. * ## Example:
  7582. *
  7583. * ```js
  7584. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  7585. * return function(exception, cause) {
  7586. * exception.message += ' (caused by "' + cause + '")';
  7587. * throw exception;
  7588. * };
  7589. * });
  7590. * ```
  7591. *
  7592. * This example will override the normal action of `$exceptionHandler`, to make angular
  7593. * exceptions fail hard when they happen, instead of just logging to the console.
  7594. *
  7595. * <hr />
  7596. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7597. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7598. * (unless executed during a digest).
  7599. *
  7600. * If you wish, you can manually delegate exceptions, e.g.
  7601. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7602. *
  7603. * @param {Error} exception Exception associated with the error.
  7604. * @param {string=} cause optional information about the context in which
  7605. * the error was thrown.
  7606. *
  7607. */
  7608. function $ExceptionHandlerProvider() {
  7609. this.$get = ['$log', function($log) {
  7610. return function(exception, cause) {
  7611. $log.error.apply($log, arguments);
  7612. };
  7613. }];
  7614. }
  7615. var APPLICATION_JSON = 'application/json';
  7616. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7617. var JSON_START = /^\s*(\[|\{[^\{])/;
  7618. var JSON_END = /[\}\]]\s*$/;
  7619. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  7620. function defaultHttpResponseTransform(data, headers) {
  7621. if (isString(data)) {
  7622. // strip json vulnerability protection prefix
  7623. data = data.replace(JSON_PROTECTION_PREFIX, '');
  7624. var contentType = headers('Content-Type');
  7625. if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0) ||
  7626. (JSON_START.test(data) && JSON_END.test(data))) {
  7627. data = fromJson(data);
  7628. }
  7629. }
  7630. return data;
  7631. }
  7632. /**
  7633. * Parse headers into key value object
  7634. *
  7635. * @param {string} headers Raw headers as a string
  7636. * @returns {Object} Parsed headers as key value object
  7637. */
  7638. function parseHeaders(headers) {
  7639. var parsed = {}, key, val, i;
  7640. if (!headers) return parsed;
  7641. forEach(headers.split('\n'), function(line) {
  7642. i = line.indexOf(':');
  7643. key = lowercase(trim(line.substr(0, i)));
  7644. val = trim(line.substr(i + 1));
  7645. if (key) {
  7646. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7647. }
  7648. });
  7649. return parsed;
  7650. }
  7651. /**
  7652. * Returns a function that provides access to parsed headers.
  7653. *
  7654. * Headers are lazy parsed when first requested.
  7655. * @see parseHeaders
  7656. *
  7657. * @param {(string|Object)} headers Headers to provide access to.
  7658. * @returns {function(string=)} Returns a getter function which if called with:
  7659. *
  7660. * - if called with single an argument returns a single header value or null
  7661. * - if called with no arguments returns an object containing all headers.
  7662. */
  7663. function headersGetter(headers) {
  7664. var headersObj = isObject(headers) ? headers : undefined;
  7665. return function(name) {
  7666. if (!headersObj) headersObj = parseHeaders(headers);
  7667. if (name) {
  7668. return headersObj[lowercase(name)] || null;
  7669. }
  7670. return headersObj;
  7671. };
  7672. }
  7673. /**
  7674. * Chain all given functions
  7675. *
  7676. * This function is used for both request and response transforming
  7677. *
  7678. * @param {*} data Data to transform.
  7679. * @param {function(string=)} headers Http headers getter fn.
  7680. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7681. * @returns {*} Transformed data.
  7682. */
  7683. function transformData(data, headers, fns) {
  7684. if (isFunction(fns))
  7685. return fns(data, headers);
  7686. forEach(fns, function(fn) {
  7687. data = fn(data, headers);
  7688. });
  7689. return data;
  7690. }
  7691. function isSuccess(status) {
  7692. return 200 <= status && status < 300;
  7693. }
  7694. /**
  7695. * @ngdoc provider
  7696. * @name $httpProvider
  7697. * @description
  7698. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7699. * */
  7700. function $HttpProvider() {
  7701. /**
  7702. * @ngdoc property
  7703. * @name $httpProvider#defaults
  7704. * @description
  7705. *
  7706. * Object containing default values for all {@link ng.$http $http} requests.
  7707. *
  7708. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7709. * Defaults value is `'XSRF-TOKEN'`.
  7710. *
  7711. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7712. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7713. *
  7714. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7715. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7716. * setting default headers.
  7717. * - **`defaults.headers.common`**
  7718. * - **`defaults.headers.post`**
  7719. * - **`defaults.headers.put`**
  7720. * - **`defaults.headers.patch`**
  7721. **/
  7722. var defaults = this.defaults = {
  7723. // transform incoming response data
  7724. transformResponse: [defaultHttpResponseTransform],
  7725. // transform outgoing request data
  7726. transformRequest: [function(d) {
  7727. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  7728. }],
  7729. // default headers
  7730. headers: {
  7731. common: {
  7732. 'Accept': 'application/json, text/plain, */*'
  7733. },
  7734. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7735. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7736. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7737. },
  7738. xsrfCookieName: 'XSRF-TOKEN',
  7739. xsrfHeaderName: 'X-XSRF-TOKEN'
  7740. };
  7741. var useApplyAsync = false;
  7742. /**
  7743. * @ngdoc method
  7744. * @name $httpProvider#useApplyAsync
  7745. * @description
  7746. *
  7747. * Configure $http service to combine processing of multiple http responses received at around
  7748. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7749. * significant performance improvement for bigger applications that make many HTTP requests
  7750. * concurrently (common during application bootstrap).
  7751. *
  7752. * Defaults to false. If no value is specifed, returns the current configured value.
  7753. *
  7754. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7755. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7756. * to load and share the same digest cycle.
  7757. *
  7758. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7759. * otherwise, returns the current configured value.
  7760. **/
  7761. this.useApplyAsync = function(value) {
  7762. if (isDefined(value)) {
  7763. useApplyAsync = !!value;
  7764. return this;
  7765. }
  7766. return useApplyAsync;
  7767. };
  7768. /**
  7769. * @ngdoc property
  7770. * @name $httpProvider#interceptors
  7771. * @description
  7772. *
  7773. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  7774. * pre-processing of request or postprocessing of responses.
  7775. *
  7776. * These service factories are ordered by request, i.e. they are applied in the same order as the
  7777. * array, on request, but reverse order, on response.
  7778. *
  7779. * {@link ng.$http#interceptors Interceptors detailed info}
  7780. **/
  7781. var interceptorFactories = this.interceptors = [];
  7782. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7783. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7784. var defaultCache = $cacheFactory('$http');
  7785. /**
  7786. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7787. * The reversal is needed so that we can build up the interception chain around the
  7788. * server request.
  7789. */
  7790. var reversedInterceptors = [];
  7791. forEach(interceptorFactories, function(interceptorFactory) {
  7792. reversedInterceptors.unshift(isString(interceptorFactory)
  7793. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7794. });
  7795. /**
  7796. * @ngdoc service
  7797. * @kind function
  7798. * @name $http
  7799. * @requires ng.$httpBackend
  7800. * @requires $cacheFactory
  7801. * @requires $rootScope
  7802. * @requires $q
  7803. * @requires $injector
  7804. *
  7805. * @description
  7806. * The `$http` service is a core Angular service that facilitates communication with the remote
  7807. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7808. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7809. *
  7810. * For unit testing applications that use `$http` service, see
  7811. * {@link ngMock.$httpBackend $httpBackend mock}.
  7812. *
  7813. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7814. * $resource} service.
  7815. *
  7816. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7817. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7818. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7819. *
  7820. *
  7821. * ## General usage
  7822. * The `$http` service is a function which takes a single argument — a configuration object —
  7823. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7824. * with two $http specific methods: `success` and `error`.
  7825. *
  7826. * ```js
  7827. * // Simple GET request example :
  7828. * $http.get('/someUrl').
  7829. * success(function(data, status, headers, config) {
  7830. * // this callback will be called asynchronously
  7831. * // when the response is available
  7832. * }).
  7833. * error(function(data, status, headers, config) {
  7834. * // called asynchronously if an error occurs
  7835. * // or server returns response with an error status.
  7836. * });
  7837. * ```
  7838. *
  7839. * ```js
  7840. * // Simple POST request example (passing data) :
  7841. * $http.post('/someUrl', {msg:'hello word!'}).
  7842. * success(function(data, status, headers, config) {
  7843. * // this callback will be called asynchronously
  7844. * // when the response is available
  7845. * }).
  7846. * error(function(data, status, headers, config) {
  7847. * // called asynchronously if an error occurs
  7848. * // or server returns response with an error status.
  7849. * });
  7850. * ```
  7851. *
  7852. *
  7853. * Since the returned value of calling the $http function is a `promise`, you can also use
  7854. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7855. * an object representing the response. See the API signature and type info below for more
  7856. * details.
  7857. *
  7858. * A response status code between 200 and 299 is considered a success status and
  7859. * will result in the success callback being called. Note that if the response is a redirect,
  7860. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  7861. * called for such responses.
  7862. *
  7863. * ## Writing Unit Tests that use $http
  7864. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  7865. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  7866. * request using trained responses.
  7867. *
  7868. * ```
  7869. * $httpBackend.expectGET(...);
  7870. * $http.get(...);
  7871. * $httpBackend.flush();
  7872. * ```
  7873. *
  7874. * ## Shortcut methods
  7875. *
  7876. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  7877. * request data must be passed in for POST/PUT requests.
  7878. *
  7879. * ```js
  7880. * $http.get('/someUrl').success(successCallback);
  7881. * $http.post('/someUrl', data).success(successCallback);
  7882. * ```
  7883. *
  7884. * Complete list of shortcut methods:
  7885. *
  7886. * - {@link ng.$http#get $http.get}
  7887. * - {@link ng.$http#head $http.head}
  7888. * - {@link ng.$http#post $http.post}
  7889. * - {@link ng.$http#put $http.put}
  7890. * - {@link ng.$http#delete $http.delete}
  7891. * - {@link ng.$http#jsonp $http.jsonp}
  7892. * - {@link ng.$http#patch $http.patch}
  7893. *
  7894. *
  7895. * ## Setting HTTP Headers
  7896. *
  7897. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  7898. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  7899. * object, which currently contains this default configuration:
  7900. *
  7901. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  7902. * - `Accept: application/json, text/plain, * / *`
  7903. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  7904. * - `Content-Type: application/json`
  7905. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  7906. * - `Content-Type: application/json`
  7907. *
  7908. * To add or overwrite these defaults, simply add or remove a property from these configuration
  7909. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  7910. * with the lowercased HTTP method name as the key, e.g.
  7911. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  7912. *
  7913. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  7914. * fashion. For example:
  7915. *
  7916. * ```
  7917. * module.run(function($http) {
  7918. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  7919. * });
  7920. * ```
  7921. *
  7922. * In addition, you can supply a `headers` property in the config object passed when
  7923. * calling `$http(config)`, which overrides the defaults without changing them globally.
  7924. *
  7925. *
  7926. * ## Transforming Requests and Responses
  7927. *
  7928. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  7929. * and `transformResponse`. These properties can be a single function that returns
  7930. * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions,
  7931. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  7932. *
  7933. * ### Default Transformations
  7934. *
  7935. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  7936. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  7937. * then these will be applied.
  7938. *
  7939. * You can augment or replace the default transformations by modifying these properties by adding to or
  7940. * replacing the array.
  7941. *
  7942. * Angular provides the following default transformations:
  7943. *
  7944. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  7945. *
  7946. * - If the `data` property of the request configuration object contains an object, serialize it
  7947. * into JSON format.
  7948. *
  7949. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  7950. *
  7951. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  7952. * - If JSON response is detected, deserialize it using a JSON parser.
  7953. *
  7954. *
  7955. * ### Overriding the Default Transformations Per Request
  7956. *
  7957. * If you wish override the request/response transformations only for a single request then provide
  7958. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  7959. * into `$http`.
  7960. *
  7961. * Note that if you provide these properties on the config object the default transformations will be
  7962. * overwritten. If you wish to augment the default transformations then you must include them in your
  7963. * local transformation array.
  7964. *
  7965. * The following code demonstrates adding a new response transformation to be run after the default response
  7966. * transformations have been run.
  7967. *
  7968. * ```js
  7969. * function appendTransform(defaults, transform) {
  7970. *
  7971. * // We can't guarantee that the default transformation is an array
  7972. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  7973. *
  7974. * // Append the new transformation to the defaults
  7975. * return defaults.concat(transform);
  7976. * }
  7977. *
  7978. * $http({
  7979. * url: '...',
  7980. * method: 'GET',
  7981. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  7982. * return doTransform(value);
  7983. * })
  7984. * });
  7985. * ```
  7986. *
  7987. *
  7988. * ## Caching
  7989. *
  7990. * To enable caching, set the request configuration `cache` property to `true` (to use default
  7991. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  7992. * When the cache is enabled, `$http` stores the response from the server in the specified
  7993. * cache. The next time the same request is made, the response is served from the cache without
  7994. * sending a request to the server.
  7995. *
  7996. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  7997. * the same way that real requests are.
  7998. *
  7999. * If there are multiple GET requests for the same URL that should be cached using the same
  8000. * cache, but the cache is not populated yet, only one request to the server will be made and
  8001. * the remaining requests will be fulfilled using the response from the first request.
  8002. *
  8003. * You can change the default cache to a new object (built with
  8004. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8005. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8006. * their `cache` property to `true` will now use this cache object.
  8007. *
  8008. * If you set the default cache to `false` then only requests that specify their own custom
  8009. * cache object will be cached.
  8010. *
  8011. * ## Interceptors
  8012. *
  8013. * Before you start creating interceptors, be sure to understand the
  8014. * {@link ng.$q $q and deferred/promise APIs}.
  8015. *
  8016. * For purposes of global error handling, authentication, or any kind of synchronous or
  8017. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8018. * able to intercept requests before they are handed to the server and
  8019. * responses before they are handed over to the application code that
  8020. * initiated these requests. The interceptors leverage the {@link ng.$q
  8021. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8022. *
  8023. * The interceptors are service factories that are registered with the `$httpProvider` by
  8024. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8025. * injected with dependencies (if specified) and returns the interceptor.
  8026. *
  8027. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8028. *
  8029. * * `request`: interceptors get called with a http `config` object. The function is free to
  8030. * modify the `config` object or create a new one. The function needs to return the `config`
  8031. * object directly, or a promise containing the `config` or a new `config` object.
  8032. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8033. * resolved with a rejection.
  8034. * * `response`: interceptors get called with http `response` object. The function is free to
  8035. * modify the `response` object or create a new one. The function needs to return the `response`
  8036. * object directly, or as a promise containing the `response` or a new `response` object.
  8037. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8038. * resolved with a rejection.
  8039. *
  8040. *
  8041. * ```js
  8042. * // register the interceptor as a service
  8043. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8044. * return {
  8045. * // optional method
  8046. * 'request': function(config) {
  8047. * // do something on success
  8048. * return config;
  8049. * },
  8050. *
  8051. * // optional method
  8052. * 'requestError': function(rejection) {
  8053. * // do something on error
  8054. * if (canRecover(rejection)) {
  8055. * return responseOrNewPromise
  8056. * }
  8057. * return $q.reject(rejection);
  8058. * },
  8059. *
  8060. *
  8061. *
  8062. * // optional method
  8063. * 'response': function(response) {
  8064. * // do something on success
  8065. * return response;
  8066. * },
  8067. *
  8068. * // optional method
  8069. * 'responseError': function(rejection) {
  8070. * // do something on error
  8071. * if (canRecover(rejection)) {
  8072. * return responseOrNewPromise
  8073. * }
  8074. * return $q.reject(rejection);
  8075. * }
  8076. * };
  8077. * });
  8078. *
  8079. * $httpProvider.interceptors.push('myHttpInterceptor');
  8080. *
  8081. *
  8082. * // alternatively, register the interceptor via an anonymous factory
  8083. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8084. * return {
  8085. * 'request': function(config) {
  8086. * // same as above
  8087. * },
  8088. *
  8089. * 'response': function(response) {
  8090. * // same as above
  8091. * }
  8092. * };
  8093. * });
  8094. * ```
  8095. *
  8096. * ## Security Considerations
  8097. *
  8098. * When designing web applications, consider security threats from:
  8099. *
  8100. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8101. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8102. *
  8103. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8104. * pre-configured with strategies that address these issues, but for this to work backend server
  8105. * cooperation is required.
  8106. *
  8107. * ### JSON Vulnerability Protection
  8108. *
  8109. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8110. * allows third party website to turn your JSON resource URL into
  8111. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8112. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8113. * Angular will automatically strip the prefix before processing it as JSON.
  8114. *
  8115. * For example if your server needs to return:
  8116. * ```js
  8117. * ['one','two']
  8118. * ```
  8119. *
  8120. * which is vulnerable to attack, your server can return:
  8121. * ```js
  8122. * )]}',
  8123. * ['one','two']
  8124. * ```
  8125. *
  8126. * Angular will strip the prefix, before processing the JSON.
  8127. *
  8128. *
  8129. * ### Cross Site Request Forgery (XSRF) Protection
  8130. *
  8131. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8132. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8133. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8134. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8135. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8136. * the XHR came from JavaScript running on your domain. The header will not be set for
  8137. * cross-domain requests.
  8138. *
  8139. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8140. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8141. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8142. * that only JavaScript running on your domain could have sent the request. The token must be
  8143. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8144. * making up its own tokens). We recommend that the token is a digest of your site's
  8145. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8146. * for added security.
  8147. *
  8148. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8149. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8150. * or the per-request config object.
  8151. *
  8152. *
  8153. * @param {object} config Object describing the request to be made and how it should be
  8154. * processed. The object has following properties:
  8155. *
  8156. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8157. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8158. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8159. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8160. * JSONified.
  8161. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8162. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8163. * HTTP headers to send to the server. If the return value of a function is null, the
  8164. * header will not be sent.
  8165. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8166. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8167. * - **transformRequest** –
  8168. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8169. * transform function or an array of such functions. The transform function takes the http
  8170. * request body and headers and returns its transformed (typically serialized) version.
  8171. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8172. * - **transformResponse** –
  8173. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8174. * transform function or an array of such functions. The transform function takes the http
  8175. * response body and headers and returns its transformed (typically deserialized) version.
  8176. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8177. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8178. * GET request, otherwise if a cache instance built with
  8179. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8180. * caching.
  8181. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8182. * that should abort the request when resolved.
  8183. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8184. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8185. * for more information.
  8186. * - **responseType** - `{string}` - see
  8187. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8188. *
  8189. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8190. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8191. * method takes two arguments a success and an error callback which will be called with a
  8192. * response object. The `success` and `error` methods take a single argument - a function that
  8193. * will be called when the request succeeds or fails respectively. The arguments passed into
  8194. * these functions are destructured representation of the response object passed into the
  8195. * `then` method. The response object has these properties:
  8196. *
  8197. * - **data** – `{string|Object}` – The response body transformed with the transform
  8198. * functions.
  8199. * - **status** – `{number}` – HTTP status code of the response.
  8200. * - **headers** – `{function([headerName])}` – Header getter function.
  8201. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8202. * - **statusText** – `{string}` – HTTP status text of the response.
  8203. *
  8204. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8205. * requests. This is primarily meant to be used for debugging purposes.
  8206. *
  8207. *
  8208. * @example
  8209. <example module="httpExample">
  8210. <file name="index.html">
  8211. <div ng-controller="FetchController">
  8212. <select ng-model="method">
  8213. <option>GET</option>
  8214. <option>JSONP</option>
  8215. </select>
  8216. <input type="text" ng-model="url" size="80"/>
  8217. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8218. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8219. <button id="samplejsonpbtn"
  8220. ng-click="updateModel('JSONP',
  8221. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8222. Sample JSONP
  8223. </button>
  8224. <button id="invalidjsonpbtn"
  8225. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8226. Invalid JSONP
  8227. </button>
  8228. <pre>http status code: {{status}}</pre>
  8229. <pre>http response data: {{data}}</pre>
  8230. </div>
  8231. </file>
  8232. <file name="script.js">
  8233. angular.module('httpExample', [])
  8234. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8235. function($scope, $http, $templateCache) {
  8236. $scope.method = 'GET';
  8237. $scope.url = 'http-hello.html';
  8238. $scope.fetch = function() {
  8239. $scope.code = null;
  8240. $scope.response = null;
  8241. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8242. success(function(data, status) {
  8243. $scope.status = status;
  8244. $scope.data = data;
  8245. }).
  8246. error(function(data, status) {
  8247. $scope.data = data || "Request failed";
  8248. $scope.status = status;
  8249. });
  8250. };
  8251. $scope.updateModel = function(method, url) {
  8252. $scope.method = method;
  8253. $scope.url = url;
  8254. };
  8255. }]);
  8256. </file>
  8257. <file name="http-hello.html">
  8258. Hello, $http!
  8259. </file>
  8260. <file name="protractor.js" type="protractor">
  8261. var status = element(by.binding('status'));
  8262. var data = element(by.binding('data'));
  8263. var fetchBtn = element(by.id('fetchbtn'));
  8264. var sampleGetBtn = element(by.id('samplegetbtn'));
  8265. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8266. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8267. it('should make an xhr GET request', function() {
  8268. sampleGetBtn.click();
  8269. fetchBtn.click();
  8270. expect(status.getText()).toMatch('200');
  8271. expect(data.getText()).toMatch(/Hello, \$http!/);
  8272. });
  8273. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8274. // it('should make a JSONP request to angularjs.org', function() {
  8275. // sampleJsonpBtn.click();
  8276. // fetchBtn.click();
  8277. // expect(status.getText()).toMatch('200');
  8278. // expect(data.getText()).toMatch(/Super Hero!/);
  8279. // });
  8280. it('should make JSONP request to invalid URL and invoke the error handler',
  8281. function() {
  8282. invalidJsonpBtn.click();
  8283. fetchBtn.click();
  8284. expect(status.getText()).toMatch('0');
  8285. expect(data.getText()).toMatch('Request failed');
  8286. });
  8287. </file>
  8288. </example>
  8289. */
  8290. function $http(requestConfig) {
  8291. var config = {
  8292. method: 'get',
  8293. transformRequest: defaults.transformRequest,
  8294. transformResponse: defaults.transformResponse
  8295. };
  8296. var headers = mergeHeaders(requestConfig);
  8297. extend(config, requestConfig);
  8298. config.headers = headers;
  8299. config.method = uppercase(config.method);
  8300. var serverRequest = function(config) {
  8301. headers = config.headers;
  8302. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  8303. // strip content-type if data is undefined
  8304. if (isUndefined(reqData)) {
  8305. forEach(headers, function(value, header) {
  8306. if (lowercase(header) === 'content-type') {
  8307. delete headers[header];
  8308. }
  8309. });
  8310. }
  8311. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8312. config.withCredentials = defaults.withCredentials;
  8313. }
  8314. // send request
  8315. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  8316. };
  8317. var chain = [serverRequest, undefined];
  8318. var promise = $q.when(config);
  8319. // apply interceptors
  8320. forEach(reversedInterceptors, function(interceptor) {
  8321. if (interceptor.request || interceptor.requestError) {
  8322. chain.unshift(interceptor.request, interceptor.requestError);
  8323. }
  8324. if (interceptor.response || interceptor.responseError) {
  8325. chain.push(interceptor.response, interceptor.responseError);
  8326. }
  8327. });
  8328. while (chain.length) {
  8329. var thenFn = chain.shift();
  8330. var rejectFn = chain.shift();
  8331. promise = promise.then(thenFn, rejectFn);
  8332. }
  8333. promise.success = function(fn) {
  8334. promise.then(function(response) {
  8335. fn(response.data, response.status, response.headers, config);
  8336. });
  8337. return promise;
  8338. };
  8339. promise.error = function(fn) {
  8340. promise.then(null, function(response) {
  8341. fn(response.data, response.status, response.headers, config);
  8342. });
  8343. return promise;
  8344. };
  8345. return promise;
  8346. function transformResponse(response) {
  8347. // make a copy since the response must be cacheable
  8348. var resp = extend({}, response);
  8349. if (!response.data) {
  8350. resp.data = response.data;
  8351. } else {
  8352. resp.data = transformData(response.data, response.headers, config.transformResponse);
  8353. }
  8354. return (isSuccess(response.status))
  8355. ? resp
  8356. : $q.reject(resp);
  8357. }
  8358. function mergeHeaders(config) {
  8359. var defHeaders = defaults.headers,
  8360. reqHeaders = extend({}, config.headers),
  8361. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8362. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8363. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8364. defaultHeadersIteration:
  8365. for (defHeaderName in defHeaders) {
  8366. lowercaseDefHeaderName = lowercase(defHeaderName);
  8367. for (reqHeaderName in reqHeaders) {
  8368. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8369. continue defaultHeadersIteration;
  8370. }
  8371. }
  8372. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8373. }
  8374. // execute if header value is a function for merged headers
  8375. execHeaders(reqHeaders);
  8376. return reqHeaders;
  8377. function execHeaders(headers) {
  8378. var headerContent;
  8379. forEach(headers, function(headerFn, header) {
  8380. if (isFunction(headerFn)) {
  8381. headerContent = headerFn();
  8382. if (headerContent != null) {
  8383. headers[header] = headerContent;
  8384. } else {
  8385. delete headers[header];
  8386. }
  8387. }
  8388. });
  8389. }
  8390. }
  8391. }
  8392. $http.pendingRequests = [];
  8393. /**
  8394. * @ngdoc method
  8395. * @name $http#get
  8396. *
  8397. * @description
  8398. * Shortcut method to perform `GET` request.
  8399. *
  8400. * @param {string} url Relative or absolute URL specifying the destination of the request
  8401. * @param {Object=} config Optional configuration object
  8402. * @returns {HttpPromise} Future object
  8403. */
  8404. /**
  8405. * @ngdoc method
  8406. * @name $http#delete
  8407. *
  8408. * @description
  8409. * Shortcut method to perform `DELETE` request.
  8410. *
  8411. * @param {string} url Relative or absolute URL specifying the destination of the request
  8412. * @param {Object=} config Optional configuration object
  8413. * @returns {HttpPromise} Future object
  8414. */
  8415. /**
  8416. * @ngdoc method
  8417. * @name $http#head
  8418. *
  8419. * @description
  8420. * Shortcut method to perform `HEAD` request.
  8421. *
  8422. * @param {string} url Relative or absolute URL specifying the destination of the request
  8423. * @param {Object=} config Optional configuration object
  8424. * @returns {HttpPromise} Future object
  8425. */
  8426. /**
  8427. * @ngdoc method
  8428. * @name $http#jsonp
  8429. *
  8430. * @description
  8431. * Shortcut method to perform `JSONP` request.
  8432. *
  8433. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8434. * The name of the callback should be the string `JSON_CALLBACK`.
  8435. * @param {Object=} config Optional configuration object
  8436. * @returns {HttpPromise} Future object
  8437. */
  8438. createShortMethods('get', 'delete', 'head', 'jsonp');
  8439. /**
  8440. * @ngdoc method
  8441. * @name $http#post
  8442. *
  8443. * @description
  8444. * Shortcut method to perform `POST` request.
  8445. *
  8446. * @param {string} url Relative or absolute URL specifying the destination of the request
  8447. * @param {*} data Request content
  8448. * @param {Object=} config Optional configuration object
  8449. * @returns {HttpPromise} Future object
  8450. */
  8451. /**
  8452. * @ngdoc method
  8453. * @name $http#put
  8454. *
  8455. * @description
  8456. * Shortcut method to perform `PUT` request.
  8457. *
  8458. * @param {string} url Relative or absolute URL specifying the destination of the request
  8459. * @param {*} data Request content
  8460. * @param {Object=} config Optional configuration object
  8461. * @returns {HttpPromise} Future object
  8462. */
  8463. /**
  8464. * @ngdoc method
  8465. * @name $http#patch
  8466. *
  8467. * @description
  8468. * Shortcut method to perform `PATCH` request.
  8469. *
  8470. * @param {string} url Relative or absolute URL specifying the destination of the request
  8471. * @param {*} data Request content
  8472. * @param {Object=} config Optional configuration object
  8473. * @returns {HttpPromise} Future object
  8474. */
  8475. createShortMethodsWithData('post', 'put', 'patch');
  8476. /**
  8477. * @ngdoc property
  8478. * @name $http#defaults
  8479. *
  8480. * @description
  8481. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8482. * default headers, withCredentials as well as request and response transformations.
  8483. *
  8484. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8485. */
  8486. $http.defaults = defaults;
  8487. return $http;
  8488. function createShortMethods(names) {
  8489. forEach(arguments, function(name) {
  8490. $http[name] = function(url, config) {
  8491. return $http(extend(config || {}, {
  8492. method: name,
  8493. url: url
  8494. }));
  8495. };
  8496. });
  8497. }
  8498. function createShortMethodsWithData(name) {
  8499. forEach(arguments, function(name) {
  8500. $http[name] = function(url, data, config) {
  8501. return $http(extend(config || {}, {
  8502. method: name,
  8503. url: url,
  8504. data: data
  8505. }));
  8506. };
  8507. });
  8508. }
  8509. /**
  8510. * Makes the request.
  8511. *
  8512. * !!! ACCESSES CLOSURE VARS:
  8513. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8514. */
  8515. function sendReq(config, reqData, reqHeaders) {
  8516. var deferred = $q.defer(),
  8517. promise = deferred.promise,
  8518. cache,
  8519. cachedResp,
  8520. url = buildUrl(config.url, config.params);
  8521. $http.pendingRequests.push(config);
  8522. promise.then(removePendingReq, removePendingReq);
  8523. if ((config.cache || defaults.cache) && config.cache !== false &&
  8524. (config.method === 'GET' || config.method === 'JSONP')) {
  8525. cache = isObject(config.cache) ? config.cache
  8526. : isObject(defaults.cache) ? defaults.cache
  8527. : defaultCache;
  8528. }
  8529. if (cache) {
  8530. cachedResp = cache.get(url);
  8531. if (isDefined(cachedResp)) {
  8532. if (isPromiseLike(cachedResp)) {
  8533. // cached request has already been sent, but there is no response yet
  8534. cachedResp.then(removePendingReq, removePendingReq);
  8535. return cachedResp;
  8536. } else {
  8537. // serving from cache
  8538. if (isArray(cachedResp)) {
  8539. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8540. } else {
  8541. resolvePromise(cachedResp, 200, {}, 'OK');
  8542. }
  8543. }
  8544. } else {
  8545. // put the promise for the non-transformed response into cache as a placeholder
  8546. cache.put(url, promise);
  8547. }
  8548. }
  8549. // if we won't have the response in cache, set the xsrf headers and
  8550. // send the request to the backend
  8551. if (isUndefined(cachedResp)) {
  8552. var xsrfValue = urlIsSameOrigin(config.url)
  8553. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8554. : undefined;
  8555. if (xsrfValue) {
  8556. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8557. }
  8558. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8559. config.withCredentials, config.responseType);
  8560. }
  8561. return promise;
  8562. /**
  8563. * Callback registered to $httpBackend():
  8564. * - caches the response if desired
  8565. * - resolves the raw $http promise
  8566. * - calls $apply
  8567. */
  8568. function done(status, response, headersString, statusText) {
  8569. if (cache) {
  8570. if (isSuccess(status)) {
  8571. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8572. } else {
  8573. // remove promise from the cache
  8574. cache.remove(url);
  8575. }
  8576. }
  8577. function resolveHttpPromise() {
  8578. resolvePromise(response, status, headersString, statusText);
  8579. }
  8580. if (useApplyAsync) {
  8581. $rootScope.$applyAsync(resolveHttpPromise);
  8582. } else {
  8583. resolveHttpPromise();
  8584. if (!$rootScope.$$phase) $rootScope.$apply();
  8585. }
  8586. }
  8587. /**
  8588. * Resolves the raw $http promise.
  8589. */
  8590. function resolvePromise(response, status, headers, statusText) {
  8591. // normalize internal statuses to 0
  8592. status = Math.max(status, 0);
  8593. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8594. data: response,
  8595. status: status,
  8596. headers: headersGetter(headers),
  8597. config: config,
  8598. statusText: statusText
  8599. });
  8600. }
  8601. function removePendingReq() {
  8602. var idx = $http.pendingRequests.indexOf(config);
  8603. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8604. }
  8605. }
  8606. function buildUrl(url, params) {
  8607. if (!params) return url;
  8608. var parts = [];
  8609. forEachSorted(params, function(value, key) {
  8610. if (value === null || isUndefined(value)) return;
  8611. if (!isArray(value)) value = [value];
  8612. forEach(value, function(v) {
  8613. if (isObject(v)) {
  8614. if (isDate(v)) {
  8615. v = v.toISOString();
  8616. } else {
  8617. v = toJson(v);
  8618. }
  8619. }
  8620. parts.push(encodeUriQuery(key) + '=' +
  8621. encodeUriQuery(v));
  8622. });
  8623. });
  8624. if (parts.length > 0) {
  8625. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8626. }
  8627. return url;
  8628. }
  8629. }];
  8630. }
  8631. function createXhr() {
  8632. return new window.XMLHttpRequest();
  8633. }
  8634. /**
  8635. * @ngdoc service
  8636. * @name $httpBackend
  8637. * @requires $window
  8638. * @requires $document
  8639. *
  8640. * @description
  8641. * HTTP backend used by the {@link ng.$http service} that delegates to
  8642. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8643. *
  8644. * You should never need to use this service directly, instead use the higher-level abstractions:
  8645. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8646. *
  8647. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8648. * $httpBackend} which can be trained with responses.
  8649. */
  8650. function $HttpBackendProvider() {
  8651. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8652. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8653. }];
  8654. }
  8655. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8656. // TODO(vojta): fix the signature
  8657. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8658. $browser.$$incOutstandingRequestCount();
  8659. url = url || $browser.url();
  8660. if (lowercase(method) == 'jsonp') {
  8661. var callbackId = '_' + (callbacks.counter++).toString(36);
  8662. callbacks[callbackId] = function(data) {
  8663. callbacks[callbackId].data = data;
  8664. callbacks[callbackId].called = true;
  8665. };
  8666. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8667. callbackId, function(status, text) {
  8668. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8669. callbacks[callbackId] = noop;
  8670. });
  8671. } else {
  8672. var xhr = createXhr();
  8673. xhr.open(method, url, true);
  8674. forEach(headers, function(value, key) {
  8675. if (isDefined(value)) {
  8676. xhr.setRequestHeader(key, value);
  8677. }
  8678. });
  8679. xhr.onload = function requestLoaded() {
  8680. var statusText = xhr.statusText || '';
  8681. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8682. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8683. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8684. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8685. var status = xhr.status === 1223 ? 204 : xhr.status;
  8686. // fix status code when it is 0 (0 status is undocumented).
  8687. // Occurs when accessing file resources or on Android 4.1 stock browser
  8688. // while retrieving files from application cache.
  8689. if (status === 0) {
  8690. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8691. }
  8692. completeRequest(callback,
  8693. status,
  8694. response,
  8695. xhr.getAllResponseHeaders(),
  8696. statusText);
  8697. };
  8698. var requestError = function() {
  8699. // The response is always empty
  8700. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8701. completeRequest(callback, -1, null, null, '');
  8702. };
  8703. xhr.onerror = requestError;
  8704. xhr.onabort = requestError;
  8705. if (withCredentials) {
  8706. xhr.withCredentials = true;
  8707. }
  8708. if (responseType) {
  8709. try {
  8710. xhr.responseType = responseType;
  8711. } catch (e) {
  8712. // WebKit added support for the json responseType value on 09/03/2013
  8713. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8714. // known to throw when setting the value "json" as the response type. Other older
  8715. // browsers implementing the responseType
  8716. //
  8717. // The json response type can be ignored if not supported, because JSON payloads are
  8718. // parsed on the client-side regardless.
  8719. if (responseType !== 'json') {
  8720. throw e;
  8721. }
  8722. }
  8723. }
  8724. xhr.send(post || null);
  8725. }
  8726. if (timeout > 0) {
  8727. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8728. } else if (isPromiseLike(timeout)) {
  8729. timeout.then(timeoutRequest);
  8730. }
  8731. function timeoutRequest() {
  8732. jsonpDone && jsonpDone();
  8733. xhr && xhr.abort();
  8734. }
  8735. function completeRequest(callback, status, response, headersString, statusText) {
  8736. // cancel timeout and subsequent timeout promise resolution
  8737. timeoutId && $browserDefer.cancel(timeoutId);
  8738. jsonpDone = xhr = null;
  8739. callback(status, response, headersString, statusText);
  8740. $browser.$$completeOutstandingRequest(noop);
  8741. }
  8742. };
  8743. function jsonpReq(url, callbackId, done) {
  8744. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8745. // - fetches local scripts via XHR and evals them
  8746. // - adds and immediately removes script elements from the document
  8747. var script = rawDocument.createElement('script'), callback = null;
  8748. script.type = "text/javascript";
  8749. script.src = url;
  8750. script.async = true;
  8751. callback = function(event) {
  8752. removeEventListenerFn(script, "load", callback);
  8753. removeEventListenerFn(script, "error", callback);
  8754. rawDocument.body.removeChild(script);
  8755. script = null;
  8756. var status = -1;
  8757. var text = "unknown";
  8758. if (event) {
  8759. if (event.type === "load" && !callbacks[callbackId].called) {
  8760. event = { type: "error" };
  8761. }
  8762. text = event.type;
  8763. status = event.type === "error" ? 404 : 200;
  8764. }
  8765. if (done) {
  8766. done(status, text);
  8767. }
  8768. };
  8769. addEventListenerFn(script, "load", callback);
  8770. addEventListenerFn(script, "error", callback);
  8771. rawDocument.body.appendChild(script);
  8772. return callback;
  8773. }
  8774. }
  8775. var $interpolateMinErr = minErr('$interpolate');
  8776. /**
  8777. * @ngdoc provider
  8778. * @name $interpolateProvider
  8779. *
  8780. * @description
  8781. *
  8782. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8783. *
  8784. * @example
  8785. <example module="customInterpolationApp">
  8786. <file name="index.html">
  8787. <script>
  8788. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8789. customInterpolationApp.config(function($interpolateProvider) {
  8790. $interpolateProvider.startSymbol('//');
  8791. $interpolateProvider.endSymbol('//');
  8792. });
  8793. customInterpolationApp.controller('DemoController', function() {
  8794. this.label = "This binding is brought you by // interpolation symbols.";
  8795. });
  8796. </script>
  8797. <div ng-app="App" ng-controller="DemoController as demo">
  8798. //demo.label//
  8799. </div>
  8800. </file>
  8801. <file name="protractor.js" type="protractor">
  8802. it('should interpolate binding with custom symbols', function() {
  8803. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8804. });
  8805. </file>
  8806. </example>
  8807. */
  8808. function $InterpolateProvider() {
  8809. var startSymbol = '{{';
  8810. var endSymbol = '}}';
  8811. /**
  8812. * @ngdoc method
  8813. * @name $interpolateProvider#startSymbol
  8814. * @description
  8815. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8816. *
  8817. * @param {string=} value new value to set the starting symbol to.
  8818. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8819. */
  8820. this.startSymbol = function(value) {
  8821. if (value) {
  8822. startSymbol = value;
  8823. return this;
  8824. } else {
  8825. return startSymbol;
  8826. }
  8827. };
  8828. /**
  8829. * @ngdoc method
  8830. * @name $interpolateProvider#endSymbol
  8831. * @description
  8832. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8833. *
  8834. * @param {string=} value new value to set the ending symbol to.
  8835. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8836. */
  8837. this.endSymbol = function(value) {
  8838. if (value) {
  8839. endSymbol = value;
  8840. return this;
  8841. } else {
  8842. return endSymbol;
  8843. }
  8844. };
  8845. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  8846. var startSymbolLength = startSymbol.length,
  8847. endSymbolLength = endSymbol.length,
  8848. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  8849. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  8850. function escape(ch) {
  8851. return '\\\\\\' + ch;
  8852. }
  8853. /**
  8854. * @ngdoc service
  8855. * @name $interpolate
  8856. * @kind function
  8857. *
  8858. * @requires $parse
  8859. * @requires $sce
  8860. *
  8861. * @description
  8862. *
  8863. * Compiles a string with markup into an interpolation function. This service is used by the
  8864. * HTML {@link ng.$compile $compile} service for data binding. See
  8865. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  8866. * interpolation markup.
  8867. *
  8868. *
  8869. * ```js
  8870. * var $interpolate = ...; // injected
  8871. * var exp = $interpolate('Hello {{name | uppercase}}!');
  8872. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  8873. * ```
  8874. *
  8875. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  8876. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  8877. * evaluate to a value other than `undefined`.
  8878. *
  8879. * ```js
  8880. * var $interpolate = ...; // injected
  8881. * var context = {greeting: 'Hello', name: undefined };
  8882. *
  8883. * // default "forgiving" mode
  8884. * var exp = $interpolate('{{greeting}} {{name}}!');
  8885. * expect(exp(context)).toEqual('Hello !');
  8886. *
  8887. * // "allOrNothing" mode
  8888. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  8889. * expect(exp(context)).toBeUndefined();
  8890. * context.name = 'Angular';
  8891. * expect(exp(context)).toEqual('Hello Angular!');
  8892. * ```
  8893. *
  8894. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  8895. *
  8896. * ####Escaped Interpolation
  8897. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  8898. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  8899. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  8900. * or binding.
  8901. *
  8902. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  8903. * degree, while also enabling code examples to work without relying on the
  8904. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  8905. *
  8906. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  8907. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  8908. * interpolation start/end markers with their escaped counterparts.**
  8909. *
  8910. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  8911. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  8912. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  8913. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  8914. * this is typically useful only when user-data is used in rendering a template from the server, or
  8915. * when otherwise untrusted data is used by a directive.
  8916. *
  8917. * <example>
  8918. * <file name="index.html">
  8919. * <div ng-init="username='A user'">
  8920. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  8921. * </p>
  8922. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  8923. * application, but fails to accomplish their task, because the server has correctly
  8924. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  8925. * characters.</p>
  8926. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  8927. * from the database by an administrator.</p>
  8928. * </div>
  8929. * </file>
  8930. * </example>
  8931. *
  8932. * @param {string} text The text with markup to interpolate.
  8933. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  8934. * embedded expression in order to return an interpolation function. Strings with no
  8935. * embedded expression will return null for the interpolation function.
  8936. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  8937. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  8938. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  8939. * provides Strict Contextual Escaping for details.
  8940. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  8941. * unless all embedded expressions evaluate to a value other than `undefined`.
  8942. * @returns {function(context)} an interpolation function which is used to compute the
  8943. * interpolated string. The function has these parameters:
  8944. *
  8945. * - `context`: evaluation context for all expressions embedded in the interpolated text
  8946. */
  8947. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  8948. allOrNothing = !!allOrNothing;
  8949. var startIndex,
  8950. endIndex,
  8951. index = 0,
  8952. expressions = [],
  8953. parseFns = [],
  8954. textLength = text.length,
  8955. exp,
  8956. concat = [],
  8957. expressionPositions = [];
  8958. while (index < textLength) {
  8959. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  8960. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  8961. if (index !== startIndex) {
  8962. concat.push(unescapeText(text.substring(index, startIndex)));
  8963. }
  8964. exp = text.substring(startIndex + startSymbolLength, endIndex);
  8965. expressions.push(exp);
  8966. parseFns.push($parse(exp, parseStringifyInterceptor));
  8967. index = endIndex + endSymbolLength;
  8968. expressionPositions.push(concat.length);
  8969. concat.push('');
  8970. } else {
  8971. // we did not find an interpolation, so we have to add the remainder to the separators array
  8972. if (index !== textLength) {
  8973. concat.push(unescapeText(text.substring(index)));
  8974. }
  8975. break;
  8976. }
  8977. }
  8978. // Concatenating expressions makes it hard to reason about whether some combination of
  8979. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  8980. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  8981. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  8982. // make it obvious that you bound the value to some user controlled value. This helps reduce
  8983. // the load when auditing for XSS issues.
  8984. if (trustedContext && concat.length > 1) {
  8985. throw $interpolateMinErr('noconcat',
  8986. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  8987. "interpolations that concatenate multiple expressions when a trusted value is " +
  8988. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  8989. }
  8990. if (!mustHaveExpression || expressions.length) {
  8991. var compute = function(values) {
  8992. for (var i = 0, ii = expressions.length; i < ii; i++) {
  8993. if (allOrNothing && isUndefined(values[i])) return;
  8994. concat[expressionPositions[i]] = values[i];
  8995. }
  8996. return concat.join('');
  8997. };
  8998. var getValue = function(value) {
  8999. return trustedContext ?
  9000. $sce.getTrusted(trustedContext, value) :
  9001. $sce.valueOf(value);
  9002. };
  9003. var stringify = function(value) {
  9004. if (value == null) { // null || undefined
  9005. return '';
  9006. }
  9007. switch (typeof value) {
  9008. case 'string':
  9009. break;
  9010. case 'number':
  9011. value = '' + value;
  9012. break;
  9013. default:
  9014. value = toJson(value);
  9015. }
  9016. return value;
  9017. };
  9018. return extend(function interpolationFn(context) {
  9019. var i = 0;
  9020. var ii = expressions.length;
  9021. var values = new Array(ii);
  9022. try {
  9023. for (; i < ii; i++) {
  9024. values[i] = parseFns[i](context);
  9025. }
  9026. return compute(values);
  9027. } catch (err) {
  9028. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9029. err.toString());
  9030. $exceptionHandler(newErr);
  9031. }
  9032. }, {
  9033. // all of these properties are undocumented for now
  9034. exp: text, //just for compatibility with regular watchers created via $watch
  9035. expressions: expressions,
  9036. $$watchDelegate: function(scope, listener, objectEquality) {
  9037. var lastValue;
  9038. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9039. var currValue = compute(values);
  9040. if (isFunction(listener)) {
  9041. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9042. }
  9043. lastValue = currValue;
  9044. }, objectEquality);
  9045. }
  9046. });
  9047. }
  9048. function unescapeText(text) {
  9049. return text.replace(escapedStartRegexp, startSymbol).
  9050. replace(escapedEndRegexp, endSymbol);
  9051. }
  9052. function parseStringifyInterceptor(value) {
  9053. try {
  9054. return stringify(getValue(value));
  9055. } catch (err) {
  9056. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9057. err.toString());
  9058. $exceptionHandler(newErr);
  9059. }
  9060. }
  9061. }
  9062. /**
  9063. * @ngdoc method
  9064. * @name $interpolate#startSymbol
  9065. * @description
  9066. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9067. *
  9068. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9069. * the symbol.
  9070. *
  9071. * @returns {string} start symbol.
  9072. */
  9073. $interpolate.startSymbol = function() {
  9074. return startSymbol;
  9075. };
  9076. /**
  9077. * @ngdoc method
  9078. * @name $interpolate#endSymbol
  9079. * @description
  9080. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9081. *
  9082. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9083. * the symbol.
  9084. *
  9085. * @returns {string} end symbol.
  9086. */
  9087. $interpolate.endSymbol = function() {
  9088. return endSymbol;
  9089. };
  9090. return $interpolate;
  9091. }];
  9092. }
  9093. function $IntervalProvider() {
  9094. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9095. function($rootScope, $window, $q, $$q) {
  9096. var intervals = {};
  9097. /**
  9098. * @ngdoc service
  9099. * @name $interval
  9100. *
  9101. * @description
  9102. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9103. * milliseconds.
  9104. *
  9105. * The return value of registering an interval function is a promise. This promise will be
  9106. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9107. * run indefinitely if `count` is not defined. The value of the notification will be the
  9108. * number of iterations that have run.
  9109. * To cancel an interval, call `$interval.cancel(promise)`.
  9110. *
  9111. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9112. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9113. * time.
  9114. *
  9115. * <div class="alert alert-warning">
  9116. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9117. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9118. * directive's element are destroyed.
  9119. * You should take this into consideration and make sure to always cancel the interval at the
  9120. * appropriate moment. See the example below for more details on how and when to do this.
  9121. * </div>
  9122. *
  9123. * @param {function()} fn A function that should be called repeatedly.
  9124. * @param {number} delay Number of milliseconds between each function call.
  9125. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9126. * indefinitely.
  9127. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9128. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9129. * @returns {promise} A promise which will be notified on each iteration.
  9130. *
  9131. * @example
  9132. * <example module="intervalExample">
  9133. * <file name="index.html">
  9134. * <script>
  9135. * angular.module('intervalExample', [])
  9136. * .controller('ExampleController', ['$scope', '$interval',
  9137. * function($scope, $interval) {
  9138. * $scope.format = 'M/d/yy h:mm:ss a';
  9139. * $scope.blood_1 = 100;
  9140. * $scope.blood_2 = 120;
  9141. *
  9142. * var stop;
  9143. * $scope.fight = function() {
  9144. * // Don't start a new fight if we are already fighting
  9145. * if ( angular.isDefined(stop) ) return;
  9146. *
  9147. * stop = $interval(function() {
  9148. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9149. * $scope.blood_1 = $scope.blood_1 - 3;
  9150. * $scope.blood_2 = $scope.blood_2 - 4;
  9151. * } else {
  9152. * $scope.stopFight();
  9153. * }
  9154. * }, 100);
  9155. * };
  9156. *
  9157. * $scope.stopFight = function() {
  9158. * if (angular.isDefined(stop)) {
  9159. * $interval.cancel(stop);
  9160. * stop = undefined;
  9161. * }
  9162. * };
  9163. *
  9164. * $scope.resetFight = function() {
  9165. * $scope.blood_1 = 100;
  9166. * $scope.blood_2 = 120;
  9167. * };
  9168. *
  9169. * $scope.$on('$destroy', function() {
  9170. * // Make sure that the interval is destroyed too
  9171. * $scope.stopFight();
  9172. * });
  9173. * }])
  9174. * // Register the 'myCurrentTime' directive factory method.
  9175. * // We inject $interval and dateFilter service since the factory method is DI.
  9176. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9177. * function($interval, dateFilter) {
  9178. * // return the directive link function. (compile function not needed)
  9179. * return function(scope, element, attrs) {
  9180. * var format, // date format
  9181. * stopTime; // so that we can cancel the time updates
  9182. *
  9183. * // used to update the UI
  9184. * function updateTime() {
  9185. * element.text(dateFilter(new Date(), format));
  9186. * }
  9187. *
  9188. * // watch the expression, and update the UI on change.
  9189. * scope.$watch(attrs.myCurrentTime, function(value) {
  9190. * format = value;
  9191. * updateTime();
  9192. * });
  9193. *
  9194. * stopTime = $interval(updateTime, 1000);
  9195. *
  9196. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9197. * // to prevent updating time after the DOM element was removed.
  9198. * element.on('$destroy', function() {
  9199. * $interval.cancel(stopTime);
  9200. * });
  9201. * }
  9202. * }]);
  9203. * </script>
  9204. *
  9205. * <div>
  9206. * <div ng-controller="ExampleController">
  9207. * Date format: <input ng-model="format"> <hr/>
  9208. * Current time is: <span my-current-time="format"></span>
  9209. * <hr/>
  9210. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9211. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9212. * <button type="button" data-ng-click="fight()">Fight</button>
  9213. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9214. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9215. * </div>
  9216. * </div>
  9217. *
  9218. * </file>
  9219. * </example>
  9220. */
  9221. function interval(fn, delay, count, invokeApply) {
  9222. var setInterval = $window.setInterval,
  9223. clearInterval = $window.clearInterval,
  9224. iteration = 0,
  9225. skipApply = (isDefined(invokeApply) && !invokeApply),
  9226. deferred = (skipApply ? $$q : $q).defer(),
  9227. promise = deferred.promise;
  9228. count = isDefined(count) ? count : 0;
  9229. promise.then(null, null, fn);
  9230. promise.$$intervalId = setInterval(function tick() {
  9231. deferred.notify(iteration++);
  9232. if (count > 0 && iteration >= count) {
  9233. deferred.resolve(iteration);
  9234. clearInterval(promise.$$intervalId);
  9235. delete intervals[promise.$$intervalId];
  9236. }
  9237. if (!skipApply) $rootScope.$apply();
  9238. }, delay);
  9239. intervals[promise.$$intervalId] = deferred;
  9240. return promise;
  9241. }
  9242. /**
  9243. * @ngdoc method
  9244. * @name $interval#cancel
  9245. *
  9246. * @description
  9247. * Cancels a task associated with the `promise`.
  9248. *
  9249. * @param {promise} promise returned by the `$interval` function.
  9250. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9251. */
  9252. interval.cancel = function(promise) {
  9253. if (promise && promise.$$intervalId in intervals) {
  9254. intervals[promise.$$intervalId].reject('canceled');
  9255. $window.clearInterval(promise.$$intervalId);
  9256. delete intervals[promise.$$intervalId];
  9257. return true;
  9258. }
  9259. return false;
  9260. };
  9261. return interval;
  9262. }];
  9263. }
  9264. /**
  9265. * @ngdoc service
  9266. * @name $locale
  9267. *
  9268. * @description
  9269. * $locale service provides localization rules for various Angular components. As of right now the
  9270. * only public api is:
  9271. *
  9272. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9273. */
  9274. function $LocaleProvider() {
  9275. this.$get = function() {
  9276. return {
  9277. id: 'en-us',
  9278. NUMBER_FORMATS: {
  9279. DECIMAL_SEP: '.',
  9280. GROUP_SEP: ',',
  9281. PATTERNS: [
  9282. { // Decimal Pattern
  9283. minInt: 1,
  9284. minFrac: 0,
  9285. maxFrac: 3,
  9286. posPre: '',
  9287. posSuf: '',
  9288. negPre: '-',
  9289. negSuf: '',
  9290. gSize: 3,
  9291. lgSize: 3
  9292. },{ //Currency Pattern
  9293. minInt: 1,
  9294. minFrac: 2,
  9295. maxFrac: 2,
  9296. posPre: '\u00A4',
  9297. posSuf: '',
  9298. negPre: '(\u00A4',
  9299. negSuf: ')',
  9300. gSize: 3,
  9301. lgSize: 3
  9302. }
  9303. ],
  9304. CURRENCY_SYM: '$'
  9305. },
  9306. DATETIME_FORMATS: {
  9307. MONTH:
  9308. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9309. .split(','),
  9310. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9311. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9312. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9313. AMPMS: ['AM','PM'],
  9314. medium: 'MMM d, y h:mm:ss a',
  9315. 'short': 'M/d/yy h:mm a',
  9316. fullDate: 'EEEE, MMMM d, y',
  9317. longDate: 'MMMM d, y',
  9318. mediumDate: 'MMM d, y',
  9319. shortDate: 'M/d/yy',
  9320. mediumTime: 'h:mm:ss a',
  9321. shortTime: 'h:mm a'
  9322. },
  9323. pluralCat: function(num) {
  9324. if (num === 1) {
  9325. return 'one';
  9326. }
  9327. return 'other';
  9328. }
  9329. };
  9330. };
  9331. }
  9332. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9333. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9334. var $locationMinErr = minErr('$location');
  9335. /**
  9336. * Encode path using encodeUriSegment, ignoring forward slashes
  9337. *
  9338. * @param {string} path Path to encode
  9339. * @returns {string}
  9340. */
  9341. function encodePath(path) {
  9342. var segments = path.split('/'),
  9343. i = segments.length;
  9344. while (i--) {
  9345. segments[i] = encodeUriSegment(segments[i]);
  9346. }
  9347. return segments.join('/');
  9348. }
  9349. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  9350. var parsedUrl = urlResolve(absoluteUrl, appBase);
  9351. locationObj.$$protocol = parsedUrl.protocol;
  9352. locationObj.$$host = parsedUrl.hostname;
  9353. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9354. }
  9355. function parseAppUrl(relativeUrl, locationObj, appBase) {
  9356. var prefixed = (relativeUrl.charAt(0) !== '/');
  9357. if (prefixed) {
  9358. relativeUrl = '/' + relativeUrl;
  9359. }
  9360. var match = urlResolve(relativeUrl, appBase);
  9361. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9362. match.pathname.substring(1) : match.pathname);
  9363. locationObj.$$search = parseKeyValue(match.search);
  9364. locationObj.$$hash = decodeURIComponent(match.hash);
  9365. // make sure path starts with '/';
  9366. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9367. locationObj.$$path = '/' + locationObj.$$path;
  9368. }
  9369. }
  9370. /**
  9371. *
  9372. * @param {string} begin
  9373. * @param {string} whole
  9374. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9375. * expected string.
  9376. */
  9377. function beginsWith(begin, whole) {
  9378. if (whole.indexOf(begin) === 0) {
  9379. return whole.substr(begin.length);
  9380. }
  9381. }
  9382. function stripHash(url) {
  9383. var index = url.indexOf('#');
  9384. return index == -1 ? url : url.substr(0, index);
  9385. }
  9386. function stripFile(url) {
  9387. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9388. }
  9389. /* return the server only (scheme://host:port) */
  9390. function serverBase(url) {
  9391. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9392. }
  9393. /**
  9394. * LocationHtml5Url represents an url
  9395. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9396. *
  9397. * @constructor
  9398. * @param {string} appBase application base URL
  9399. * @param {string} basePrefix url path prefix
  9400. */
  9401. function LocationHtml5Url(appBase, basePrefix) {
  9402. this.$$html5 = true;
  9403. basePrefix = basePrefix || '';
  9404. var appBaseNoFile = stripFile(appBase);
  9405. parseAbsoluteUrl(appBase, this, appBase);
  9406. /**
  9407. * Parse given html5 (regular) url string into properties
  9408. * @param {string} url HTML5 url
  9409. * @private
  9410. */
  9411. this.$$parse = function(url) {
  9412. var pathUrl = beginsWith(appBaseNoFile, url);
  9413. if (!isString(pathUrl)) {
  9414. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9415. appBaseNoFile);
  9416. }
  9417. parseAppUrl(pathUrl, this, appBase);
  9418. if (!this.$$path) {
  9419. this.$$path = '/';
  9420. }
  9421. this.$$compose();
  9422. };
  9423. /**
  9424. * Compose url and update `absUrl` property
  9425. * @private
  9426. */
  9427. this.$$compose = function() {
  9428. var search = toKeyValue(this.$$search),
  9429. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9430. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9431. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9432. };
  9433. this.$$parseLinkUrl = function(url, relHref) {
  9434. if (relHref && relHref[0] === '#') {
  9435. // special case for links to hash fragments:
  9436. // keep the old url and only replace the hash fragment
  9437. this.hash(relHref.slice(1));
  9438. return true;
  9439. }
  9440. var appUrl, prevAppUrl;
  9441. var rewrittenUrl;
  9442. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  9443. prevAppUrl = appUrl;
  9444. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  9445. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9446. } else {
  9447. rewrittenUrl = appBase + prevAppUrl;
  9448. }
  9449. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  9450. rewrittenUrl = appBaseNoFile + appUrl;
  9451. } else if (appBaseNoFile == url + '/') {
  9452. rewrittenUrl = appBaseNoFile;
  9453. }
  9454. if (rewrittenUrl) {
  9455. this.$$parse(rewrittenUrl);
  9456. }
  9457. return !!rewrittenUrl;
  9458. };
  9459. }
  9460. /**
  9461. * LocationHashbangUrl represents url
  9462. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9463. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9464. *
  9465. * @constructor
  9466. * @param {string} appBase application base URL
  9467. * @param {string} hashPrefix hashbang prefix
  9468. */
  9469. function LocationHashbangUrl(appBase, hashPrefix) {
  9470. var appBaseNoFile = stripFile(appBase);
  9471. parseAbsoluteUrl(appBase, this, appBase);
  9472. /**
  9473. * Parse given hashbang url into properties
  9474. * @param {string} url Hashbang url
  9475. * @private
  9476. */
  9477. this.$$parse = function(url) {
  9478. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9479. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  9480. ? beginsWith(hashPrefix, withoutBaseUrl)
  9481. : (this.$$html5)
  9482. ? withoutBaseUrl
  9483. : '';
  9484. if (!isString(withoutHashUrl)) {
  9485. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  9486. hashPrefix);
  9487. }
  9488. parseAppUrl(withoutHashUrl, this, appBase);
  9489. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9490. this.$$compose();
  9491. /*
  9492. * In Windows, on an anchor node on documents loaded from
  9493. * the filesystem, the browser will return a pathname
  9494. * prefixed with the drive name ('/C:/path') when a
  9495. * pathname without a drive is set:
  9496. * * a.setAttribute('href', '/foo')
  9497. * * a.pathname === '/C:/foo' //true
  9498. *
  9499. * Inside of Angular, we're always using pathnames that
  9500. * do not include drive names for routing.
  9501. */
  9502. function removeWindowsDriveName(path, url, base) {
  9503. /*
  9504. Matches paths for file protocol on windows,
  9505. such as /C:/foo/bar, and captures only /foo/bar.
  9506. */
  9507. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9508. var firstPathSegmentMatch;
  9509. //Get the relative path from the input URL.
  9510. if (url.indexOf(base) === 0) {
  9511. url = url.replace(base, '');
  9512. }
  9513. // The input URL intentionally contains a first path segment that ends with a colon.
  9514. if (windowsFilePathExp.exec(url)) {
  9515. return path;
  9516. }
  9517. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9518. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9519. }
  9520. };
  9521. /**
  9522. * Compose hashbang url and update `absUrl` property
  9523. * @private
  9524. */
  9525. this.$$compose = function() {
  9526. var search = toKeyValue(this.$$search),
  9527. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9528. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9529. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9530. };
  9531. this.$$parseLinkUrl = function(url, relHref) {
  9532. if (stripHash(appBase) == stripHash(url)) {
  9533. this.$$parse(url);
  9534. return true;
  9535. }
  9536. return false;
  9537. };
  9538. }
  9539. /**
  9540. * LocationHashbangUrl represents url
  9541. * This object is exposed as $location service when html5 history api is enabled but the browser
  9542. * does not support it.
  9543. *
  9544. * @constructor
  9545. * @param {string} appBase application base URL
  9546. * @param {string} hashPrefix hashbang prefix
  9547. */
  9548. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9549. this.$$html5 = true;
  9550. LocationHashbangUrl.apply(this, arguments);
  9551. var appBaseNoFile = stripFile(appBase);
  9552. this.$$parseLinkUrl = function(url, relHref) {
  9553. if (relHref && relHref[0] === '#') {
  9554. // special case for links to hash fragments:
  9555. // keep the old url and only replace the hash fragment
  9556. this.hash(relHref.slice(1));
  9557. return true;
  9558. }
  9559. var rewrittenUrl;
  9560. var appUrl;
  9561. if (appBase == stripHash(url)) {
  9562. rewrittenUrl = url;
  9563. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  9564. rewrittenUrl = appBase + hashPrefix + appUrl;
  9565. } else if (appBaseNoFile === url + '/') {
  9566. rewrittenUrl = appBaseNoFile;
  9567. }
  9568. if (rewrittenUrl) {
  9569. this.$$parse(rewrittenUrl);
  9570. }
  9571. return !!rewrittenUrl;
  9572. };
  9573. this.$$compose = function() {
  9574. var search = toKeyValue(this.$$search),
  9575. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9576. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9577. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9578. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9579. };
  9580. }
  9581. var locationPrototype = {
  9582. /**
  9583. * Are we in html5 mode?
  9584. * @private
  9585. */
  9586. $$html5: false,
  9587. /**
  9588. * Has any change been replacing?
  9589. * @private
  9590. */
  9591. $$replace: false,
  9592. /**
  9593. * @ngdoc method
  9594. * @name $location#absUrl
  9595. *
  9596. * @description
  9597. * This method is getter only.
  9598. *
  9599. * Return full url representation with all segments encoded according to rules specified in
  9600. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9601. *
  9602. * @return {string} full url
  9603. */
  9604. absUrl: locationGetter('$$absUrl'),
  9605. /**
  9606. * @ngdoc method
  9607. * @name $location#url
  9608. *
  9609. * @description
  9610. * This method is getter / setter.
  9611. *
  9612. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9613. *
  9614. * Change path, search and hash, when called with parameter and return `$location`.
  9615. *
  9616. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9617. * @return {string} url
  9618. */
  9619. url: function(url) {
  9620. if (isUndefined(url))
  9621. return this.$$url;
  9622. var match = PATH_MATCH.exec(url);
  9623. if (match[1]) this.path(decodeURIComponent(match[1]));
  9624. if (match[2] || match[1]) this.search(match[3] || '');
  9625. this.hash(match[5] || '');
  9626. return this;
  9627. },
  9628. /**
  9629. * @ngdoc method
  9630. * @name $location#protocol
  9631. *
  9632. * @description
  9633. * This method is getter only.
  9634. *
  9635. * Return protocol of current url.
  9636. *
  9637. * @return {string} protocol of current url
  9638. */
  9639. protocol: locationGetter('$$protocol'),
  9640. /**
  9641. * @ngdoc method
  9642. * @name $location#host
  9643. *
  9644. * @description
  9645. * This method is getter only.
  9646. *
  9647. * Return host of current url.
  9648. *
  9649. * @return {string} host of current url.
  9650. */
  9651. host: locationGetter('$$host'),
  9652. /**
  9653. * @ngdoc method
  9654. * @name $location#port
  9655. *
  9656. * @description
  9657. * This method is getter only.
  9658. *
  9659. * Return port of current url.
  9660. *
  9661. * @return {Number} port
  9662. */
  9663. port: locationGetter('$$port'),
  9664. /**
  9665. * @ngdoc method
  9666. * @name $location#path
  9667. *
  9668. * @description
  9669. * This method is getter / setter.
  9670. *
  9671. * Return path of current url when called without any parameter.
  9672. *
  9673. * Change path when called with parameter and return `$location`.
  9674. *
  9675. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9676. * if it is missing.
  9677. *
  9678. * @param {(string|number)=} path New path
  9679. * @return {string} path
  9680. */
  9681. path: locationGetterSetter('$$path', function(path) {
  9682. path = path !== null ? path.toString() : '';
  9683. return path.charAt(0) == '/' ? path : '/' + path;
  9684. }),
  9685. /**
  9686. * @ngdoc method
  9687. * @name $location#search
  9688. *
  9689. * @description
  9690. * This method is getter / setter.
  9691. *
  9692. * Return search part (as object) of current url when called without any parameter.
  9693. *
  9694. * Change search part when called with parameter and return `$location`.
  9695. *
  9696. *
  9697. * ```js
  9698. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9699. * var searchObject = $location.search();
  9700. * // => {foo: 'bar', baz: 'xoxo'}
  9701. *
  9702. *
  9703. * // set foo to 'yipee'
  9704. * $location.search('foo', 'yipee');
  9705. * // => $location
  9706. * ```
  9707. *
  9708. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9709. * hash object.
  9710. *
  9711. * When called with a single argument the method acts as a setter, setting the `search` component
  9712. * of `$location` to the specified value.
  9713. *
  9714. * If the argument is a hash object containing an array of values, these values will be encoded
  9715. * as duplicate search parameters in the url.
  9716. *
  9717. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9718. * will override only a single search property.
  9719. *
  9720. * If `paramValue` is an array, it will override the property of the `search` component of
  9721. * `$location` specified via the first argument.
  9722. *
  9723. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9724. *
  9725. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9726. * value nor trailing equal sign.
  9727. *
  9728. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9729. * one or more arguments returns `$location` object itself.
  9730. */
  9731. search: function(search, paramValue) {
  9732. switch (arguments.length) {
  9733. case 0:
  9734. return this.$$search;
  9735. case 1:
  9736. if (isString(search) || isNumber(search)) {
  9737. search = search.toString();
  9738. this.$$search = parseKeyValue(search);
  9739. } else if (isObject(search)) {
  9740. search = copy(search, {});
  9741. // remove object undefined or null properties
  9742. forEach(search, function(value, key) {
  9743. if (value == null) delete search[key];
  9744. });
  9745. this.$$search = search;
  9746. } else {
  9747. throw $locationMinErr('isrcharg',
  9748. 'The first argument of the `$location#search()` call must be a string or an object.');
  9749. }
  9750. break;
  9751. default:
  9752. if (isUndefined(paramValue) || paramValue === null) {
  9753. delete this.$$search[search];
  9754. } else {
  9755. this.$$search[search] = paramValue;
  9756. }
  9757. }
  9758. this.$$compose();
  9759. return this;
  9760. },
  9761. /**
  9762. * @ngdoc method
  9763. * @name $location#hash
  9764. *
  9765. * @description
  9766. * This method is getter / setter.
  9767. *
  9768. * Return hash fragment when called without any parameter.
  9769. *
  9770. * Change hash fragment when called with parameter and return `$location`.
  9771. *
  9772. * @param {(string|number)=} hash New hash fragment
  9773. * @return {string} hash
  9774. */
  9775. hash: locationGetterSetter('$$hash', function(hash) {
  9776. return hash !== null ? hash.toString() : '';
  9777. }),
  9778. /**
  9779. * @ngdoc method
  9780. * @name $location#replace
  9781. *
  9782. * @description
  9783. * If called, all changes to $location during current `$digest` will be replacing current history
  9784. * record, instead of adding new one.
  9785. */
  9786. replace: function() {
  9787. this.$$replace = true;
  9788. return this;
  9789. }
  9790. };
  9791. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  9792. Location.prototype = Object.create(locationPrototype);
  9793. /**
  9794. * @ngdoc method
  9795. * @name $location#state
  9796. *
  9797. * @description
  9798. * This method is getter / setter.
  9799. *
  9800. * Return the history state object when called without any parameter.
  9801. *
  9802. * Change the history state object when called with one parameter and return `$location`.
  9803. * The state object is later passed to `pushState` or `replaceState`.
  9804. *
  9805. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  9806. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  9807. * older browsers (like IE9 or Android < 4.0), don't use this method.
  9808. *
  9809. * @param {object=} state State object for pushState or replaceState
  9810. * @return {object} state
  9811. */
  9812. Location.prototype.state = function(state) {
  9813. if (!arguments.length)
  9814. return this.$$state;
  9815. if (Location !== LocationHtml5Url || !this.$$html5) {
  9816. throw $locationMinErr('nostate', 'History API state support is available only ' +
  9817. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  9818. }
  9819. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  9820. // but we're changing the $$state reference to $browser.state() during the $digest
  9821. // so the modification window is narrow.
  9822. this.$$state = isUndefined(state) ? null : state;
  9823. return this;
  9824. };
  9825. });
  9826. function locationGetter(property) {
  9827. return function() {
  9828. return this[property];
  9829. };
  9830. }
  9831. function locationGetterSetter(property, preprocess) {
  9832. return function(value) {
  9833. if (isUndefined(value))
  9834. return this[property];
  9835. this[property] = preprocess(value);
  9836. this.$$compose();
  9837. return this;
  9838. };
  9839. }
  9840. /**
  9841. * @ngdoc service
  9842. * @name $location
  9843. *
  9844. * @requires $rootElement
  9845. *
  9846. * @description
  9847. * The $location service parses the URL in the browser address bar (based on the
  9848. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  9849. * available to your application. Changes to the URL in the address bar are reflected into
  9850. * $location service and changes to $location are reflected into the browser address bar.
  9851. *
  9852. * **The $location service:**
  9853. *
  9854. * - Exposes the current URL in the browser address bar, so you can
  9855. * - Watch and observe the URL.
  9856. * - Change the URL.
  9857. * - Synchronizes the URL with the browser when the user
  9858. * - Changes the address bar.
  9859. * - Clicks the back or forward button (or clicks a History link).
  9860. * - Clicks on a link.
  9861. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  9862. *
  9863. * For more information see {@link guide/$location Developer Guide: Using $location}
  9864. */
  9865. /**
  9866. * @ngdoc provider
  9867. * @name $locationProvider
  9868. * @description
  9869. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  9870. */
  9871. function $LocationProvider() {
  9872. var hashPrefix = '',
  9873. html5Mode = {
  9874. enabled: false,
  9875. requireBase: true,
  9876. rewriteLinks: true
  9877. };
  9878. /**
  9879. * @ngdoc method
  9880. * @name $locationProvider#hashPrefix
  9881. * @description
  9882. * @param {string=} prefix Prefix for hash part (containing path and search)
  9883. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9884. */
  9885. this.hashPrefix = function(prefix) {
  9886. if (isDefined(prefix)) {
  9887. hashPrefix = prefix;
  9888. return this;
  9889. } else {
  9890. return hashPrefix;
  9891. }
  9892. };
  9893. /**
  9894. * @ngdoc method
  9895. * @name $locationProvider#html5Mode
  9896. * @description
  9897. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  9898. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  9899. * properties:
  9900. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  9901. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  9902. * support `pushState`.
  9903. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  9904. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  9905. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  9906. * See the {@link guide/$location $location guide for more information}
  9907. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  9908. * enables/disables url rewriting for relative links.
  9909. *
  9910. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  9911. */
  9912. this.html5Mode = function(mode) {
  9913. if (isBoolean(mode)) {
  9914. html5Mode.enabled = mode;
  9915. return this;
  9916. } else if (isObject(mode)) {
  9917. if (isBoolean(mode.enabled)) {
  9918. html5Mode.enabled = mode.enabled;
  9919. }
  9920. if (isBoolean(mode.requireBase)) {
  9921. html5Mode.requireBase = mode.requireBase;
  9922. }
  9923. if (isBoolean(mode.rewriteLinks)) {
  9924. html5Mode.rewriteLinks = mode.rewriteLinks;
  9925. }
  9926. return this;
  9927. } else {
  9928. return html5Mode;
  9929. }
  9930. };
  9931. /**
  9932. * @ngdoc event
  9933. * @name $location#$locationChangeStart
  9934. * @eventType broadcast on root scope
  9935. * @description
  9936. * Broadcasted before a URL will change.
  9937. *
  9938. * This change can be prevented by calling
  9939. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  9940. * details about event object. Upon successful change
  9941. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  9942. *
  9943. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  9944. * the browser supports the HTML5 History API.
  9945. *
  9946. * @param {Object} angularEvent Synthetic event object.
  9947. * @param {string} newUrl New URL
  9948. * @param {string=} oldUrl URL that was before it was changed.
  9949. * @param {string=} newState New history state object
  9950. * @param {string=} oldState History state object that was before it was changed.
  9951. */
  9952. /**
  9953. * @ngdoc event
  9954. * @name $location#$locationChangeSuccess
  9955. * @eventType broadcast on root scope
  9956. * @description
  9957. * Broadcasted after a URL was changed.
  9958. *
  9959. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  9960. * the browser supports the HTML5 History API.
  9961. *
  9962. * @param {Object} angularEvent Synthetic event object.
  9963. * @param {string} newUrl New URL
  9964. * @param {string=} oldUrl URL that was before it was changed.
  9965. * @param {string=} newState New history state object
  9966. * @param {string=} oldState History state object that was before it was changed.
  9967. */
  9968. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  9969. function($rootScope, $browser, $sniffer, $rootElement) {
  9970. var $location,
  9971. LocationMode,
  9972. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  9973. initialUrl = $browser.url(),
  9974. appBase;
  9975. if (html5Mode.enabled) {
  9976. if (!baseHref && html5Mode.requireBase) {
  9977. throw $locationMinErr('nobase',
  9978. "$location in HTML5 mode requires a <base> tag to be present!");
  9979. }
  9980. appBase = serverBase(initialUrl) + (baseHref || '/');
  9981. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  9982. } else {
  9983. appBase = stripHash(initialUrl);
  9984. LocationMode = LocationHashbangUrl;
  9985. }
  9986. $location = new LocationMode(appBase, '#' + hashPrefix);
  9987. $location.$$parseLinkUrl(initialUrl, initialUrl);
  9988. $location.$$state = $browser.state();
  9989. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  9990. function setBrowserUrlWithFallback(url, replace, state) {
  9991. var oldUrl = $location.url();
  9992. var oldState = $location.$$state;
  9993. try {
  9994. $browser.url(url, replace, state);
  9995. // Make sure $location.state() returns referentially identical (not just deeply equal)
  9996. // state object; this makes possible quick checking if the state changed in the digest
  9997. // loop. Checking deep equality would be too expensive.
  9998. $location.$$state = $browser.state();
  9999. } catch (e) {
  10000. // Restore old values if pushState fails
  10001. $location.url(oldUrl);
  10002. $location.$$state = oldState;
  10003. throw e;
  10004. }
  10005. }
  10006. $rootElement.on('click', function(event) {
  10007. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10008. // currently we open nice url link and redirect then
  10009. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return;
  10010. var elm = jqLite(event.target);
  10011. // traverse the DOM up to find first A tag
  10012. while (nodeName_(elm[0]) !== 'a') {
  10013. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10014. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10015. }
  10016. var absHref = elm.prop('href');
  10017. // get the actual href attribute - see
  10018. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10019. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10020. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10021. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10022. // an animation.
  10023. absHref = urlResolve(absHref.animVal).href;
  10024. }
  10025. // Ignore when url is started with javascript: or mailto:
  10026. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10027. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10028. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10029. // We do a preventDefault for all urls that are part of the angular application,
  10030. // in html5mode and also without, so that we are able to abort navigation without
  10031. // getting double entries in the location history.
  10032. event.preventDefault();
  10033. // update location manually
  10034. if ($location.absUrl() != $browser.url()) {
  10035. $rootScope.$apply();
  10036. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10037. window.angular['ff-684208-preventDefault'] = true;
  10038. }
  10039. }
  10040. }
  10041. });
  10042. // rewrite hashbang url <> html5 url
  10043. if ($location.absUrl() != initialUrl) {
  10044. $browser.url($location.absUrl(), true);
  10045. }
  10046. var initializing = true;
  10047. // update $location when $browser url changes
  10048. $browser.onUrlChange(function(newUrl, newState) {
  10049. $rootScope.$evalAsync(function() {
  10050. var oldUrl = $location.absUrl();
  10051. var oldState = $location.$$state;
  10052. $location.$$parse(newUrl);
  10053. $location.$$state = newState;
  10054. if ($rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10055. newState, oldState).defaultPrevented) {
  10056. $location.$$parse(oldUrl);
  10057. $location.$$state = oldState;
  10058. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10059. } else {
  10060. initializing = false;
  10061. afterLocationChange(oldUrl, oldState);
  10062. }
  10063. });
  10064. if (!$rootScope.$$phase) $rootScope.$digest();
  10065. });
  10066. // update browser
  10067. $rootScope.$watch(function $locationWatch() {
  10068. var oldUrl = $browser.url();
  10069. var oldState = $browser.state();
  10070. var currentReplace = $location.$$replace;
  10071. var urlOrStateChanged = oldUrl !== $location.absUrl() ||
  10072. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10073. if (initializing || urlOrStateChanged) {
  10074. initializing = false;
  10075. $rootScope.$evalAsync(function() {
  10076. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl,
  10077. $location.$$state, oldState).defaultPrevented) {
  10078. $location.$$parse(oldUrl);
  10079. $location.$$state = oldState;
  10080. } else {
  10081. if (urlOrStateChanged) {
  10082. setBrowserUrlWithFallback($location.absUrl(), currentReplace,
  10083. oldState === $location.$$state ? null : $location.$$state);
  10084. }
  10085. afterLocationChange(oldUrl, oldState);
  10086. }
  10087. });
  10088. }
  10089. $location.$$replace = false;
  10090. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10091. // there is a change
  10092. });
  10093. return $location;
  10094. function afterLocationChange(oldUrl, oldState) {
  10095. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10096. $location.$$state, oldState);
  10097. }
  10098. }];
  10099. }
  10100. /**
  10101. * @ngdoc service
  10102. * @name $log
  10103. * @requires $window
  10104. *
  10105. * @description
  10106. * Simple service for logging. Default implementation safely writes the message
  10107. * into the browser's console (if present).
  10108. *
  10109. * The main purpose of this service is to simplify debugging and troubleshooting.
  10110. *
  10111. * The default is to log `debug` messages. You can use
  10112. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10113. *
  10114. * @example
  10115. <example module="logExample">
  10116. <file name="script.js">
  10117. angular.module('logExample', [])
  10118. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10119. $scope.$log = $log;
  10120. $scope.message = 'Hello World!';
  10121. }]);
  10122. </file>
  10123. <file name="index.html">
  10124. <div ng-controller="LogController">
  10125. <p>Reload this page with open console, enter text and hit the log button...</p>
  10126. Message:
  10127. <input type="text" ng-model="message"/>
  10128. <button ng-click="$log.log(message)">log</button>
  10129. <button ng-click="$log.warn(message)">warn</button>
  10130. <button ng-click="$log.info(message)">info</button>
  10131. <button ng-click="$log.error(message)">error</button>
  10132. </div>
  10133. </file>
  10134. </example>
  10135. */
  10136. /**
  10137. * @ngdoc provider
  10138. * @name $logProvider
  10139. * @description
  10140. * Use the `$logProvider` to configure how the application logs messages
  10141. */
  10142. function $LogProvider() {
  10143. var debug = true,
  10144. self = this;
  10145. /**
  10146. * @ngdoc method
  10147. * @name $logProvider#debugEnabled
  10148. * @description
  10149. * @param {boolean=} flag enable or disable debug level messages
  10150. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10151. */
  10152. this.debugEnabled = function(flag) {
  10153. if (isDefined(flag)) {
  10154. debug = flag;
  10155. return this;
  10156. } else {
  10157. return debug;
  10158. }
  10159. };
  10160. this.$get = ['$window', function($window) {
  10161. return {
  10162. /**
  10163. * @ngdoc method
  10164. * @name $log#log
  10165. *
  10166. * @description
  10167. * Write a log message
  10168. */
  10169. log: consoleLog('log'),
  10170. /**
  10171. * @ngdoc method
  10172. * @name $log#info
  10173. *
  10174. * @description
  10175. * Write an information message
  10176. */
  10177. info: consoleLog('info'),
  10178. /**
  10179. * @ngdoc method
  10180. * @name $log#warn
  10181. *
  10182. * @description
  10183. * Write a warning message
  10184. */
  10185. warn: consoleLog('warn'),
  10186. /**
  10187. * @ngdoc method
  10188. * @name $log#error
  10189. *
  10190. * @description
  10191. * Write an error message
  10192. */
  10193. error: consoleLog('error'),
  10194. /**
  10195. * @ngdoc method
  10196. * @name $log#debug
  10197. *
  10198. * @description
  10199. * Write a debug message
  10200. */
  10201. debug: (function() {
  10202. var fn = consoleLog('debug');
  10203. return function() {
  10204. if (debug) {
  10205. fn.apply(self, arguments);
  10206. }
  10207. };
  10208. }())
  10209. };
  10210. function formatError(arg) {
  10211. if (arg instanceof Error) {
  10212. if (arg.stack) {
  10213. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10214. ? 'Error: ' + arg.message + '\n' + arg.stack
  10215. : arg.stack;
  10216. } else if (arg.sourceURL) {
  10217. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10218. }
  10219. }
  10220. return arg;
  10221. }
  10222. function consoleLog(type) {
  10223. var console = $window.console || {},
  10224. logFn = console[type] || console.log || noop,
  10225. hasApply = false;
  10226. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10227. // The reason behind this is that console.log has type "object" in IE8...
  10228. try {
  10229. hasApply = !!logFn.apply;
  10230. } catch (e) {}
  10231. if (hasApply) {
  10232. return function() {
  10233. var args = [];
  10234. forEach(arguments, function(arg) {
  10235. args.push(formatError(arg));
  10236. });
  10237. return logFn.apply(console, args);
  10238. };
  10239. }
  10240. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10241. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10242. return function(arg1, arg2) {
  10243. logFn(arg1, arg2 == null ? '' : arg2);
  10244. };
  10245. }
  10246. }];
  10247. }
  10248. var $parseMinErr = minErr('$parse');
  10249. // Sandboxing Angular Expressions
  10250. // ------------------------------
  10251. // Angular expressions are generally considered safe because these expressions only have direct
  10252. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  10253. // obtaining a reference to native JS functions such as the Function constructor.
  10254. //
  10255. // As an example, consider the following Angular expression:
  10256. //
  10257. // {}.toString.constructor('alert("evil JS code")')
  10258. //
  10259. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10260. // against the expression language, but not to prevent exploits that were enabled by exposing
  10261. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  10262. // practice and therefore we are not even trying to protect against interaction with an object
  10263. // explicitly exposed in this way.
  10264. //
  10265. // In general, it is not possible to access a Window object from an angular expression unless a
  10266. // window or some DOM object that has a reference to window is published onto a Scope.
  10267. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10268. // native objects.
  10269. function ensureSafeMemberName(name, fullExpression) {
  10270. if (name === "__defineGetter__" || name === "__defineSetter__"
  10271. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10272. || name === "__proto__") {
  10273. throw $parseMinErr('isecfld',
  10274. 'Attempting to access a disallowed field in Angular expressions! '
  10275. +'Expression: {0}', fullExpression);
  10276. }
  10277. return name;
  10278. }
  10279. function ensureSafeObject(obj, fullExpression) {
  10280. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10281. if (obj) {
  10282. if (obj.constructor === obj) {
  10283. throw $parseMinErr('isecfn',
  10284. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10285. fullExpression);
  10286. } else if (// isWindow(obj)
  10287. obj.window === obj) {
  10288. throw $parseMinErr('isecwindow',
  10289. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10290. fullExpression);
  10291. } else if (// isElement(obj)
  10292. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10293. throw $parseMinErr('isecdom',
  10294. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10295. fullExpression);
  10296. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10297. obj === Object) {
  10298. throw $parseMinErr('isecobj',
  10299. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10300. fullExpression);
  10301. }
  10302. }
  10303. return obj;
  10304. }
  10305. var CALL = Function.prototype.call;
  10306. var APPLY = Function.prototype.apply;
  10307. var BIND = Function.prototype.bind;
  10308. function ensureSafeFunction(obj, fullExpression) {
  10309. if (obj) {
  10310. if (obj.constructor === obj) {
  10311. throw $parseMinErr('isecfn',
  10312. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10313. fullExpression);
  10314. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10315. throw $parseMinErr('isecff',
  10316. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10317. fullExpression);
  10318. }
  10319. }
  10320. }
  10321. //Keyword constants
  10322. var CONSTANTS = createMap();
  10323. forEach({
  10324. 'null': function() { return null; },
  10325. 'true': function() { return true; },
  10326. 'false': function() { return false; },
  10327. 'undefined': function() {}
  10328. }, function(constantGetter, name) {
  10329. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10330. CONSTANTS[name] = constantGetter;
  10331. });
  10332. //Not quite a constant, but can be lex/parsed the same
  10333. CONSTANTS['this'] = function(self) { return self; };
  10334. CONSTANTS['this'].sharedGetter = true;
  10335. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10336. var OPERATORS = extend(createMap(), {
  10337. '+':function(self, locals, a, b) {
  10338. a=a(self, locals); b=b(self, locals);
  10339. if (isDefined(a)) {
  10340. if (isDefined(b)) {
  10341. return a + b;
  10342. }
  10343. return a;
  10344. }
  10345. return isDefined(b)?b:undefined;},
  10346. '-':function(self, locals, a, b) {
  10347. a=a(self, locals); b=b(self, locals);
  10348. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  10349. },
  10350. '*':function(self, locals, a, b) {return a(self, locals)*b(self, locals);},
  10351. '/':function(self, locals, a, b) {return a(self, locals)/b(self, locals);},
  10352. '%':function(self, locals, a, b) {return a(self, locals)%b(self, locals);},
  10353. '===':function(self, locals, a, b) {return a(self, locals)===b(self, locals);},
  10354. '!==':function(self, locals, a, b) {return a(self, locals)!==b(self, locals);},
  10355. '==':function(self, locals, a, b) {return a(self, locals)==b(self, locals);},
  10356. '!=':function(self, locals, a, b) {return a(self, locals)!=b(self, locals);},
  10357. '<':function(self, locals, a, b) {return a(self, locals)<b(self, locals);},
  10358. '>':function(self, locals, a, b) {return a(self, locals)>b(self, locals);},
  10359. '<=':function(self, locals, a, b) {return a(self, locals)<=b(self, locals);},
  10360. '>=':function(self, locals, a, b) {return a(self, locals)>=b(self, locals);},
  10361. '&&':function(self, locals, a, b) {return a(self, locals)&&b(self, locals);},
  10362. '||':function(self, locals, a, b) {return a(self, locals)||b(self, locals);},
  10363. '!':function(self, locals, a) {return !a(self, locals);},
  10364. //Tokenized as operators but parsed as assignment/filters
  10365. '=':true,
  10366. '|':true
  10367. });
  10368. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10369. /////////////////////////////////////////
  10370. /**
  10371. * @constructor
  10372. */
  10373. var Lexer = function(options) {
  10374. this.options = options;
  10375. };
  10376. Lexer.prototype = {
  10377. constructor: Lexer,
  10378. lex: function(text) {
  10379. this.text = text;
  10380. this.index = 0;
  10381. this.ch = undefined;
  10382. this.tokens = [];
  10383. while (this.index < this.text.length) {
  10384. this.ch = this.text.charAt(this.index);
  10385. if (this.is('"\'')) {
  10386. this.readString(this.ch);
  10387. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  10388. this.readNumber();
  10389. } else if (this.isIdent(this.ch)) {
  10390. this.readIdent();
  10391. } else if (this.is('(){}[].,;:?')) {
  10392. this.tokens.push({
  10393. index: this.index,
  10394. text: this.ch
  10395. });
  10396. this.index++;
  10397. } else if (this.isWhitespace(this.ch)) {
  10398. this.index++;
  10399. } else {
  10400. var ch2 = this.ch + this.peek();
  10401. var ch3 = ch2 + this.peek(2);
  10402. var fn = OPERATORS[this.ch];
  10403. var fn2 = OPERATORS[ch2];
  10404. var fn3 = OPERATORS[ch3];
  10405. if (fn3) {
  10406. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  10407. this.index += 3;
  10408. } else if (fn2) {
  10409. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  10410. this.index += 2;
  10411. } else if (fn) {
  10412. this.tokens.push({
  10413. index: this.index,
  10414. text: this.ch,
  10415. fn: fn
  10416. });
  10417. this.index += 1;
  10418. } else {
  10419. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10420. }
  10421. }
  10422. }
  10423. return this.tokens;
  10424. },
  10425. is: function(chars) {
  10426. return chars.indexOf(this.ch) !== -1;
  10427. },
  10428. peek: function(i) {
  10429. var num = i || 1;
  10430. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10431. },
  10432. isNumber: function(ch) {
  10433. return ('0' <= ch && ch <= '9');
  10434. },
  10435. isWhitespace: function(ch) {
  10436. // IE treats non-breaking space as \u00A0
  10437. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10438. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10439. },
  10440. isIdent: function(ch) {
  10441. return ('a' <= ch && ch <= 'z' ||
  10442. 'A' <= ch && ch <= 'Z' ||
  10443. '_' === ch || ch === '$');
  10444. },
  10445. isExpOperator: function(ch) {
  10446. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10447. },
  10448. throwError: function(error, start, end) {
  10449. end = end || this.index;
  10450. var colStr = (isDefined(start)
  10451. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10452. : ' ' + end);
  10453. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10454. error, colStr, this.text);
  10455. },
  10456. readNumber: function() {
  10457. var number = '';
  10458. var start = this.index;
  10459. while (this.index < this.text.length) {
  10460. var ch = lowercase(this.text.charAt(this.index));
  10461. if (ch == '.' || this.isNumber(ch)) {
  10462. number += ch;
  10463. } else {
  10464. var peekCh = this.peek();
  10465. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10466. number += ch;
  10467. } else if (this.isExpOperator(ch) &&
  10468. peekCh && this.isNumber(peekCh) &&
  10469. number.charAt(number.length - 1) == 'e') {
  10470. number += ch;
  10471. } else if (this.isExpOperator(ch) &&
  10472. (!peekCh || !this.isNumber(peekCh)) &&
  10473. number.charAt(number.length - 1) == 'e') {
  10474. this.throwError('Invalid exponent');
  10475. } else {
  10476. break;
  10477. }
  10478. }
  10479. this.index++;
  10480. }
  10481. number = 1 * number;
  10482. this.tokens.push({
  10483. index: start,
  10484. text: number,
  10485. constant: true,
  10486. fn: function() { return number; }
  10487. });
  10488. },
  10489. readIdent: function() {
  10490. var expression = this.text;
  10491. var ident = '';
  10492. var start = this.index;
  10493. var lastDot, peekIndex, methodName, ch;
  10494. while (this.index < this.text.length) {
  10495. ch = this.text.charAt(this.index);
  10496. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  10497. if (ch === '.') lastDot = this.index;
  10498. ident += ch;
  10499. } else {
  10500. break;
  10501. }
  10502. this.index++;
  10503. }
  10504. //check if the identifier ends with . and if so move back one char
  10505. if (lastDot && ident[ident.length - 1] === '.') {
  10506. this.index--;
  10507. ident = ident.slice(0, -1);
  10508. lastDot = ident.lastIndexOf('.');
  10509. if (lastDot === -1) {
  10510. lastDot = undefined;
  10511. }
  10512. }
  10513. //check if this is not a method invocation and if it is back out to last dot
  10514. if (lastDot) {
  10515. peekIndex = this.index;
  10516. while (peekIndex < this.text.length) {
  10517. ch = this.text.charAt(peekIndex);
  10518. if (ch === '(') {
  10519. methodName = ident.substr(lastDot - start + 1);
  10520. ident = ident.substr(0, lastDot - start);
  10521. this.index = peekIndex;
  10522. break;
  10523. }
  10524. if (this.isWhitespace(ch)) {
  10525. peekIndex++;
  10526. } else {
  10527. break;
  10528. }
  10529. }
  10530. }
  10531. this.tokens.push({
  10532. index: start,
  10533. text: ident,
  10534. fn: CONSTANTS[ident] || getterFn(ident, this.options, expression)
  10535. });
  10536. if (methodName) {
  10537. this.tokens.push({
  10538. index: lastDot,
  10539. text: '.'
  10540. });
  10541. this.tokens.push({
  10542. index: lastDot + 1,
  10543. text: methodName
  10544. });
  10545. }
  10546. },
  10547. readString: function(quote) {
  10548. var start = this.index;
  10549. this.index++;
  10550. var string = '';
  10551. var rawString = quote;
  10552. var escape = false;
  10553. while (this.index < this.text.length) {
  10554. var ch = this.text.charAt(this.index);
  10555. rawString += ch;
  10556. if (escape) {
  10557. if (ch === 'u') {
  10558. var hex = this.text.substring(this.index + 1, this.index + 5);
  10559. if (!hex.match(/[\da-f]{4}/i))
  10560. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10561. this.index += 4;
  10562. string += String.fromCharCode(parseInt(hex, 16));
  10563. } else {
  10564. var rep = ESCAPE[ch];
  10565. string = string + (rep || ch);
  10566. }
  10567. escape = false;
  10568. } else if (ch === '\\') {
  10569. escape = true;
  10570. } else if (ch === quote) {
  10571. this.index++;
  10572. this.tokens.push({
  10573. index: start,
  10574. text: rawString,
  10575. string: string,
  10576. constant: true,
  10577. fn: function() { return string; }
  10578. });
  10579. return;
  10580. } else {
  10581. string += ch;
  10582. }
  10583. this.index++;
  10584. }
  10585. this.throwError('Unterminated quote', start);
  10586. }
  10587. };
  10588. function isConstant(exp) {
  10589. return exp.constant;
  10590. }
  10591. /**
  10592. * @constructor
  10593. */
  10594. var Parser = function(lexer, $filter, options) {
  10595. this.lexer = lexer;
  10596. this.$filter = $filter;
  10597. this.options = options;
  10598. };
  10599. Parser.ZERO = extend(function() {
  10600. return 0;
  10601. }, {
  10602. sharedGetter: true,
  10603. constant: true
  10604. });
  10605. Parser.prototype = {
  10606. constructor: Parser,
  10607. parse: function(text) {
  10608. this.text = text;
  10609. this.tokens = this.lexer.lex(text);
  10610. var value = this.statements();
  10611. if (this.tokens.length !== 0) {
  10612. this.throwError('is an unexpected token', this.tokens[0]);
  10613. }
  10614. value.literal = !!value.literal;
  10615. value.constant = !!value.constant;
  10616. return value;
  10617. },
  10618. primary: function() {
  10619. var primary;
  10620. if (this.expect('(')) {
  10621. primary = this.filterChain();
  10622. this.consume(')');
  10623. } else if (this.expect('[')) {
  10624. primary = this.arrayDeclaration();
  10625. } else if (this.expect('{')) {
  10626. primary = this.object();
  10627. } else {
  10628. var token = this.expect();
  10629. primary = token.fn;
  10630. if (!primary) {
  10631. this.throwError('not a primary expression', token);
  10632. }
  10633. if (token.constant) {
  10634. primary.constant = true;
  10635. primary.literal = true;
  10636. }
  10637. }
  10638. var next, context;
  10639. while ((next = this.expect('(', '[', '.'))) {
  10640. if (next.text === '(') {
  10641. primary = this.functionCall(primary, context);
  10642. context = null;
  10643. } else if (next.text === '[') {
  10644. context = primary;
  10645. primary = this.objectIndex(primary);
  10646. } else if (next.text === '.') {
  10647. context = primary;
  10648. primary = this.fieldAccess(primary);
  10649. } else {
  10650. this.throwError('IMPOSSIBLE');
  10651. }
  10652. }
  10653. return primary;
  10654. },
  10655. throwError: function(msg, token) {
  10656. throw $parseMinErr('syntax',
  10657. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10658. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10659. },
  10660. peekToken: function() {
  10661. if (this.tokens.length === 0)
  10662. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10663. return this.tokens[0];
  10664. },
  10665. peek: function(e1, e2, e3, e4) {
  10666. if (this.tokens.length > 0) {
  10667. var token = this.tokens[0];
  10668. var t = token.text;
  10669. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10670. (!e1 && !e2 && !e3 && !e4)) {
  10671. return token;
  10672. }
  10673. }
  10674. return false;
  10675. },
  10676. expect: function(e1, e2, e3, e4) {
  10677. var token = this.peek(e1, e2, e3, e4);
  10678. if (token) {
  10679. this.tokens.shift();
  10680. return token;
  10681. }
  10682. return false;
  10683. },
  10684. consume: function(e1) {
  10685. if (!this.expect(e1)) {
  10686. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10687. }
  10688. },
  10689. unaryFn: function(fn, right) {
  10690. return extend(function $parseUnaryFn(self, locals) {
  10691. return fn(self, locals, right);
  10692. }, {
  10693. constant:right.constant,
  10694. inputs: [right]
  10695. });
  10696. },
  10697. binaryFn: function(left, fn, right, isBranching) {
  10698. return extend(function $parseBinaryFn(self, locals) {
  10699. return fn(self, locals, left, right);
  10700. }, {
  10701. constant: left.constant && right.constant,
  10702. inputs: !isBranching && [left, right]
  10703. });
  10704. },
  10705. statements: function() {
  10706. var statements = [];
  10707. while (true) {
  10708. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10709. statements.push(this.filterChain());
  10710. if (!this.expect(';')) {
  10711. // optimize for the common case where there is only one statement.
  10712. // TODO(size): maybe we should not support multiple statements?
  10713. return (statements.length === 1)
  10714. ? statements[0]
  10715. : function $parseStatements(self, locals) {
  10716. var value;
  10717. for (var i = 0, ii = statements.length; i < ii; i++) {
  10718. value = statements[i](self, locals);
  10719. }
  10720. return value;
  10721. };
  10722. }
  10723. }
  10724. },
  10725. filterChain: function() {
  10726. var left = this.expression();
  10727. var token;
  10728. while ((token = this.expect('|'))) {
  10729. left = this.filter(left);
  10730. }
  10731. return left;
  10732. },
  10733. filter: function(inputFn) {
  10734. var token = this.expect();
  10735. var fn = this.$filter(token.text);
  10736. var argsFn;
  10737. var args;
  10738. if (this.peek(':')) {
  10739. argsFn = [];
  10740. args = []; // we can safely reuse the array
  10741. while (this.expect(':')) {
  10742. argsFn.push(this.expression());
  10743. }
  10744. }
  10745. var inputs = [inputFn].concat(argsFn || []);
  10746. return extend(function $parseFilter(self, locals) {
  10747. var input = inputFn(self, locals);
  10748. if (args) {
  10749. args[0] = input;
  10750. var i = argsFn.length;
  10751. while (i--) {
  10752. args[i + 1] = argsFn[i](self, locals);
  10753. }
  10754. return fn.apply(undefined, args);
  10755. }
  10756. return fn(input);
  10757. }, {
  10758. constant: !fn.$stateful && inputs.every(isConstant),
  10759. inputs: !fn.$stateful && inputs
  10760. });
  10761. },
  10762. expression: function() {
  10763. return this.assignment();
  10764. },
  10765. assignment: function() {
  10766. var left = this.ternary();
  10767. var right;
  10768. var token;
  10769. if ((token = this.expect('='))) {
  10770. if (!left.assign) {
  10771. this.throwError('implies assignment but [' +
  10772. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10773. }
  10774. right = this.ternary();
  10775. return extend(function $parseAssignment(scope, locals) {
  10776. return left.assign(scope, right(scope, locals), locals);
  10777. }, {
  10778. inputs: [left, right]
  10779. });
  10780. }
  10781. return left;
  10782. },
  10783. ternary: function() {
  10784. var left = this.logicalOR();
  10785. var middle;
  10786. var token;
  10787. if ((token = this.expect('?'))) {
  10788. middle = this.assignment();
  10789. if ((token = this.expect(':'))) {
  10790. var right = this.assignment();
  10791. return extend(function $parseTernary(self, locals) {
  10792. return left(self, locals) ? middle(self, locals) : right(self, locals);
  10793. }, {
  10794. constant: left.constant && middle.constant && right.constant
  10795. });
  10796. } else {
  10797. this.throwError('expected :', token);
  10798. }
  10799. }
  10800. return left;
  10801. },
  10802. logicalOR: function() {
  10803. var left = this.logicalAND();
  10804. var token;
  10805. while ((token = this.expect('||'))) {
  10806. left = this.binaryFn(left, token.fn, this.logicalAND(), true);
  10807. }
  10808. return left;
  10809. },
  10810. logicalAND: function() {
  10811. var left = this.equality();
  10812. var token;
  10813. if ((token = this.expect('&&'))) {
  10814. left = this.binaryFn(left, token.fn, this.logicalAND(), true);
  10815. }
  10816. return left;
  10817. },
  10818. equality: function() {
  10819. var left = this.relational();
  10820. var token;
  10821. if ((token = this.expect('==','!=','===','!=='))) {
  10822. left = this.binaryFn(left, token.fn, this.equality());
  10823. }
  10824. return left;
  10825. },
  10826. relational: function() {
  10827. var left = this.additive();
  10828. var token;
  10829. if ((token = this.expect('<', '>', '<=', '>='))) {
  10830. left = this.binaryFn(left, token.fn, this.relational());
  10831. }
  10832. return left;
  10833. },
  10834. additive: function() {
  10835. var left = this.multiplicative();
  10836. var token;
  10837. while ((token = this.expect('+','-'))) {
  10838. left = this.binaryFn(left, token.fn, this.multiplicative());
  10839. }
  10840. return left;
  10841. },
  10842. multiplicative: function() {
  10843. var left = this.unary();
  10844. var token;
  10845. while ((token = this.expect('*','/','%'))) {
  10846. left = this.binaryFn(left, token.fn, this.unary());
  10847. }
  10848. return left;
  10849. },
  10850. unary: function() {
  10851. var token;
  10852. if (this.expect('+')) {
  10853. return this.primary();
  10854. } else if ((token = this.expect('-'))) {
  10855. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  10856. } else if ((token = this.expect('!'))) {
  10857. return this.unaryFn(token.fn, this.unary());
  10858. } else {
  10859. return this.primary();
  10860. }
  10861. },
  10862. fieldAccess: function(object) {
  10863. var expression = this.text;
  10864. var field = this.expect().text;
  10865. var getter = getterFn(field, this.options, expression);
  10866. return extend(function $parseFieldAccess(scope, locals, self) {
  10867. return getter(self || object(scope, locals));
  10868. }, {
  10869. assign: function(scope, value, locals) {
  10870. var o = object(scope, locals);
  10871. if (!o) object.assign(scope, o = {});
  10872. return setter(o, field, value, expression);
  10873. }
  10874. });
  10875. },
  10876. objectIndex: function(obj) {
  10877. var expression = this.text;
  10878. var indexFn = this.expression();
  10879. this.consume(']');
  10880. return extend(function $parseObjectIndex(self, locals) {
  10881. var o = obj(self, locals),
  10882. i = indexFn(self, locals),
  10883. v;
  10884. ensureSafeMemberName(i, expression);
  10885. if (!o) return undefined;
  10886. v = ensureSafeObject(o[i], expression);
  10887. return v;
  10888. }, {
  10889. assign: function(self, value, locals) {
  10890. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  10891. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  10892. var o = ensureSafeObject(obj(self, locals), expression);
  10893. if (!o) obj.assign(self, o = {});
  10894. return o[key] = value;
  10895. }
  10896. });
  10897. },
  10898. functionCall: function(fnGetter, contextGetter) {
  10899. var argsFn = [];
  10900. if (this.peekToken().text !== ')') {
  10901. do {
  10902. argsFn.push(this.expression());
  10903. } while (this.expect(','));
  10904. }
  10905. this.consume(')');
  10906. var expressionText = this.text;
  10907. // we can safely reuse the array across invocations
  10908. var args = argsFn.length ? [] : null;
  10909. return function $parseFunctionCall(scope, locals) {
  10910. var context = contextGetter ? contextGetter(scope, locals) : scope;
  10911. var fn = fnGetter(scope, locals, context) || noop;
  10912. if (args) {
  10913. var i = argsFn.length;
  10914. while (i--) {
  10915. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  10916. }
  10917. }
  10918. ensureSafeObject(context, expressionText);
  10919. ensureSafeFunction(fn, expressionText);
  10920. // IE stupidity! (IE doesn't have apply for some native functions)
  10921. var v = fn.apply
  10922. ? fn.apply(context, args)
  10923. : fn(args[0], args[1], args[2], args[3], args[4]);
  10924. return ensureSafeObject(v, expressionText);
  10925. };
  10926. },
  10927. // This is used with json array declaration
  10928. arrayDeclaration: function() {
  10929. var elementFns = [];
  10930. if (this.peekToken().text !== ']') {
  10931. do {
  10932. if (this.peek(']')) {
  10933. // Support trailing commas per ES5.1.
  10934. break;
  10935. }
  10936. var elementFn = this.expression();
  10937. elementFns.push(elementFn);
  10938. } while (this.expect(','));
  10939. }
  10940. this.consume(']');
  10941. return extend(function $parseArrayLiteral(self, locals) {
  10942. var array = [];
  10943. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  10944. array.push(elementFns[i](self, locals));
  10945. }
  10946. return array;
  10947. }, {
  10948. literal: true,
  10949. constant: elementFns.every(isConstant),
  10950. inputs: elementFns
  10951. });
  10952. },
  10953. object: function() {
  10954. var keys = [], valueFns = [];
  10955. if (this.peekToken().text !== '}') {
  10956. do {
  10957. if (this.peek('}')) {
  10958. // Support trailing commas per ES5.1.
  10959. break;
  10960. }
  10961. var token = this.expect();
  10962. keys.push(token.string || token.text);
  10963. this.consume(':');
  10964. var value = this.expression();
  10965. valueFns.push(value);
  10966. } while (this.expect(','));
  10967. }
  10968. this.consume('}');
  10969. return extend(function $parseObjectLiteral(self, locals) {
  10970. var object = {};
  10971. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  10972. object[keys[i]] = valueFns[i](self, locals);
  10973. }
  10974. return object;
  10975. }, {
  10976. literal: true,
  10977. constant: valueFns.every(isConstant),
  10978. inputs: valueFns
  10979. });
  10980. }
  10981. };
  10982. //////////////////////////////////////////////////
  10983. // Parser helper functions
  10984. //////////////////////////////////////////////////
  10985. function setter(obj, path, setValue, fullExp) {
  10986. ensureSafeObject(obj, fullExp);
  10987. var element = path.split('.'), key;
  10988. for (var i = 0; element.length > 1; i++) {
  10989. key = ensureSafeMemberName(element.shift(), fullExp);
  10990. var propertyObj = ensureSafeObject(obj[key], fullExp);
  10991. if (!propertyObj) {
  10992. propertyObj = {};
  10993. obj[key] = propertyObj;
  10994. }
  10995. obj = propertyObj;
  10996. }
  10997. key = ensureSafeMemberName(element.shift(), fullExp);
  10998. ensureSafeObject(obj[key], fullExp);
  10999. obj[key] = setValue;
  11000. return setValue;
  11001. }
  11002. var getterFnCacheDefault = createMap();
  11003. var getterFnCacheExpensive = createMap();
  11004. function isPossiblyDangerousMemberName(name) {
  11005. return name == 'constructor';
  11006. }
  11007. /**
  11008. * Implementation of the "Black Hole" variant from:
  11009. * - http://jsperf.com/angularjs-parse-getter/4
  11010. * - http://jsperf.com/path-evaluation-simplified/7
  11011. */
  11012. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
  11013. ensureSafeMemberName(key0, fullExp);
  11014. ensureSafeMemberName(key1, fullExp);
  11015. ensureSafeMemberName(key2, fullExp);
  11016. ensureSafeMemberName(key3, fullExp);
  11017. ensureSafeMemberName(key4, fullExp);
  11018. var eso = function(o) {
  11019. return ensureSafeObject(o, fullExp);
  11020. };
  11021. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  11022. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  11023. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  11024. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  11025. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  11026. return function cspSafeGetter(scope, locals) {
  11027. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  11028. if (pathVal == null) return pathVal;
  11029. pathVal = eso0(pathVal[key0]);
  11030. if (!key1) return pathVal;
  11031. if (pathVal == null) return undefined;
  11032. pathVal = eso1(pathVal[key1]);
  11033. if (!key2) return pathVal;
  11034. if (pathVal == null) return undefined;
  11035. pathVal = eso2(pathVal[key2]);
  11036. if (!key3) return pathVal;
  11037. if (pathVal == null) return undefined;
  11038. pathVal = eso3(pathVal[key3]);
  11039. if (!key4) return pathVal;
  11040. if (pathVal == null) return undefined;
  11041. pathVal = eso4(pathVal[key4]);
  11042. return pathVal;
  11043. };
  11044. }
  11045. function getterFnWithEnsureSafeObject(fn, fullExpression) {
  11046. return function(s, l) {
  11047. return fn(s, l, ensureSafeObject, fullExpression);
  11048. };
  11049. }
  11050. function getterFn(path, options, fullExp) {
  11051. var expensiveChecks = options.expensiveChecks;
  11052. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  11053. var fn = getterFnCache[path];
  11054. if (fn) return fn;
  11055. var pathKeys = path.split('.'),
  11056. pathKeysLength = pathKeys.length;
  11057. // http://jsperf.com/angularjs-parse-getter/6
  11058. if (options.csp) {
  11059. if (pathKeysLength < 6) {
  11060. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
  11061. } else {
  11062. fn = function cspSafeGetter(scope, locals) {
  11063. var i = 0, val;
  11064. do {
  11065. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11066. pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
  11067. locals = undefined; // clear after first iteration
  11068. scope = val;
  11069. } while (i < pathKeysLength);
  11070. return val;
  11071. };
  11072. }
  11073. } else {
  11074. var code = '';
  11075. if (expensiveChecks) {
  11076. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  11077. }
  11078. var needsEnsureSafeObject = expensiveChecks;
  11079. forEach(pathKeys, function(key, index) {
  11080. ensureSafeMemberName(key, fullExp);
  11081. var lookupJs = (index
  11082. // we simply dereference 's' on any .dot notation
  11083. ? 's'
  11084. // but if we are first then we check locals first, and if so read it first
  11085. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
  11086. if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
  11087. lookupJs = 'eso(' + lookupJs + ', fe)';
  11088. needsEnsureSafeObject = true;
  11089. }
  11090. code += 'if(s == null) return undefined;\n' +
  11091. 's=' + lookupJs + ';\n';
  11092. });
  11093. code += 'return s;';
  11094. /* jshint -W054 */
  11095. var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
  11096. /* jshint +W054 */
  11097. evaledFnGetter.toString = valueFn(code);
  11098. if (needsEnsureSafeObject) {
  11099. evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
  11100. }
  11101. fn = evaledFnGetter;
  11102. }
  11103. fn.sharedGetter = true;
  11104. fn.assign = function(self, value) {
  11105. return setter(self, path, value, path);
  11106. };
  11107. getterFnCache[path] = fn;
  11108. return fn;
  11109. }
  11110. var objectValueOf = Object.prototype.valueOf;
  11111. function getValueOf(value) {
  11112. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  11113. }
  11114. ///////////////////////////////////
  11115. /**
  11116. * @ngdoc service
  11117. * @name $parse
  11118. * @kind function
  11119. *
  11120. * @description
  11121. *
  11122. * Converts Angular {@link guide/expression expression} into a function.
  11123. *
  11124. * ```js
  11125. * var getter = $parse('user.name');
  11126. * var setter = getter.assign;
  11127. * var context = {user:{name:'angular'}};
  11128. * var locals = {user:{name:'local'}};
  11129. *
  11130. * expect(getter(context)).toEqual('angular');
  11131. * setter(context, 'newValue');
  11132. * expect(context.user.name).toEqual('newValue');
  11133. * expect(getter(context, locals)).toEqual('local');
  11134. * ```
  11135. *
  11136. *
  11137. * @param {string} expression String expression to compile.
  11138. * @returns {function(context, locals)} a function which represents the compiled expression:
  11139. *
  11140. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11141. * are evaluated against (typically a scope object).
  11142. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11143. * `context`.
  11144. *
  11145. * The returned function also has the following properties:
  11146. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11147. * literal.
  11148. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11149. * constant literals.
  11150. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11151. * set to a function to change its value on the given context.
  11152. *
  11153. */
  11154. /**
  11155. * @ngdoc provider
  11156. * @name $parseProvider
  11157. *
  11158. * @description
  11159. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11160. * service.
  11161. */
  11162. function $ParseProvider() {
  11163. var cacheDefault = createMap();
  11164. var cacheExpensive = createMap();
  11165. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11166. var $parseOptions = {
  11167. csp: $sniffer.csp,
  11168. expensiveChecks: false
  11169. },
  11170. $parseOptionsExpensive = {
  11171. csp: $sniffer.csp,
  11172. expensiveChecks: true
  11173. };
  11174. function wrapSharedExpression(exp) {
  11175. var wrapped = exp;
  11176. if (exp.sharedGetter) {
  11177. wrapped = function $parseWrapper(self, locals) {
  11178. return exp(self, locals);
  11179. };
  11180. wrapped.literal = exp.literal;
  11181. wrapped.constant = exp.constant;
  11182. wrapped.assign = exp.assign;
  11183. }
  11184. return wrapped;
  11185. }
  11186. return function $parse(exp, interceptorFn, expensiveChecks) {
  11187. var parsedExpression, oneTime, cacheKey;
  11188. switch (typeof exp) {
  11189. case 'string':
  11190. cacheKey = exp = exp.trim();
  11191. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  11192. parsedExpression = cache[cacheKey];
  11193. if (!parsedExpression) {
  11194. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11195. oneTime = true;
  11196. exp = exp.substring(2);
  11197. }
  11198. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  11199. var lexer = new Lexer(parseOptions);
  11200. var parser = new Parser(lexer, $filter, parseOptions);
  11201. parsedExpression = parser.parse(exp);
  11202. if (parsedExpression.constant) {
  11203. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11204. } else if (oneTime) {
  11205. //oneTime is not part of the exp passed to the Parser so we may have to
  11206. //wrap the parsedExpression before adding a $$watchDelegate
  11207. parsedExpression = wrapSharedExpression(parsedExpression);
  11208. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11209. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11210. } else if (parsedExpression.inputs) {
  11211. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11212. }
  11213. cache[cacheKey] = parsedExpression;
  11214. }
  11215. return addInterceptor(parsedExpression, interceptorFn);
  11216. case 'function':
  11217. return addInterceptor(exp, interceptorFn);
  11218. default:
  11219. return addInterceptor(noop, interceptorFn);
  11220. }
  11221. };
  11222. function collectExpressionInputs(inputs, list) {
  11223. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11224. var input = inputs[i];
  11225. if (!input.constant) {
  11226. if (input.inputs) {
  11227. collectExpressionInputs(input.inputs, list);
  11228. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11229. list.push(input);
  11230. }
  11231. }
  11232. }
  11233. return list;
  11234. }
  11235. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11236. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11237. return newValue === oldValueOfValue;
  11238. }
  11239. if (typeof newValue === 'object') {
  11240. // attempt to convert the value to a primitive type
  11241. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11242. // be cheaply dirty-checked
  11243. newValue = getValueOf(newValue);
  11244. if (typeof newValue === 'object') {
  11245. // objects/arrays are not supported - deep-watching them would be too expensive
  11246. return false;
  11247. }
  11248. // fall-through to the primitive equality check
  11249. }
  11250. //Primitive or NaN
  11251. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11252. }
  11253. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11254. var inputExpressions = parsedExpression.$$inputs ||
  11255. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11256. var lastResult;
  11257. if (inputExpressions.length === 1) {
  11258. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11259. inputExpressions = inputExpressions[0];
  11260. return scope.$watch(function expressionInputWatch(scope) {
  11261. var newInputValue = inputExpressions(scope);
  11262. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11263. lastResult = parsedExpression(scope);
  11264. oldInputValue = newInputValue && getValueOf(newInputValue);
  11265. }
  11266. return lastResult;
  11267. }, listener, objectEquality);
  11268. }
  11269. var oldInputValueOfValues = [];
  11270. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11271. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11272. }
  11273. return scope.$watch(function expressionInputsWatch(scope) {
  11274. var changed = false;
  11275. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11276. var newInputValue = inputExpressions[i](scope);
  11277. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11278. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  11279. }
  11280. }
  11281. if (changed) {
  11282. lastResult = parsedExpression(scope);
  11283. }
  11284. return lastResult;
  11285. }, listener, objectEquality);
  11286. }
  11287. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11288. var unwatch, lastValue;
  11289. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11290. return parsedExpression(scope);
  11291. }, function oneTimeListener(value, old, scope) {
  11292. lastValue = value;
  11293. if (isFunction(listener)) {
  11294. listener.apply(this, arguments);
  11295. }
  11296. if (isDefined(value)) {
  11297. scope.$$postDigest(function() {
  11298. if (isDefined(lastValue)) {
  11299. unwatch();
  11300. }
  11301. });
  11302. }
  11303. }, objectEquality);
  11304. }
  11305. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11306. var unwatch, lastValue;
  11307. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11308. return parsedExpression(scope);
  11309. }, function oneTimeListener(value, old, scope) {
  11310. lastValue = value;
  11311. if (isFunction(listener)) {
  11312. listener.call(this, value, old, scope);
  11313. }
  11314. if (isAllDefined(value)) {
  11315. scope.$$postDigest(function() {
  11316. if (isAllDefined(lastValue)) unwatch();
  11317. });
  11318. }
  11319. }, objectEquality);
  11320. function isAllDefined(value) {
  11321. var allDefined = true;
  11322. forEach(value, function(val) {
  11323. if (!isDefined(val)) allDefined = false;
  11324. });
  11325. return allDefined;
  11326. }
  11327. }
  11328. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11329. var unwatch;
  11330. return unwatch = scope.$watch(function constantWatch(scope) {
  11331. return parsedExpression(scope);
  11332. }, function constantListener(value, old, scope) {
  11333. if (isFunction(listener)) {
  11334. listener.apply(this, arguments);
  11335. }
  11336. unwatch();
  11337. }, objectEquality);
  11338. }
  11339. function addInterceptor(parsedExpression, interceptorFn) {
  11340. if (!interceptorFn) return parsedExpression;
  11341. var fn = function interceptedExpression(scope, locals) {
  11342. var value = parsedExpression(scope, locals);
  11343. var result = interceptorFn(value, scope, locals);
  11344. // we only return the interceptor's result if the
  11345. // initial value is defined (for bind-once)
  11346. return isDefined(value) || interceptorFn.$stateful ? result : value;
  11347. };
  11348. // Propagate $$watchDelegates other then inputsWatchDelegate
  11349. if (parsedExpression.$$watchDelegate &&
  11350. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11351. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11352. } else if (!interceptorFn.$stateful) {
  11353. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11354. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11355. fn.$$watchDelegate = inputsWatchDelegate;
  11356. fn.inputs = [parsedExpression];
  11357. }
  11358. return fn;
  11359. }
  11360. }];
  11361. }
  11362. /**
  11363. * @ngdoc service
  11364. * @name $q
  11365. * @requires $rootScope
  11366. *
  11367. * @description
  11368. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  11369. *
  11370. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11371. * implementations, and the other which resembles ES6 promises to some degree.
  11372. *
  11373. * # $q constructor
  11374. *
  11375. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11376. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11377. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11378. *
  11379. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11380. * available yet.
  11381. *
  11382. * It can be used like so:
  11383. *
  11384. * ```js
  11385. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11386. * // are available in the current lexical scope (they could have been injected or passed in).
  11387. *
  11388. * function asyncGreet(name) {
  11389. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11390. * return $q(function(resolve, reject) {
  11391. * setTimeout(function() {
  11392. * if (okToGreet(name)) {
  11393. * resolve('Hello, ' + name + '!');
  11394. * } else {
  11395. * reject('Greeting ' + name + ' is not allowed.');
  11396. * }
  11397. * }, 1000);
  11398. * });
  11399. * }
  11400. *
  11401. * var promise = asyncGreet('Robin Hood');
  11402. * promise.then(function(greeting) {
  11403. * alert('Success: ' + greeting);
  11404. * }, function(reason) {
  11405. * alert('Failed: ' + reason);
  11406. * });
  11407. * ```
  11408. *
  11409. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11410. *
  11411. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11412. *
  11413. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11414. * interface for interacting with an object that represents the result of an action that is
  11415. * performed asynchronously, and may or may not be finished at any given point in time.
  11416. *
  11417. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11418. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11419. *
  11420. * ```js
  11421. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11422. * // are available in the current lexical scope (they could have been injected or passed in).
  11423. *
  11424. * function asyncGreet(name) {
  11425. * var deferred = $q.defer();
  11426. *
  11427. * setTimeout(function() {
  11428. * deferred.notify('About to greet ' + name + '.');
  11429. *
  11430. * if (okToGreet(name)) {
  11431. * deferred.resolve('Hello, ' + name + '!');
  11432. * } else {
  11433. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11434. * }
  11435. * }, 1000);
  11436. *
  11437. * return deferred.promise;
  11438. * }
  11439. *
  11440. * var promise = asyncGreet('Robin Hood');
  11441. * promise.then(function(greeting) {
  11442. * alert('Success: ' + greeting);
  11443. * }, function(reason) {
  11444. * alert('Failed: ' + reason);
  11445. * }, function(update) {
  11446. * alert('Got notification: ' + update);
  11447. * });
  11448. * ```
  11449. *
  11450. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11451. * comes in the way of guarantees that promise and deferred APIs make, see
  11452. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11453. *
  11454. * Additionally the promise api allows for composition that is very hard to do with the
  11455. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11456. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11457. * section on serial or parallel joining of promises.
  11458. *
  11459. * # The Deferred API
  11460. *
  11461. * A new instance of deferred is constructed by calling `$q.defer()`.
  11462. *
  11463. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11464. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11465. * of the task.
  11466. *
  11467. * **Methods**
  11468. *
  11469. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11470. * constructed via `$q.reject`, the promise will be rejected instead.
  11471. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11472. * resolving it with a rejection constructed via `$q.reject`.
  11473. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11474. * multiple times before the promise is either resolved or rejected.
  11475. *
  11476. * **Properties**
  11477. *
  11478. * - promise – `{Promise}` – promise object associated with this deferred.
  11479. *
  11480. *
  11481. * # The Promise API
  11482. *
  11483. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11484. * calling `deferred.promise`.
  11485. *
  11486. * The purpose of the promise object is to allow for interested parties to get access to the result
  11487. * of the deferred task when it completes.
  11488. *
  11489. * **Methods**
  11490. *
  11491. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11492. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11493. * as soon as the result is available. The callbacks are called with a single argument: the result
  11494. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11495. * provide a progress indication, before the promise is resolved or rejected.
  11496. *
  11497. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11498. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11499. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11500. * method.
  11501. *
  11502. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11503. *
  11504. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  11505. * but to do so without modifying the final value. This is useful to release resources or do some
  11506. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11507. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11508. * more information.
  11509. *
  11510. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  11511. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  11512. * make your code IE8 and Android 2.x compatible.
  11513. *
  11514. * # Chaining promises
  11515. *
  11516. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11517. * possible to create a chain of promises:
  11518. *
  11519. * ```js
  11520. * promiseB = promiseA.then(function(result) {
  11521. * return result + 1;
  11522. * });
  11523. *
  11524. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11525. * // will be the result of promiseA incremented by 1
  11526. * ```
  11527. *
  11528. * It is possible to create chains of any length and since a promise can be resolved with another
  11529. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11530. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11531. * $http's response interceptors.
  11532. *
  11533. *
  11534. * # Differences between Kris Kowal's Q and $q
  11535. *
  11536. * There are two main differences:
  11537. *
  11538. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11539. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11540. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11541. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11542. * all the important functionality needed for common async tasks.
  11543. *
  11544. * # Testing
  11545. *
  11546. * ```js
  11547. * it('should simulate promise', inject(function($q, $rootScope) {
  11548. * var deferred = $q.defer();
  11549. * var promise = deferred.promise;
  11550. * var resolvedValue;
  11551. *
  11552. * promise.then(function(value) { resolvedValue = value; });
  11553. * expect(resolvedValue).toBeUndefined();
  11554. *
  11555. * // Simulate resolving of promise
  11556. * deferred.resolve(123);
  11557. * // Note that the 'then' function does not get called synchronously.
  11558. * // This is because we want the promise API to always be async, whether or not
  11559. * // it got called synchronously or asynchronously.
  11560. * expect(resolvedValue).toBeUndefined();
  11561. *
  11562. * // Propagate promise resolution to 'then' functions using $apply().
  11563. * $rootScope.$apply();
  11564. * expect(resolvedValue).toEqual(123);
  11565. * }));
  11566. * ```
  11567. *
  11568. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11569. * rejecting the newly created promise. The first parameter is a function which resolves the
  11570. * promise, the second parameter is a function which rejects the promise.
  11571. *
  11572. * @returns {Promise} The newly created promise.
  11573. */
  11574. function $QProvider() {
  11575. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11576. return qFactory(function(callback) {
  11577. $rootScope.$evalAsync(callback);
  11578. }, $exceptionHandler);
  11579. }];
  11580. }
  11581. function $$QProvider() {
  11582. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11583. return qFactory(function(callback) {
  11584. $browser.defer(callback);
  11585. }, $exceptionHandler);
  11586. }];
  11587. }
  11588. /**
  11589. * Constructs a promise manager.
  11590. *
  11591. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11592. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11593. * debugging purposes.
  11594. * @returns {object} Promise manager.
  11595. */
  11596. function qFactory(nextTick, exceptionHandler) {
  11597. var $qMinErr = minErr('$q', TypeError);
  11598. function callOnce(self, resolveFn, rejectFn) {
  11599. var called = false;
  11600. function wrap(fn) {
  11601. return function(value) {
  11602. if (called) return;
  11603. called = true;
  11604. fn.call(self, value);
  11605. };
  11606. }
  11607. return [wrap(resolveFn), wrap(rejectFn)];
  11608. }
  11609. /**
  11610. * @ngdoc method
  11611. * @name ng.$q#defer
  11612. * @kind function
  11613. *
  11614. * @description
  11615. * Creates a `Deferred` object which represents a task which will finish in the future.
  11616. *
  11617. * @returns {Deferred} Returns a new instance of deferred.
  11618. */
  11619. var defer = function() {
  11620. return new Deferred();
  11621. };
  11622. function Promise() {
  11623. this.$$state = { status: 0 };
  11624. }
  11625. Promise.prototype = {
  11626. then: function(onFulfilled, onRejected, progressBack) {
  11627. var result = new Deferred();
  11628. this.$$state.pending = this.$$state.pending || [];
  11629. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11630. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11631. return result.promise;
  11632. },
  11633. "catch": function(callback) {
  11634. return this.then(null, callback);
  11635. },
  11636. "finally": function(callback, progressBack) {
  11637. return this.then(function(value) {
  11638. return handleCallback(value, true, callback);
  11639. }, function(error) {
  11640. return handleCallback(error, false, callback);
  11641. }, progressBack);
  11642. }
  11643. };
  11644. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11645. function simpleBind(context, fn) {
  11646. return function(value) {
  11647. fn.call(context, value);
  11648. };
  11649. }
  11650. function processQueue(state) {
  11651. var fn, promise, pending;
  11652. pending = state.pending;
  11653. state.processScheduled = false;
  11654. state.pending = undefined;
  11655. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11656. promise = pending[i][0];
  11657. fn = pending[i][state.status];
  11658. try {
  11659. if (isFunction(fn)) {
  11660. promise.resolve(fn(state.value));
  11661. } else if (state.status === 1) {
  11662. promise.resolve(state.value);
  11663. } else {
  11664. promise.reject(state.value);
  11665. }
  11666. } catch (e) {
  11667. promise.reject(e);
  11668. exceptionHandler(e);
  11669. }
  11670. }
  11671. }
  11672. function scheduleProcessQueue(state) {
  11673. if (state.processScheduled || !state.pending) return;
  11674. state.processScheduled = true;
  11675. nextTick(function() { processQueue(state); });
  11676. }
  11677. function Deferred() {
  11678. this.promise = new Promise();
  11679. //Necessary to support unbound execution :/
  11680. this.resolve = simpleBind(this, this.resolve);
  11681. this.reject = simpleBind(this, this.reject);
  11682. this.notify = simpleBind(this, this.notify);
  11683. }
  11684. Deferred.prototype = {
  11685. resolve: function(val) {
  11686. if (this.promise.$$state.status) return;
  11687. if (val === this.promise) {
  11688. this.$$reject($qMinErr(
  11689. 'qcycle',
  11690. "Expected promise to be resolved with value other than itself '{0}'",
  11691. val));
  11692. }
  11693. else {
  11694. this.$$resolve(val);
  11695. }
  11696. },
  11697. $$resolve: function(val) {
  11698. var then, fns;
  11699. fns = callOnce(this, this.$$resolve, this.$$reject);
  11700. try {
  11701. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11702. if (isFunction(then)) {
  11703. this.promise.$$state.status = -1;
  11704. then.call(val, fns[0], fns[1], this.notify);
  11705. } else {
  11706. this.promise.$$state.value = val;
  11707. this.promise.$$state.status = 1;
  11708. scheduleProcessQueue(this.promise.$$state);
  11709. }
  11710. } catch (e) {
  11711. fns[1](e);
  11712. exceptionHandler(e);
  11713. }
  11714. },
  11715. reject: function(reason) {
  11716. if (this.promise.$$state.status) return;
  11717. this.$$reject(reason);
  11718. },
  11719. $$reject: function(reason) {
  11720. this.promise.$$state.value = reason;
  11721. this.promise.$$state.status = 2;
  11722. scheduleProcessQueue(this.promise.$$state);
  11723. },
  11724. notify: function(progress) {
  11725. var callbacks = this.promise.$$state.pending;
  11726. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11727. nextTick(function() {
  11728. var callback, result;
  11729. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11730. result = callbacks[i][0];
  11731. callback = callbacks[i][3];
  11732. try {
  11733. result.notify(isFunction(callback) ? callback(progress) : progress);
  11734. } catch (e) {
  11735. exceptionHandler(e);
  11736. }
  11737. }
  11738. });
  11739. }
  11740. }
  11741. };
  11742. /**
  11743. * @ngdoc method
  11744. * @name $q#reject
  11745. * @kind function
  11746. *
  11747. * @description
  11748. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11749. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11750. * a promise chain, you don't need to worry about it.
  11751. *
  11752. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11753. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11754. * a promise error callback and you want to forward the error to the promise derived from the
  11755. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11756. * `reject`.
  11757. *
  11758. * ```js
  11759. * promiseB = promiseA.then(function(result) {
  11760. * // success: do something and resolve promiseB
  11761. * // with the old or a new result
  11762. * return result;
  11763. * }, function(reason) {
  11764. * // error: handle the error if possible and
  11765. * // resolve promiseB with newPromiseOrValue,
  11766. * // otherwise forward the rejection to promiseB
  11767. * if (canHandle(reason)) {
  11768. * // handle the error and recover
  11769. * return newPromiseOrValue;
  11770. * }
  11771. * return $q.reject(reason);
  11772. * });
  11773. * ```
  11774. *
  11775. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  11776. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  11777. */
  11778. var reject = function(reason) {
  11779. var result = new Deferred();
  11780. result.reject(reason);
  11781. return result.promise;
  11782. };
  11783. var makePromise = function makePromise(value, resolved) {
  11784. var result = new Deferred();
  11785. if (resolved) {
  11786. result.resolve(value);
  11787. } else {
  11788. result.reject(value);
  11789. }
  11790. return result.promise;
  11791. };
  11792. var handleCallback = function handleCallback(value, isResolved, callback) {
  11793. var callbackOutput = null;
  11794. try {
  11795. if (isFunction(callback)) callbackOutput = callback();
  11796. } catch (e) {
  11797. return makePromise(e, false);
  11798. }
  11799. if (isPromiseLike(callbackOutput)) {
  11800. return callbackOutput.then(function() {
  11801. return makePromise(value, isResolved);
  11802. }, function(error) {
  11803. return makePromise(error, false);
  11804. });
  11805. } else {
  11806. return makePromise(value, isResolved);
  11807. }
  11808. };
  11809. /**
  11810. * @ngdoc method
  11811. * @name $q#when
  11812. * @kind function
  11813. *
  11814. * @description
  11815. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  11816. * This is useful when you are dealing with an object that might or might not be a promise, or if
  11817. * the promise comes from a source that can't be trusted.
  11818. *
  11819. * @param {*} value Value or a promise
  11820. * @returns {Promise} Returns a promise of the passed value or promise
  11821. */
  11822. var when = function(value, callback, errback, progressBack) {
  11823. var result = new Deferred();
  11824. result.resolve(value);
  11825. return result.promise.then(callback, errback, progressBack);
  11826. };
  11827. /**
  11828. * @ngdoc method
  11829. * @name $q#all
  11830. * @kind function
  11831. *
  11832. * @description
  11833. * Combines multiple promises into a single promise that is resolved when all of the input
  11834. * promises are resolved.
  11835. *
  11836. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  11837. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  11838. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  11839. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  11840. * with the same rejection value.
  11841. */
  11842. function all(promises) {
  11843. var deferred = new Deferred(),
  11844. counter = 0,
  11845. results = isArray(promises) ? [] : {};
  11846. forEach(promises, function(promise, key) {
  11847. counter++;
  11848. when(promise).then(function(value) {
  11849. if (results.hasOwnProperty(key)) return;
  11850. results[key] = value;
  11851. if (!(--counter)) deferred.resolve(results);
  11852. }, function(reason) {
  11853. if (results.hasOwnProperty(key)) return;
  11854. deferred.reject(reason);
  11855. });
  11856. });
  11857. if (counter === 0) {
  11858. deferred.resolve(results);
  11859. }
  11860. return deferred.promise;
  11861. }
  11862. var $Q = function Q(resolver) {
  11863. if (!isFunction(resolver)) {
  11864. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  11865. }
  11866. if (!(this instanceof Q)) {
  11867. // More useful when $Q is the Promise itself.
  11868. return new Q(resolver);
  11869. }
  11870. var deferred = new Deferred();
  11871. function resolveFn(value) {
  11872. deferred.resolve(value);
  11873. }
  11874. function rejectFn(reason) {
  11875. deferred.reject(reason);
  11876. }
  11877. resolver(resolveFn, rejectFn);
  11878. return deferred.promise;
  11879. };
  11880. $Q.defer = defer;
  11881. $Q.reject = reject;
  11882. $Q.when = when;
  11883. $Q.all = all;
  11884. return $Q;
  11885. }
  11886. function $$RAFProvider() { //rAF
  11887. this.$get = ['$window', '$timeout', function($window, $timeout) {
  11888. var requestAnimationFrame = $window.requestAnimationFrame ||
  11889. $window.webkitRequestAnimationFrame ||
  11890. $window.mozRequestAnimationFrame;
  11891. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  11892. $window.webkitCancelAnimationFrame ||
  11893. $window.mozCancelAnimationFrame ||
  11894. $window.webkitCancelRequestAnimationFrame;
  11895. var rafSupported = !!requestAnimationFrame;
  11896. var raf = rafSupported
  11897. ? function(fn) {
  11898. var id = requestAnimationFrame(fn);
  11899. return function() {
  11900. cancelAnimationFrame(id);
  11901. };
  11902. }
  11903. : function(fn) {
  11904. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  11905. return function() {
  11906. $timeout.cancel(timer);
  11907. };
  11908. };
  11909. raf.supported = rafSupported;
  11910. return raf;
  11911. }];
  11912. }
  11913. /**
  11914. * DESIGN NOTES
  11915. *
  11916. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  11917. *
  11918. * The typical use of scope is to watch the expressions, which most of the time return the same
  11919. * value as last time so we optimize the operation.
  11920. *
  11921. * Closures construction is expensive in terms of speed as well as memory:
  11922. * - No closures, instead use prototypical inheritance for API
  11923. * - Internal state needs to be stored on scope directly, which means that private state is
  11924. * exposed as $$____ properties
  11925. *
  11926. * Loop operations are optimized by using while(count--) { ... }
  11927. * - this means that in order to keep the same order of execution as addition we have to add
  11928. * items to the array at the beginning (unshift) instead of at the end (push)
  11929. *
  11930. * Child scopes are created and removed often
  11931. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  11932. *
  11933. * There are few watches then a lot of observers. This is why you don't want the observer to be
  11934. * implemented in the same way as watch. Watch requires return of initialization function which
  11935. * are expensive to construct.
  11936. */
  11937. /**
  11938. * @ngdoc provider
  11939. * @name $rootScopeProvider
  11940. * @description
  11941. *
  11942. * Provider for the $rootScope service.
  11943. */
  11944. /**
  11945. * @ngdoc method
  11946. * @name $rootScopeProvider#digestTtl
  11947. * @description
  11948. *
  11949. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  11950. * assuming that the model is unstable.
  11951. *
  11952. * The current default is 10 iterations.
  11953. *
  11954. * In complex applications it's possible that the dependencies between `$watch`s will result in
  11955. * several digest iterations. However if an application needs more than the default 10 digest
  11956. * iterations for its model to stabilize then you should investigate what is causing the model to
  11957. * continuously change during the digest.
  11958. *
  11959. * Increasing the TTL could have performance implications, so you should not change it without
  11960. * proper justification.
  11961. *
  11962. * @param {number} limit The number of digest iterations.
  11963. */
  11964. /**
  11965. * @ngdoc service
  11966. * @name $rootScope
  11967. * @description
  11968. *
  11969. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  11970. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  11971. * between the model and the view, via a mechanism for watching the model for changes.
  11972. * They also provide an event emission/broadcast and subscription facility. See the
  11973. * {@link guide/scope developer guide on scopes}.
  11974. */
  11975. function $RootScopeProvider() {
  11976. var TTL = 10;
  11977. var $rootScopeMinErr = minErr('$rootScope');
  11978. var lastDirtyWatch = null;
  11979. var applyAsyncId = null;
  11980. this.digestTtl = function(value) {
  11981. if (arguments.length) {
  11982. TTL = value;
  11983. }
  11984. return TTL;
  11985. };
  11986. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  11987. function($injector, $exceptionHandler, $parse, $browser) {
  11988. /**
  11989. * @ngdoc type
  11990. * @name $rootScope.Scope
  11991. *
  11992. * @description
  11993. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  11994. * {@link auto.$injector $injector}. Child scopes are created using the
  11995. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  11996. * compiled HTML template is executed.)
  11997. *
  11998. * Here is a simple scope snippet to show how you can interact with the scope.
  11999. * ```html
  12000. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  12001. * ```
  12002. *
  12003. * # Inheritance
  12004. * A scope can inherit from a parent scope, as in this example:
  12005. * ```js
  12006. var parent = $rootScope;
  12007. var child = parent.$new();
  12008. parent.salutation = "Hello";
  12009. child.name = "World";
  12010. expect(child.salutation).toEqual('Hello');
  12011. child.salutation = "Welcome";
  12012. expect(child.salutation).toEqual('Welcome');
  12013. expect(parent.salutation).toEqual('Hello');
  12014. * ```
  12015. *
  12016. * When interacting with `Scope` in tests, additional helper methods are available on the
  12017. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  12018. * details.
  12019. *
  12020. *
  12021. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  12022. * provided for the current scope. Defaults to {@link ng}.
  12023. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  12024. * append/override services provided by `providers`. This is handy
  12025. * when unit-testing and having the need to override a default
  12026. * service.
  12027. * @returns {Object} Newly created scope.
  12028. *
  12029. */
  12030. function Scope() {
  12031. this.$id = nextUid();
  12032. this.$$phase = this.$parent = this.$$watchers =
  12033. this.$$nextSibling = this.$$prevSibling =
  12034. this.$$childHead = this.$$childTail = null;
  12035. this.$root = this;
  12036. this.$$destroyed = false;
  12037. this.$$listeners = {};
  12038. this.$$listenerCount = {};
  12039. this.$$isolateBindings = null;
  12040. }
  12041. /**
  12042. * @ngdoc property
  12043. * @name $rootScope.Scope#$id
  12044. *
  12045. * @description
  12046. * Unique scope ID (monotonically increasing) useful for debugging.
  12047. */
  12048. /**
  12049. * @ngdoc property
  12050. * @name $rootScope.Scope#$parent
  12051. *
  12052. * @description
  12053. * Reference to the parent scope.
  12054. */
  12055. /**
  12056. * @ngdoc property
  12057. * @name $rootScope.Scope#$root
  12058. *
  12059. * @description
  12060. * Reference to the root scope.
  12061. */
  12062. Scope.prototype = {
  12063. constructor: Scope,
  12064. /**
  12065. * @ngdoc method
  12066. * @name $rootScope.Scope#$new
  12067. * @kind function
  12068. *
  12069. * @description
  12070. * Creates a new child {@link ng.$rootScope.Scope scope}.
  12071. *
  12072. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12073. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12074. *
  12075. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12076. * desired for the scope and its child scopes to be permanently detached from the parent and
  12077. * thus stop participating in model change detection and listener notification by invoking.
  12078. *
  12079. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12080. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12081. * When creating widgets, it is useful for the widget to not accidentally read parent
  12082. * state.
  12083. *
  12084. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12085. * of the newly created scope. Defaults to `this` scope if not provided.
  12086. * This is used when creating a transclude scope to correctly place it
  12087. * in the scope hierarchy while maintaining the correct prototypical
  12088. * inheritance.
  12089. *
  12090. * @returns {Object} The newly created child scope.
  12091. *
  12092. */
  12093. $new: function(isolate, parent) {
  12094. var child;
  12095. parent = parent || this;
  12096. if (isolate) {
  12097. child = new Scope();
  12098. child.$root = this.$root;
  12099. } else {
  12100. // Only create a child scope class if somebody asks for one,
  12101. // but cache it to allow the VM to optimize lookups.
  12102. if (!this.$$ChildScope) {
  12103. this.$$ChildScope = function ChildScope() {
  12104. this.$$watchers = this.$$nextSibling =
  12105. this.$$childHead = this.$$childTail = null;
  12106. this.$$listeners = {};
  12107. this.$$listenerCount = {};
  12108. this.$id = nextUid();
  12109. this.$$ChildScope = null;
  12110. };
  12111. this.$$ChildScope.prototype = this;
  12112. }
  12113. child = new this.$$ChildScope();
  12114. }
  12115. child.$parent = parent;
  12116. child.$$prevSibling = parent.$$childTail;
  12117. if (parent.$$childHead) {
  12118. parent.$$childTail.$$nextSibling = child;
  12119. parent.$$childTail = child;
  12120. } else {
  12121. parent.$$childHead = parent.$$childTail = child;
  12122. }
  12123. // When the new scope is not isolated or we inherit from `this`, and
  12124. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12125. // prototypically. In all other cases, this property needs to be set
  12126. // when the parent scope is destroyed.
  12127. // The listener needs to be added after the parent is set
  12128. if (isolate || parent != this) child.$on('$destroy', destroyChild);
  12129. return child;
  12130. function destroyChild() {
  12131. child.$$destroyed = true;
  12132. }
  12133. },
  12134. /**
  12135. * @ngdoc method
  12136. * @name $rootScope.Scope#$watch
  12137. * @kind function
  12138. *
  12139. * @description
  12140. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12141. *
  12142. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12143. * $digest()} and should return the value that will be watched. (Since
  12144. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12145. * `watchExpression` can execute multiple times per
  12146. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12147. * - The `listener` is called only when the value from the current `watchExpression` and the
  12148. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12149. * see below). Inequality is determined according to reference inequality,
  12150. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12151. * via the `!==` Javascript operator, unless `objectEquality == true`
  12152. * (see next point)
  12153. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12154. * according to the {@link angular.equals} function. To save the value of the object for
  12155. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12156. * watching complex objects will have adverse memory and performance implications.
  12157. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12158. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12159. * iteration limit is 10 to prevent an infinite loop deadlock.
  12160. *
  12161. *
  12162. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12163. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12164. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12165. * change is detected, be prepared for multiple calls to your listener.)
  12166. *
  12167. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12168. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12169. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12170. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12171. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12172. * listener was called due to initialization.
  12173. *
  12174. *
  12175. *
  12176. * # Example
  12177. * ```js
  12178. // let's assume that scope was dependency injected as the $rootScope
  12179. var scope = $rootScope;
  12180. scope.name = 'misko';
  12181. scope.counter = 0;
  12182. expect(scope.counter).toEqual(0);
  12183. scope.$watch('name', function(newValue, oldValue) {
  12184. scope.counter = scope.counter + 1;
  12185. });
  12186. expect(scope.counter).toEqual(0);
  12187. scope.$digest();
  12188. // the listener is always called during the first $digest loop after it was registered
  12189. expect(scope.counter).toEqual(1);
  12190. scope.$digest();
  12191. // but now it will not be called unless the value changes
  12192. expect(scope.counter).toEqual(1);
  12193. scope.name = 'adam';
  12194. scope.$digest();
  12195. expect(scope.counter).toEqual(2);
  12196. // Using a function as a watchExpression
  12197. var food;
  12198. scope.foodCounter = 0;
  12199. expect(scope.foodCounter).toEqual(0);
  12200. scope.$watch(
  12201. // This function returns the value being watched. It is called for each turn of the $digest loop
  12202. function() { return food; },
  12203. // This is the change listener, called when the value returned from the above function changes
  12204. function(newValue, oldValue) {
  12205. if ( newValue !== oldValue ) {
  12206. // Only increment the counter if the value changed
  12207. scope.foodCounter = scope.foodCounter + 1;
  12208. }
  12209. }
  12210. );
  12211. // No digest has been run so the counter will be zero
  12212. expect(scope.foodCounter).toEqual(0);
  12213. // Run the digest but since food has not changed count will still be zero
  12214. scope.$digest();
  12215. expect(scope.foodCounter).toEqual(0);
  12216. // Update food and run digest. Now the counter will increment
  12217. food = 'cheeseburger';
  12218. scope.$digest();
  12219. expect(scope.foodCounter).toEqual(1);
  12220. * ```
  12221. *
  12222. *
  12223. *
  12224. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12225. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12226. * a call to the `listener`.
  12227. *
  12228. * - `string`: Evaluated as {@link guide/expression expression}
  12229. * - `function(scope)`: called with current `scope` as a parameter.
  12230. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12231. * of `watchExpression` changes.
  12232. *
  12233. * - `newVal` contains the current value of the `watchExpression`
  12234. * - `oldVal` contains the previous value of the `watchExpression`
  12235. * - `scope` refers to the current scope
  12236. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12237. * comparing for reference equality.
  12238. * @returns {function()} Returns a deregistration function for this listener.
  12239. */
  12240. $watch: function(watchExp, listener, objectEquality) {
  12241. var get = $parse(watchExp);
  12242. if (get.$$watchDelegate) {
  12243. return get.$$watchDelegate(this, listener, objectEquality, get);
  12244. }
  12245. var scope = this,
  12246. array = scope.$$watchers,
  12247. watcher = {
  12248. fn: listener,
  12249. last: initWatchVal,
  12250. get: get,
  12251. exp: watchExp,
  12252. eq: !!objectEquality
  12253. };
  12254. lastDirtyWatch = null;
  12255. if (!isFunction(listener)) {
  12256. watcher.fn = noop;
  12257. }
  12258. if (!array) {
  12259. array = scope.$$watchers = [];
  12260. }
  12261. // we use unshift since we use a while loop in $digest for speed.
  12262. // the while loop reads in reverse order.
  12263. array.unshift(watcher);
  12264. return function deregisterWatch() {
  12265. arrayRemove(array, watcher);
  12266. lastDirtyWatch = null;
  12267. };
  12268. },
  12269. /**
  12270. * @ngdoc method
  12271. * @name $rootScope.Scope#$watchGroup
  12272. * @kind function
  12273. *
  12274. * @description
  12275. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12276. * If any one expression in the collection changes the `listener` is executed.
  12277. *
  12278. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12279. * call to $digest() to see if any items changes.
  12280. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12281. *
  12282. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12283. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12284. *
  12285. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12286. * expression in `watchExpressions` changes
  12287. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12288. * those of `watchExpression`
  12289. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12290. * those of `watchExpression`
  12291. * The `scope` refers to the current scope.
  12292. * @returns {function()} Returns a de-registration function for all listeners.
  12293. */
  12294. $watchGroup: function(watchExpressions, listener) {
  12295. var oldValues = new Array(watchExpressions.length);
  12296. var newValues = new Array(watchExpressions.length);
  12297. var deregisterFns = [];
  12298. var self = this;
  12299. var changeReactionScheduled = false;
  12300. var firstRun = true;
  12301. if (!watchExpressions.length) {
  12302. // No expressions means we call the listener ASAP
  12303. var shouldCall = true;
  12304. self.$evalAsync(function() {
  12305. if (shouldCall) listener(newValues, newValues, self);
  12306. });
  12307. return function deregisterWatchGroup() {
  12308. shouldCall = false;
  12309. };
  12310. }
  12311. if (watchExpressions.length === 1) {
  12312. // Special case size of one
  12313. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12314. newValues[0] = value;
  12315. oldValues[0] = oldValue;
  12316. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12317. });
  12318. }
  12319. forEach(watchExpressions, function(expr, i) {
  12320. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12321. newValues[i] = value;
  12322. oldValues[i] = oldValue;
  12323. if (!changeReactionScheduled) {
  12324. changeReactionScheduled = true;
  12325. self.$evalAsync(watchGroupAction);
  12326. }
  12327. });
  12328. deregisterFns.push(unwatchFn);
  12329. });
  12330. function watchGroupAction() {
  12331. changeReactionScheduled = false;
  12332. if (firstRun) {
  12333. firstRun = false;
  12334. listener(newValues, newValues, self);
  12335. } else {
  12336. listener(newValues, oldValues, self);
  12337. }
  12338. }
  12339. return function deregisterWatchGroup() {
  12340. while (deregisterFns.length) {
  12341. deregisterFns.shift()();
  12342. }
  12343. };
  12344. },
  12345. /**
  12346. * @ngdoc method
  12347. * @name $rootScope.Scope#$watchCollection
  12348. * @kind function
  12349. *
  12350. * @description
  12351. * Shallow watches the properties of an object and fires whenever any of the properties change
  12352. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12353. * the properties). If a change is detected, the `listener` callback is fired.
  12354. *
  12355. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12356. * call to $digest() to see if any items have been added, removed, or moved.
  12357. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12358. * adding, removing, and moving items belonging to an object or array.
  12359. *
  12360. *
  12361. * # Example
  12362. * ```js
  12363. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12364. $scope.dataCount = 4;
  12365. $scope.$watchCollection('names', function(newNames, oldNames) {
  12366. $scope.dataCount = newNames.length;
  12367. });
  12368. expect($scope.dataCount).toEqual(4);
  12369. $scope.$digest();
  12370. //still at 4 ... no changes
  12371. expect($scope.dataCount).toEqual(4);
  12372. $scope.names.pop();
  12373. $scope.$digest();
  12374. //now there's been a change
  12375. expect($scope.dataCount).toEqual(3);
  12376. * ```
  12377. *
  12378. *
  12379. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12380. * expression value should evaluate to an object or an array which is observed on each
  12381. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12382. * collection will trigger a call to the `listener`.
  12383. *
  12384. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12385. * when a change is detected.
  12386. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12387. * - The `oldCollection` object is a copy of the former collection data.
  12388. * Due to performance considerations, the`oldCollection` value is computed only if the
  12389. * `listener` function declares two or more arguments.
  12390. * - The `scope` argument refers to the current scope.
  12391. *
  12392. * @returns {function()} Returns a de-registration function for this listener. When the
  12393. * de-registration function is executed, the internal watch operation is terminated.
  12394. */
  12395. $watchCollection: function(obj, listener) {
  12396. $watchCollectionInterceptor.$stateful = true;
  12397. var self = this;
  12398. // the current value, updated on each dirty-check run
  12399. var newValue;
  12400. // a shallow copy of the newValue from the last dirty-check run,
  12401. // updated to match newValue during dirty-check run
  12402. var oldValue;
  12403. // a shallow copy of the newValue from when the last change happened
  12404. var veryOldValue;
  12405. // only track veryOldValue if the listener is asking for it
  12406. var trackVeryOldValue = (listener.length > 1);
  12407. var changeDetected = 0;
  12408. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12409. var internalArray = [];
  12410. var internalObject = {};
  12411. var initRun = true;
  12412. var oldLength = 0;
  12413. function $watchCollectionInterceptor(_value) {
  12414. newValue = _value;
  12415. var newLength, key, bothNaN, newItem, oldItem;
  12416. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  12417. if (isUndefined(newValue)) return;
  12418. if (!isObject(newValue)) { // if primitive
  12419. if (oldValue !== newValue) {
  12420. oldValue = newValue;
  12421. changeDetected++;
  12422. }
  12423. } else if (isArrayLike(newValue)) {
  12424. if (oldValue !== internalArray) {
  12425. // we are transitioning from something which was not an array into array.
  12426. oldValue = internalArray;
  12427. oldLength = oldValue.length = 0;
  12428. changeDetected++;
  12429. }
  12430. newLength = newValue.length;
  12431. if (oldLength !== newLength) {
  12432. // if lengths do not match we need to trigger change notification
  12433. changeDetected++;
  12434. oldValue.length = oldLength = newLength;
  12435. }
  12436. // copy the items to oldValue and look for changes.
  12437. for (var i = 0; i < newLength; i++) {
  12438. oldItem = oldValue[i];
  12439. newItem = newValue[i];
  12440. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12441. if (!bothNaN && (oldItem !== newItem)) {
  12442. changeDetected++;
  12443. oldValue[i] = newItem;
  12444. }
  12445. }
  12446. } else {
  12447. if (oldValue !== internalObject) {
  12448. // we are transitioning from something which was not an object into object.
  12449. oldValue = internalObject = {};
  12450. oldLength = 0;
  12451. changeDetected++;
  12452. }
  12453. // copy the items to oldValue and look for changes.
  12454. newLength = 0;
  12455. for (key in newValue) {
  12456. if (newValue.hasOwnProperty(key)) {
  12457. newLength++;
  12458. newItem = newValue[key];
  12459. oldItem = oldValue[key];
  12460. if (key in oldValue) {
  12461. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12462. if (!bothNaN && (oldItem !== newItem)) {
  12463. changeDetected++;
  12464. oldValue[key] = newItem;
  12465. }
  12466. } else {
  12467. oldLength++;
  12468. oldValue[key] = newItem;
  12469. changeDetected++;
  12470. }
  12471. }
  12472. }
  12473. if (oldLength > newLength) {
  12474. // we used to have more keys, need to find them and destroy them.
  12475. changeDetected++;
  12476. for (key in oldValue) {
  12477. if (!newValue.hasOwnProperty(key)) {
  12478. oldLength--;
  12479. delete oldValue[key];
  12480. }
  12481. }
  12482. }
  12483. }
  12484. return changeDetected;
  12485. }
  12486. function $watchCollectionAction() {
  12487. if (initRun) {
  12488. initRun = false;
  12489. listener(newValue, newValue, self);
  12490. } else {
  12491. listener(newValue, veryOldValue, self);
  12492. }
  12493. // make a copy for the next time a collection is changed
  12494. if (trackVeryOldValue) {
  12495. if (!isObject(newValue)) {
  12496. //primitive
  12497. veryOldValue = newValue;
  12498. } else if (isArrayLike(newValue)) {
  12499. veryOldValue = new Array(newValue.length);
  12500. for (var i = 0; i < newValue.length; i++) {
  12501. veryOldValue[i] = newValue[i];
  12502. }
  12503. } else { // if object
  12504. veryOldValue = {};
  12505. for (var key in newValue) {
  12506. if (hasOwnProperty.call(newValue, key)) {
  12507. veryOldValue[key] = newValue[key];
  12508. }
  12509. }
  12510. }
  12511. }
  12512. }
  12513. return this.$watch(changeDetector, $watchCollectionAction);
  12514. },
  12515. /**
  12516. * @ngdoc method
  12517. * @name $rootScope.Scope#$digest
  12518. * @kind function
  12519. *
  12520. * @description
  12521. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12522. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12523. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12524. * until no more listeners are firing. This means that it is possible to get into an infinite
  12525. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12526. * iterations exceeds 10.
  12527. *
  12528. * Usually, you don't call `$digest()` directly in
  12529. * {@link ng.directive:ngController controllers} or in
  12530. * {@link ng.$compileProvider#directive directives}.
  12531. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12532. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12533. *
  12534. * If you want to be notified whenever `$digest()` is called,
  12535. * you can register a `watchExpression` function with
  12536. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12537. *
  12538. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12539. *
  12540. * # Example
  12541. * ```js
  12542. var scope = ...;
  12543. scope.name = 'misko';
  12544. scope.counter = 0;
  12545. expect(scope.counter).toEqual(0);
  12546. scope.$watch('name', function(newValue, oldValue) {
  12547. scope.counter = scope.counter + 1;
  12548. });
  12549. expect(scope.counter).toEqual(0);
  12550. scope.$digest();
  12551. // the listener is always called during the first $digest loop after it was registered
  12552. expect(scope.counter).toEqual(1);
  12553. scope.$digest();
  12554. // but now it will not be called unless the value changes
  12555. expect(scope.counter).toEqual(1);
  12556. scope.name = 'adam';
  12557. scope.$digest();
  12558. expect(scope.counter).toEqual(2);
  12559. * ```
  12560. *
  12561. */
  12562. $digest: function() {
  12563. var watch, value, last,
  12564. watchers,
  12565. length,
  12566. dirty, ttl = TTL,
  12567. next, current, target = this,
  12568. watchLog = [],
  12569. logIdx, logMsg, asyncTask;
  12570. beginPhase('$digest');
  12571. // Check for changes to browser url that happened in sync before the call to $digest
  12572. $browser.$$checkUrlChange();
  12573. if (this === $rootScope && applyAsyncId !== null) {
  12574. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12575. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12576. $browser.defer.cancel(applyAsyncId);
  12577. flushApplyAsync();
  12578. }
  12579. lastDirtyWatch = null;
  12580. do { // "while dirty" loop
  12581. dirty = false;
  12582. current = target;
  12583. while (asyncQueue.length) {
  12584. try {
  12585. asyncTask = asyncQueue.shift();
  12586. asyncTask.scope.$eval(asyncTask.expression);
  12587. } catch (e) {
  12588. $exceptionHandler(e);
  12589. }
  12590. lastDirtyWatch = null;
  12591. }
  12592. traverseScopesLoop:
  12593. do { // "traverse the scopes" loop
  12594. if ((watchers = current.$$watchers)) {
  12595. // process our watches
  12596. length = watchers.length;
  12597. while (length--) {
  12598. try {
  12599. watch = watchers[length];
  12600. // Most common watches are on primitives, in which case we can short
  12601. // circuit it with === operator, only when === fails do we use .equals
  12602. if (watch) {
  12603. if ((value = watch.get(current)) !== (last = watch.last) &&
  12604. !(watch.eq
  12605. ? equals(value, last)
  12606. : (typeof value === 'number' && typeof last === 'number'
  12607. && isNaN(value) && isNaN(last)))) {
  12608. dirty = true;
  12609. lastDirtyWatch = watch;
  12610. watch.last = watch.eq ? copy(value, null) : value;
  12611. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12612. if (ttl < 5) {
  12613. logIdx = 4 - ttl;
  12614. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12615. logMsg = (isFunction(watch.exp))
  12616. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  12617. : watch.exp;
  12618. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  12619. watchLog[logIdx].push(logMsg);
  12620. }
  12621. } else if (watch === lastDirtyWatch) {
  12622. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12623. // have already been tested.
  12624. dirty = false;
  12625. break traverseScopesLoop;
  12626. }
  12627. }
  12628. } catch (e) {
  12629. $exceptionHandler(e);
  12630. }
  12631. }
  12632. }
  12633. // Insanity Warning: scope depth-first traversal
  12634. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12635. // this piece should be kept in sync with the traversal in $broadcast
  12636. if (!(next = (current.$$childHead ||
  12637. (current !== target && current.$$nextSibling)))) {
  12638. while (current !== target && !(next = current.$$nextSibling)) {
  12639. current = current.$parent;
  12640. }
  12641. }
  12642. } while ((current = next));
  12643. // `break traverseScopesLoop;` takes us to here
  12644. if ((dirty || asyncQueue.length) && !(ttl--)) {
  12645. clearPhase();
  12646. throw $rootScopeMinErr('infdig',
  12647. '{0} $digest() iterations reached. Aborting!\n' +
  12648. 'Watchers fired in the last 5 iterations: {1}',
  12649. TTL, toJson(watchLog));
  12650. }
  12651. } while (dirty || asyncQueue.length);
  12652. clearPhase();
  12653. while (postDigestQueue.length) {
  12654. try {
  12655. postDigestQueue.shift()();
  12656. } catch (e) {
  12657. $exceptionHandler(e);
  12658. }
  12659. }
  12660. },
  12661. /**
  12662. * @ngdoc event
  12663. * @name $rootScope.Scope#$destroy
  12664. * @eventType broadcast on scope being destroyed
  12665. *
  12666. * @description
  12667. * Broadcasted when a scope and its children are being destroyed.
  12668. *
  12669. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12670. * clean up DOM bindings before an element is removed from the DOM.
  12671. */
  12672. /**
  12673. * @ngdoc method
  12674. * @name $rootScope.Scope#$destroy
  12675. * @kind function
  12676. *
  12677. * @description
  12678. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12679. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12680. * propagate to the current scope and its children. Removal also implies that the current
  12681. * scope is eligible for garbage collection.
  12682. *
  12683. * The `$destroy()` is usually used by directives such as
  12684. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12685. * unrolling of the loop.
  12686. *
  12687. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12688. * Application code can register a `$destroy` event handler that will give it a chance to
  12689. * perform any necessary cleanup.
  12690. *
  12691. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12692. * clean up DOM bindings before an element is removed from the DOM.
  12693. */
  12694. $destroy: function() {
  12695. // we can't destroy the root scope or a scope that has been already destroyed
  12696. if (this.$$destroyed) return;
  12697. var parent = this.$parent;
  12698. this.$broadcast('$destroy');
  12699. this.$$destroyed = true;
  12700. if (this === $rootScope) return;
  12701. for (var eventName in this.$$listenerCount) {
  12702. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12703. }
  12704. // sever all the references to parent scopes (after this cleanup, the current scope should
  12705. // not be retained by any of our references and should be eligible for garbage collection)
  12706. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12707. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12708. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12709. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12710. // Disable listeners, watchers and apply/digest methods
  12711. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12712. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12713. this.$$listeners = {};
  12714. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12715. // and inline caches.
  12716. //
  12717. // see:
  12718. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12719. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12720. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12721. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12722. this.$$childTail = this.$root = this.$$watchers = null;
  12723. },
  12724. /**
  12725. * @ngdoc method
  12726. * @name $rootScope.Scope#$eval
  12727. * @kind function
  12728. *
  12729. * @description
  12730. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12731. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12732. * expressions.
  12733. *
  12734. * # Example
  12735. * ```js
  12736. var scope = ng.$rootScope.Scope();
  12737. scope.a = 1;
  12738. scope.b = 2;
  12739. expect(scope.$eval('a+b')).toEqual(3);
  12740. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12741. * ```
  12742. *
  12743. * @param {(string|function())=} expression An angular expression to be executed.
  12744. *
  12745. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12746. * - `function(scope)`: execute the function with the current `scope` parameter.
  12747. *
  12748. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12749. * @returns {*} The result of evaluating the expression.
  12750. */
  12751. $eval: function(expr, locals) {
  12752. return $parse(expr)(this, locals);
  12753. },
  12754. /**
  12755. * @ngdoc method
  12756. * @name $rootScope.Scope#$evalAsync
  12757. * @kind function
  12758. *
  12759. * @description
  12760. * Executes the expression on the current scope at a later point in time.
  12761. *
  12762. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12763. * that:
  12764. *
  12765. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  12766. * rendering).
  12767. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  12768. * `expression` execution.
  12769. *
  12770. * Any exceptions from the execution of the expression are forwarded to the
  12771. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12772. *
  12773. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  12774. * will be scheduled. However, it is encouraged to always call code that changes the model
  12775. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  12776. *
  12777. * @param {(string|function())=} expression An angular expression to be executed.
  12778. *
  12779. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12780. * - `function(scope)`: execute the function with the current `scope` parameter.
  12781. *
  12782. */
  12783. $evalAsync: function(expr) {
  12784. // if we are outside of an $digest loop and this is the first time we are scheduling async
  12785. // task also schedule async auto-flush
  12786. if (!$rootScope.$$phase && !asyncQueue.length) {
  12787. $browser.defer(function() {
  12788. if (asyncQueue.length) {
  12789. $rootScope.$digest();
  12790. }
  12791. });
  12792. }
  12793. asyncQueue.push({scope: this, expression: expr});
  12794. },
  12795. $$postDigest: function(fn) {
  12796. postDigestQueue.push(fn);
  12797. },
  12798. /**
  12799. * @ngdoc method
  12800. * @name $rootScope.Scope#$apply
  12801. * @kind function
  12802. *
  12803. * @description
  12804. * `$apply()` is used to execute an expression in angular from outside of the angular
  12805. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  12806. * Because we are calling into the angular framework we need to perform proper scope life
  12807. * cycle of {@link ng.$exceptionHandler exception handling},
  12808. * {@link ng.$rootScope.Scope#$digest executing watches}.
  12809. *
  12810. * ## Life cycle
  12811. *
  12812. * # Pseudo-Code of `$apply()`
  12813. * ```js
  12814. function $apply(expr) {
  12815. try {
  12816. return $eval(expr);
  12817. } catch (e) {
  12818. $exceptionHandler(e);
  12819. } finally {
  12820. $root.$digest();
  12821. }
  12822. }
  12823. * ```
  12824. *
  12825. *
  12826. * Scope's `$apply()` method transitions through the following stages:
  12827. *
  12828. * 1. The {@link guide/expression expression} is executed using the
  12829. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  12830. * 2. Any exceptions from the execution of the expression are forwarded to the
  12831. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12832. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  12833. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  12834. *
  12835. *
  12836. * @param {(string|function())=} exp An angular expression to be executed.
  12837. *
  12838. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12839. * - `function(scope)`: execute the function with current `scope` parameter.
  12840. *
  12841. * @returns {*} The result of evaluating the expression.
  12842. */
  12843. $apply: function(expr) {
  12844. try {
  12845. beginPhase('$apply');
  12846. return this.$eval(expr);
  12847. } catch (e) {
  12848. $exceptionHandler(e);
  12849. } finally {
  12850. clearPhase();
  12851. try {
  12852. $rootScope.$digest();
  12853. } catch (e) {
  12854. $exceptionHandler(e);
  12855. throw e;
  12856. }
  12857. }
  12858. },
  12859. /**
  12860. * @ngdoc method
  12861. * @name $rootScope.Scope#$applyAsync
  12862. * @kind function
  12863. *
  12864. * @description
  12865. * Schedule the invokation of $apply to occur at a later time. The actual time difference
  12866. * varies across browsers, but is typically around ~10 milliseconds.
  12867. *
  12868. * This can be used to queue up multiple expressions which need to be evaluated in the same
  12869. * digest.
  12870. *
  12871. * @param {(string|function())=} exp An angular expression to be executed.
  12872. *
  12873. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12874. * - `function(scope)`: execute the function with current `scope` parameter.
  12875. */
  12876. $applyAsync: function(expr) {
  12877. var scope = this;
  12878. expr && applyAsyncQueue.push($applyAsyncExpression);
  12879. scheduleApplyAsync();
  12880. function $applyAsyncExpression() {
  12881. scope.$eval(expr);
  12882. }
  12883. },
  12884. /**
  12885. * @ngdoc method
  12886. * @name $rootScope.Scope#$on
  12887. * @kind function
  12888. *
  12889. * @description
  12890. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  12891. * discussion of event life cycle.
  12892. *
  12893. * The event listener function format is: `function(event, args...)`. The `event` object
  12894. * passed into the listener has the following attributes:
  12895. *
  12896. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  12897. * `$broadcast`-ed.
  12898. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  12899. * event propagates through the scope hierarchy, this property is set to null.
  12900. * - `name` - `{string}`: name of the event.
  12901. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  12902. * further event propagation (available only for events that were `$emit`-ed).
  12903. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  12904. * to true.
  12905. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  12906. *
  12907. * @param {string} name Event name to listen on.
  12908. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  12909. * @returns {function()} Returns a deregistration function for this listener.
  12910. */
  12911. $on: function(name, listener) {
  12912. var namedListeners = this.$$listeners[name];
  12913. if (!namedListeners) {
  12914. this.$$listeners[name] = namedListeners = [];
  12915. }
  12916. namedListeners.push(listener);
  12917. var current = this;
  12918. do {
  12919. if (!current.$$listenerCount[name]) {
  12920. current.$$listenerCount[name] = 0;
  12921. }
  12922. current.$$listenerCount[name]++;
  12923. } while ((current = current.$parent));
  12924. var self = this;
  12925. return function() {
  12926. var indexOfListener = namedListeners.indexOf(listener);
  12927. if (indexOfListener !== -1) {
  12928. namedListeners[indexOfListener] = null;
  12929. decrementListenerCount(self, 1, name);
  12930. }
  12931. };
  12932. },
  12933. /**
  12934. * @ngdoc method
  12935. * @name $rootScope.Scope#$emit
  12936. * @kind function
  12937. *
  12938. * @description
  12939. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  12940. * registered {@link ng.$rootScope.Scope#$on} listeners.
  12941. *
  12942. * The event life cycle starts at the scope on which `$emit` was called. All
  12943. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  12944. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  12945. * registered listeners along the way. The event will stop propagating if one of the listeners
  12946. * cancels it.
  12947. *
  12948. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  12949. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  12950. *
  12951. * @param {string} name Event name to emit.
  12952. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  12953. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  12954. */
  12955. $emit: function(name, args) {
  12956. var empty = [],
  12957. namedListeners,
  12958. scope = this,
  12959. stopPropagation = false,
  12960. event = {
  12961. name: name,
  12962. targetScope: scope,
  12963. stopPropagation: function() {stopPropagation = true;},
  12964. preventDefault: function() {
  12965. event.defaultPrevented = true;
  12966. },
  12967. defaultPrevented: false
  12968. },
  12969. listenerArgs = concat([event], arguments, 1),
  12970. i, length;
  12971. do {
  12972. namedListeners = scope.$$listeners[name] || empty;
  12973. event.currentScope = scope;
  12974. for (i=0, length=namedListeners.length; i<length; i++) {
  12975. // if listeners were deregistered, defragment the array
  12976. if (!namedListeners[i]) {
  12977. namedListeners.splice(i, 1);
  12978. i--;
  12979. length--;
  12980. continue;
  12981. }
  12982. try {
  12983. //allow all listeners attached to the current scope to run
  12984. namedListeners[i].apply(null, listenerArgs);
  12985. } catch (e) {
  12986. $exceptionHandler(e);
  12987. }
  12988. }
  12989. //if any listener on the current scope stops propagation, prevent bubbling
  12990. if (stopPropagation) {
  12991. event.currentScope = null;
  12992. return event;
  12993. }
  12994. //traverse upwards
  12995. scope = scope.$parent;
  12996. } while (scope);
  12997. event.currentScope = null;
  12998. return event;
  12999. },
  13000. /**
  13001. * @ngdoc method
  13002. * @name $rootScope.Scope#$broadcast
  13003. * @kind function
  13004. *
  13005. * @description
  13006. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  13007. * registered {@link ng.$rootScope.Scope#$on} listeners.
  13008. *
  13009. * The event life cycle starts at the scope on which `$broadcast` was called. All
  13010. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  13011. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  13012. * scope and calls all registered listeners along the way. The event cannot be canceled.
  13013. *
  13014. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  13015. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  13016. *
  13017. * @param {string} name Event name to broadcast.
  13018. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  13019. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  13020. */
  13021. $broadcast: function(name, args) {
  13022. var target = this,
  13023. current = target,
  13024. next = target,
  13025. event = {
  13026. name: name,
  13027. targetScope: target,
  13028. preventDefault: function() {
  13029. event.defaultPrevented = true;
  13030. },
  13031. defaultPrevented: false
  13032. };
  13033. if (!target.$$listenerCount[name]) return event;
  13034. var listenerArgs = concat([event], arguments, 1),
  13035. listeners, i, length;
  13036. //down while you can, then up and next sibling or up and next sibling until back at root
  13037. while ((current = next)) {
  13038. event.currentScope = current;
  13039. listeners = current.$$listeners[name] || [];
  13040. for (i=0, length = listeners.length; i<length; i++) {
  13041. // if listeners were deregistered, defragment the array
  13042. if (!listeners[i]) {
  13043. listeners.splice(i, 1);
  13044. i--;
  13045. length--;
  13046. continue;
  13047. }
  13048. try {
  13049. listeners[i].apply(null, listenerArgs);
  13050. } catch (e) {
  13051. $exceptionHandler(e);
  13052. }
  13053. }
  13054. // Insanity Warning: scope depth-first traversal
  13055. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  13056. // this piece should be kept in sync with the traversal in $digest
  13057. // (though it differs due to having the extra check for $$listenerCount)
  13058. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  13059. (current !== target && current.$$nextSibling)))) {
  13060. while (current !== target && !(next = current.$$nextSibling)) {
  13061. current = current.$parent;
  13062. }
  13063. }
  13064. }
  13065. event.currentScope = null;
  13066. return event;
  13067. }
  13068. };
  13069. var $rootScope = new Scope();
  13070. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  13071. var asyncQueue = $rootScope.$$asyncQueue = [];
  13072. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  13073. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  13074. return $rootScope;
  13075. function beginPhase(phase) {
  13076. if ($rootScope.$$phase) {
  13077. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13078. }
  13079. $rootScope.$$phase = phase;
  13080. }
  13081. function clearPhase() {
  13082. $rootScope.$$phase = null;
  13083. }
  13084. function decrementListenerCount(current, count, name) {
  13085. do {
  13086. current.$$listenerCount[name] -= count;
  13087. if (current.$$listenerCount[name] === 0) {
  13088. delete current.$$listenerCount[name];
  13089. }
  13090. } while ((current = current.$parent));
  13091. }
  13092. /**
  13093. * function used as an initial value for watchers.
  13094. * because it's unique we can easily tell it apart from other values
  13095. */
  13096. function initWatchVal() {}
  13097. function flushApplyAsync() {
  13098. while (applyAsyncQueue.length) {
  13099. try {
  13100. applyAsyncQueue.shift()();
  13101. } catch (e) {
  13102. $exceptionHandler(e);
  13103. }
  13104. }
  13105. applyAsyncId = null;
  13106. }
  13107. function scheduleApplyAsync() {
  13108. if (applyAsyncId === null) {
  13109. applyAsyncId = $browser.defer(function() {
  13110. $rootScope.$apply(flushApplyAsync);
  13111. });
  13112. }
  13113. }
  13114. }];
  13115. }
  13116. /**
  13117. * @description
  13118. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13119. */
  13120. function $$SanitizeUriProvider() {
  13121. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13122. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13123. /**
  13124. * @description
  13125. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13126. * urls during a[href] sanitization.
  13127. *
  13128. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13129. *
  13130. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13131. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13132. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13133. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13134. *
  13135. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13136. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13137. * chaining otherwise.
  13138. */
  13139. this.aHrefSanitizationWhitelist = function(regexp) {
  13140. if (isDefined(regexp)) {
  13141. aHrefSanitizationWhitelist = regexp;
  13142. return this;
  13143. }
  13144. return aHrefSanitizationWhitelist;
  13145. };
  13146. /**
  13147. * @description
  13148. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13149. * urls during img[src] sanitization.
  13150. *
  13151. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13152. *
  13153. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13154. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13155. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13156. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13157. *
  13158. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13159. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13160. * chaining otherwise.
  13161. */
  13162. this.imgSrcSanitizationWhitelist = function(regexp) {
  13163. if (isDefined(regexp)) {
  13164. imgSrcSanitizationWhitelist = regexp;
  13165. return this;
  13166. }
  13167. return imgSrcSanitizationWhitelist;
  13168. };
  13169. this.$get = function() {
  13170. return function sanitizeUri(uri, isImage) {
  13171. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13172. var normalizedVal;
  13173. normalizedVal = urlResolve(uri).href;
  13174. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13175. return 'unsafe:'+normalizedVal;
  13176. }
  13177. return uri;
  13178. };
  13179. };
  13180. }
  13181. var $sceMinErr = minErr('$sce');
  13182. var SCE_CONTEXTS = {
  13183. HTML: 'html',
  13184. CSS: 'css',
  13185. URL: 'url',
  13186. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13187. // url. (e.g. ng-include, script src, templateUrl)
  13188. RESOURCE_URL: 'resourceUrl',
  13189. JS: 'js'
  13190. };
  13191. // Helper functions follow.
  13192. function adjustMatcher(matcher) {
  13193. if (matcher === 'self') {
  13194. return matcher;
  13195. } else if (isString(matcher)) {
  13196. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13197. // '*' matches any character except those from the set ':/.?&'.
  13198. // '**' matches any character (like .* in a RegExp).
  13199. // More than 2 *'s raises an error as it's ill defined.
  13200. if (matcher.indexOf('***') > -1) {
  13201. throw $sceMinErr('iwcard',
  13202. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13203. }
  13204. matcher = escapeForRegexp(matcher).
  13205. replace('\\*\\*', '.*').
  13206. replace('\\*', '[^:/.?&;]*');
  13207. return new RegExp('^' + matcher + '$');
  13208. } else if (isRegExp(matcher)) {
  13209. // The only other type of matcher allowed is a Regexp.
  13210. // Match entire URL / disallow partial matches.
  13211. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13212. return new RegExp('^' + matcher.source + '$');
  13213. } else {
  13214. throw $sceMinErr('imatcher',
  13215. 'Matchers may only be "self", string patterns or RegExp objects');
  13216. }
  13217. }
  13218. function adjustMatchers(matchers) {
  13219. var adjustedMatchers = [];
  13220. if (isDefined(matchers)) {
  13221. forEach(matchers, function(matcher) {
  13222. adjustedMatchers.push(adjustMatcher(matcher));
  13223. });
  13224. }
  13225. return adjustedMatchers;
  13226. }
  13227. /**
  13228. * @ngdoc service
  13229. * @name $sceDelegate
  13230. * @kind function
  13231. *
  13232. * @description
  13233. *
  13234. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13235. * Contextual Escaping (SCE)} services to AngularJS.
  13236. *
  13237. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13238. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13239. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13240. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13241. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13242. *
  13243. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13244. *
  13245. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13246. * can override it completely to change the behavior of `$sce`, the common case would
  13247. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13248. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13249. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13250. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13251. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13252. */
  13253. /**
  13254. * @ngdoc provider
  13255. * @name $sceDelegateProvider
  13256. * @description
  13257. *
  13258. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13259. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13260. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13261. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13262. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13263. *
  13264. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13265. * Strict Contextual Escaping (SCE)}.
  13266. *
  13267. * **Example**: Consider the following case. <a name="example"></a>
  13268. *
  13269. * - your app is hosted at url `http://myapp.example.com/`
  13270. * - but some of your templates are hosted on other domains you control such as
  13271. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13272. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13273. *
  13274. * Here is what a secure configuration for this scenario might look like:
  13275. *
  13276. * ```
  13277. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13278. * $sceDelegateProvider.resourceUrlWhitelist([
  13279. * // Allow same origin resource loads.
  13280. * 'self',
  13281. * // Allow loading from our assets domain. Notice the difference between * and **.
  13282. * 'http://srv*.assets.example.com/**'
  13283. * ]);
  13284. *
  13285. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13286. * $sceDelegateProvider.resourceUrlBlacklist([
  13287. * 'http://myapp.example.com/clickThru**'
  13288. * ]);
  13289. * });
  13290. * ```
  13291. */
  13292. function $SceDelegateProvider() {
  13293. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13294. // Resource URLs can also be trusted by policy.
  13295. var resourceUrlWhitelist = ['self'],
  13296. resourceUrlBlacklist = [];
  13297. /**
  13298. * @ngdoc method
  13299. * @name $sceDelegateProvider#resourceUrlWhitelist
  13300. * @kind function
  13301. *
  13302. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13303. * provided. This must be an array or null. A snapshot of this array is used so further
  13304. * changes to the array are ignored.
  13305. *
  13306. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13307. * allowed in this array.
  13308. *
  13309. * Note: **an empty whitelist array will block all URLs**!
  13310. *
  13311. * @return {Array} the currently set whitelist array.
  13312. *
  13313. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13314. * same origin resource requests.
  13315. *
  13316. * @description
  13317. * Sets/Gets the whitelist of trusted resource URLs.
  13318. */
  13319. this.resourceUrlWhitelist = function(value) {
  13320. if (arguments.length) {
  13321. resourceUrlWhitelist = adjustMatchers(value);
  13322. }
  13323. return resourceUrlWhitelist;
  13324. };
  13325. /**
  13326. * @ngdoc method
  13327. * @name $sceDelegateProvider#resourceUrlBlacklist
  13328. * @kind function
  13329. *
  13330. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13331. * provided. This must be an array or null. A snapshot of this array is used so further
  13332. * changes to the array are ignored.
  13333. *
  13334. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13335. * allowed in this array.
  13336. *
  13337. * The typical usage for the blacklist is to **block
  13338. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13339. * these would otherwise be trusted but actually return content from the redirected domain.
  13340. *
  13341. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13342. *
  13343. * @return {Array} the currently set blacklist array.
  13344. *
  13345. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13346. * is no blacklist.)
  13347. *
  13348. * @description
  13349. * Sets/Gets the blacklist of trusted resource URLs.
  13350. */
  13351. this.resourceUrlBlacklist = function(value) {
  13352. if (arguments.length) {
  13353. resourceUrlBlacklist = adjustMatchers(value);
  13354. }
  13355. return resourceUrlBlacklist;
  13356. };
  13357. this.$get = ['$injector', function($injector) {
  13358. var htmlSanitizer = function htmlSanitizer(html) {
  13359. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13360. };
  13361. if ($injector.has('$sanitize')) {
  13362. htmlSanitizer = $injector.get('$sanitize');
  13363. }
  13364. function matchUrl(matcher, parsedUrl) {
  13365. if (matcher === 'self') {
  13366. return urlIsSameOrigin(parsedUrl);
  13367. } else {
  13368. // definitely a regex. See adjustMatchers()
  13369. return !!matcher.exec(parsedUrl.href);
  13370. }
  13371. }
  13372. function isResourceUrlAllowedByPolicy(url) {
  13373. var parsedUrl = urlResolve(url.toString());
  13374. var i, n, allowed = false;
  13375. // Ensure that at least one item from the whitelist allows this url.
  13376. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13377. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13378. allowed = true;
  13379. break;
  13380. }
  13381. }
  13382. if (allowed) {
  13383. // Ensure that no item from the blacklist blocked this url.
  13384. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13385. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13386. allowed = false;
  13387. break;
  13388. }
  13389. }
  13390. }
  13391. return allowed;
  13392. }
  13393. function generateHolderType(Base) {
  13394. var holderType = function TrustedValueHolderType(trustedValue) {
  13395. this.$$unwrapTrustedValue = function() {
  13396. return trustedValue;
  13397. };
  13398. };
  13399. if (Base) {
  13400. holderType.prototype = new Base();
  13401. }
  13402. holderType.prototype.valueOf = function sceValueOf() {
  13403. return this.$$unwrapTrustedValue();
  13404. };
  13405. holderType.prototype.toString = function sceToString() {
  13406. return this.$$unwrapTrustedValue().toString();
  13407. };
  13408. return holderType;
  13409. }
  13410. var trustedValueHolderBase = generateHolderType(),
  13411. byType = {};
  13412. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13413. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13414. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13415. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13416. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13417. /**
  13418. * @ngdoc method
  13419. * @name $sceDelegate#trustAs
  13420. *
  13421. * @description
  13422. * Returns an object that is trusted by angular for use in specified strict
  13423. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13424. * attribute interpolation, any dom event binding attribute interpolation
  13425. * such as for onclick, etc.) that uses the provided value.
  13426. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13427. *
  13428. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13429. * resourceUrl, html, js and css.
  13430. * @param {*} value The value that that should be considered trusted/safe.
  13431. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13432. * where Angular expects a $sce.trustAs() return value.
  13433. */
  13434. function trustAs(type, trustedValue) {
  13435. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13436. if (!Constructor) {
  13437. throw $sceMinErr('icontext',
  13438. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13439. type, trustedValue);
  13440. }
  13441. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13442. return trustedValue;
  13443. }
  13444. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13445. // mutable objects, we ensure here that the value passed in is actually a string.
  13446. if (typeof trustedValue !== 'string') {
  13447. throw $sceMinErr('itype',
  13448. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13449. type);
  13450. }
  13451. return new Constructor(trustedValue);
  13452. }
  13453. /**
  13454. * @ngdoc method
  13455. * @name $sceDelegate#valueOf
  13456. *
  13457. * @description
  13458. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13459. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13460. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13461. *
  13462. * If the passed parameter is not a value that had been returned by {@link
  13463. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13464. *
  13465. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13466. * call or anything else.
  13467. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13468. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13469. * `value` unchanged.
  13470. */
  13471. function valueOf(maybeTrusted) {
  13472. if (maybeTrusted instanceof trustedValueHolderBase) {
  13473. return maybeTrusted.$$unwrapTrustedValue();
  13474. } else {
  13475. return maybeTrusted;
  13476. }
  13477. }
  13478. /**
  13479. * @ngdoc method
  13480. * @name $sceDelegate#getTrusted
  13481. *
  13482. * @description
  13483. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13484. * returns the originally supplied value if the queried context type is a supertype of the
  13485. * created type. If this condition isn't satisfied, throws an exception.
  13486. *
  13487. * @param {string} type The kind of context in which this value is to be used.
  13488. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13489. * `$sceDelegate.trustAs`} call.
  13490. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13491. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13492. */
  13493. function getTrusted(type, maybeTrusted) {
  13494. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13495. return maybeTrusted;
  13496. }
  13497. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13498. if (constructor && maybeTrusted instanceof constructor) {
  13499. return maybeTrusted.$$unwrapTrustedValue();
  13500. }
  13501. // If we get here, then we may only take one of two actions.
  13502. // 1. sanitize the value for the requested type, or
  13503. // 2. throw an exception.
  13504. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13505. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13506. return maybeTrusted;
  13507. } else {
  13508. throw $sceMinErr('insecurl',
  13509. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13510. maybeTrusted.toString());
  13511. }
  13512. } else if (type === SCE_CONTEXTS.HTML) {
  13513. return htmlSanitizer(maybeTrusted);
  13514. }
  13515. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13516. }
  13517. return { trustAs: trustAs,
  13518. getTrusted: getTrusted,
  13519. valueOf: valueOf };
  13520. }];
  13521. }
  13522. /**
  13523. * @ngdoc provider
  13524. * @name $sceProvider
  13525. * @description
  13526. *
  13527. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13528. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13529. * - override the default implementation with a custom delegate
  13530. *
  13531. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13532. */
  13533. /* jshint maxlen: false*/
  13534. /**
  13535. * @ngdoc service
  13536. * @name $sce
  13537. * @kind function
  13538. *
  13539. * @description
  13540. *
  13541. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13542. *
  13543. * # Strict Contextual Escaping
  13544. *
  13545. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13546. * contexts to result in a value that is marked as safe to use for that context. One example of
  13547. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13548. * to these contexts as privileged or SCE contexts.
  13549. *
  13550. * As of version 1.2, Angular ships with SCE enabled by default.
  13551. *
  13552. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13553. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13554. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13555. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13556. * to the top of your HTML document.
  13557. *
  13558. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13559. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13560. *
  13561. * Here's an example of a binding in a privileged context:
  13562. *
  13563. * ```
  13564. * <input ng-model="userHtml">
  13565. * <div ng-bind-html="userHtml"></div>
  13566. * ```
  13567. *
  13568. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13569. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13570. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13571. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13572. * security vulnerabilities.)
  13573. *
  13574. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13575. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13576. *
  13577. * How would you ensure that every place that used these types of bindings was bound to a value that
  13578. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13579. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13580. * properties/fields and forgot to update the binding to the sanitized value?
  13581. *
  13582. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13583. * determine that something explicitly says it's safe to use a value for binding in that
  13584. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13585. * for those values that you can easily tell are safe - because they were received from your server,
  13586. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13587. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13588. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13589. *
  13590. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13591. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13592. * obtain values that will be accepted by SCE / privileged contexts.
  13593. *
  13594. *
  13595. * ## How does it work?
  13596. *
  13597. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13598. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13599. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13600. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13601. *
  13602. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13603. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13604. * simplified):
  13605. *
  13606. * ```
  13607. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13608. * return function(scope, element, attr) {
  13609. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13610. * element.html(value || '');
  13611. * });
  13612. * };
  13613. * }];
  13614. * ```
  13615. *
  13616. * ## Impact on loading templates
  13617. *
  13618. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13619. * `templateUrl`'s specified by {@link guide/directive directives}.
  13620. *
  13621. * By default, Angular only loads templates from the same domain and protocol as the application
  13622. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13623. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13624. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13625. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13626. *
  13627. * *Please note*:
  13628. * The browser's
  13629. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13630. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13631. * policy apply in addition to this and may further restrict whether the template is successfully
  13632. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13633. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13634. * browsers.
  13635. *
  13636. * ## This feels like too much overhead
  13637. *
  13638. * It's important to remember that SCE only applies to interpolation expressions.
  13639. *
  13640. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13641. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13642. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13643. *
  13644. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13645. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13646. *
  13647. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13648. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13649. * It blocks loading templates from other domains or loading templates over http from an https
  13650. * served document. You can change these by setting your own custom {@link
  13651. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13652. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13653. *
  13654. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13655. * application that's secure and can be audited to verify that with much more ease than bolting
  13656. * security onto an application later.
  13657. *
  13658. * <a name="contexts"></a>
  13659. * ## What trusted context types are supported?
  13660. *
  13661. * | Context | Notes |
  13662. * |---------------------|----------------|
  13663. * | `$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. |
  13664. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13665. * | `$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. |
  13666. * | `$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. |
  13667. * | `$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. |
  13668. *
  13669. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13670. *
  13671. * Each element in these arrays must be one of the following:
  13672. *
  13673. * - **'self'**
  13674. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13675. * domain** as the application document using the **same protocol**.
  13676. * - **String** (except the special value `'self'`)
  13677. * - The string is matched against the full *normalized / absolute URL* of the resource
  13678. * being tested (substring matches are not good enough.)
  13679. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13680. * match themselves.
  13681. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13682. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13683. * in a whitelist.
  13684. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13685. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13686. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13687. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13688. * http://foo.example.com/templates/**).
  13689. * - **RegExp** (*see caveat below*)
  13690. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13691. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13692. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13693. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13694. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13695. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13696. * is highly recommended to use the string patterns and only fall back to regular expressions
  13697. * if they as a last resort.
  13698. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13699. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13700. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13701. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13702. * - If you are generating your JavaScript from some other templating engine (not
  13703. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13704. * remember to escape your regular expression (and be aware that you might need more than
  13705. * one level of escaping depending on your templating engine and the way you interpolated
  13706. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13707. * enough before coding your own. e.g. Ruby has
  13708. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13709. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13710. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13711. * Closure library's [goog.string.regExpEscape(s)](
  13712. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13713. *
  13714. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13715. *
  13716. * ## Show me an example using SCE.
  13717. *
  13718. * <example module="mySceApp" deps="angular-sanitize.js">
  13719. * <file name="index.html">
  13720. * <div ng-controller="AppController as myCtrl">
  13721. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13722. * <b>User comments</b><br>
  13723. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13724. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13725. * exploit.
  13726. * <div class="well">
  13727. * <div ng-repeat="userComment in myCtrl.userComments">
  13728. * <b>{{userComment.name}}</b>:
  13729. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13730. * <br>
  13731. * </div>
  13732. * </div>
  13733. * </div>
  13734. * </file>
  13735. *
  13736. * <file name="script.js">
  13737. * angular.module('mySceApp', ['ngSanitize'])
  13738. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13739. * function($http, $templateCache, $sce) {
  13740. * var self = this;
  13741. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13742. * self.userComments = userComments;
  13743. * });
  13744. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13745. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13746. * 'sanitization.&quot;">Hover over this text.</span>');
  13747. * }]);
  13748. * </file>
  13749. *
  13750. * <file name="test_data.json">
  13751. * [
  13752. * { "name": "Alice",
  13753. * "htmlComment":
  13754. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  13755. * },
  13756. * { "name": "Bob",
  13757. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  13758. * }
  13759. * ]
  13760. * </file>
  13761. *
  13762. * <file name="protractor.js" type="protractor">
  13763. * describe('SCE doc demo', function() {
  13764. * it('should sanitize untrusted values', function() {
  13765. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  13766. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  13767. * });
  13768. *
  13769. * it('should NOT sanitize explicitly trusted values', function() {
  13770. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  13771. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13772. * 'sanitization.&quot;">Hover over this text.</span>');
  13773. * });
  13774. * });
  13775. * </file>
  13776. * </example>
  13777. *
  13778. *
  13779. *
  13780. * ## Can I disable SCE completely?
  13781. *
  13782. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  13783. * for little coding overhead. It will be much harder to take an SCE disabled application and
  13784. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  13785. * for cases where you have a lot of existing code that was written before SCE was introduced and
  13786. * you're migrating them a module at a time.
  13787. *
  13788. * That said, here's how you can completely disable SCE:
  13789. *
  13790. * ```
  13791. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  13792. * // Completely disable SCE. For demonstration purposes only!
  13793. * // Do not use in new projects.
  13794. * $sceProvider.enabled(false);
  13795. * });
  13796. * ```
  13797. *
  13798. */
  13799. /* jshint maxlen: 100 */
  13800. function $SceProvider() {
  13801. var enabled = true;
  13802. /**
  13803. * @ngdoc method
  13804. * @name $sceProvider#enabled
  13805. * @kind function
  13806. *
  13807. * @param {boolean=} value If provided, then enables/disables SCE.
  13808. * @return {boolean} true if SCE is enabled, false otherwise.
  13809. *
  13810. * @description
  13811. * Enables/disables SCE and returns the current value.
  13812. */
  13813. this.enabled = function(value) {
  13814. if (arguments.length) {
  13815. enabled = !!value;
  13816. }
  13817. return enabled;
  13818. };
  13819. /* Design notes on the default implementation for SCE.
  13820. *
  13821. * The API contract for the SCE delegate
  13822. * -------------------------------------
  13823. * The SCE delegate object must provide the following 3 methods:
  13824. *
  13825. * - trustAs(contextEnum, value)
  13826. * This method is used to tell the SCE service that the provided value is OK to use in the
  13827. * contexts specified by contextEnum. It must return an object that will be accepted by
  13828. * getTrusted() for a compatible contextEnum and return this value.
  13829. *
  13830. * - valueOf(value)
  13831. * For values that were not produced by trustAs(), return them as is. For values that were
  13832. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  13833. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  13834. * such a value.
  13835. *
  13836. * - getTrusted(contextEnum, value)
  13837. * This function should return the a value that is safe to use in the context specified by
  13838. * contextEnum or throw and exception otherwise.
  13839. *
  13840. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  13841. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  13842. * instance, an implementation could maintain a registry of all trusted objects by context. In
  13843. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  13844. * return the same object passed in if it was found in the registry under a compatible context or
  13845. * throw an exception otherwise. An implementation might only wrap values some of the time based
  13846. * on some criteria. getTrusted() might return a value and not throw an exception for special
  13847. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  13848. *
  13849. *
  13850. * A note on the inheritance model for SCE contexts
  13851. * ------------------------------------------------
  13852. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  13853. * is purely an implementation details.
  13854. *
  13855. * The contract is simply this:
  13856. *
  13857. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  13858. * will also succeed.
  13859. *
  13860. * Inheritance happens to capture this in a natural way. In some future, we
  13861. * may not use inheritance anymore. That is OK because no code outside of
  13862. * sce.js and sceSpecs.js would need to be aware of this detail.
  13863. */
  13864. this.$get = ['$parse', '$sceDelegate', function(
  13865. $parse, $sceDelegate) {
  13866. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  13867. // the "expression(javascript expression)" syntax which is insecure.
  13868. if (enabled && msie < 8) {
  13869. throw $sceMinErr('iequirks',
  13870. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  13871. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  13872. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  13873. }
  13874. var sce = shallowCopy(SCE_CONTEXTS);
  13875. /**
  13876. * @ngdoc method
  13877. * @name $sce#isEnabled
  13878. * @kind function
  13879. *
  13880. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  13881. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  13882. *
  13883. * @description
  13884. * Returns a boolean indicating if SCE is enabled.
  13885. */
  13886. sce.isEnabled = function() {
  13887. return enabled;
  13888. };
  13889. sce.trustAs = $sceDelegate.trustAs;
  13890. sce.getTrusted = $sceDelegate.getTrusted;
  13891. sce.valueOf = $sceDelegate.valueOf;
  13892. if (!enabled) {
  13893. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  13894. sce.valueOf = identity;
  13895. }
  13896. /**
  13897. * @ngdoc method
  13898. * @name $sce#parseAs
  13899. *
  13900. * @description
  13901. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  13902. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  13903. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  13904. * *result*)}
  13905. *
  13906. * @param {string} type The kind of SCE context in which this result will be used.
  13907. * @param {string} expression String expression to compile.
  13908. * @returns {function(context, locals)} a function which represents the compiled expression:
  13909. *
  13910. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13911. * are evaluated against (typically a scope object).
  13912. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13913. * `context`.
  13914. */
  13915. sce.parseAs = function sceParseAs(type, expr) {
  13916. var parsed = $parse(expr);
  13917. if (parsed.literal && parsed.constant) {
  13918. return parsed;
  13919. } else {
  13920. return $parse(expr, function(value) {
  13921. return sce.getTrusted(type, value);
  13922. });
  13923. }
  13924. };
  13925. /**
  13926. * @ngdoc method
  13927. * @name $sce#trustAs
  13928. *
  13929. * @description
  13930. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  13931. * returns an object that is trusted by angular for use in specified strict contextual
  13932. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  13933. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  13934. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  13935. * escaping.
  13936. *
  13937. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13938. * resource_url, html, js and css.
  13939. * @param {*} value The value that that should be considered trusted/safe.
  13940. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13941. * where Angular expects a $sce.trustAs() return value.
  13942. */
  13943. /**
  13944. * @ngdoc method
  13945. * @name $sce#trustAsHtml
  13946. *
  13947. * @description
  13948. * Shorthand method. `$sce.trustAsHtml(value)` →
  13949. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  13950. *
  13951. * @param {*} value The value to trustAs.
  13952. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  13953. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  13954. * only accept expressions that are either literal constants or are the
  13955. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13956. */
  13957. /**
  13958. * @ngdoc method
  13959. * @name $sce#trustAsUrl
  13960. *
  13961. * @description
  13962. * Shorthand method. `$sce.trustAsUrl(value)` →
  13963. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  13964. *
  13965. * @param {*} value The value to trustAs.
  13966. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  13967. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  13968. * only accept expressions that are either literal constants or are the
  13969. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13970. */
  13971. /**
  13972. * @ngdoc method
  13973. * @name $sce#trustAsResourceUrl
  13974. *
  13975. * @description
  13976. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  13977. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  13978. *
  13979. * @param {*} value The value to trustAs.
  13980. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  13981. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  13982. * only accept expressions that are either literal constants or are the return
  13983. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13984. */
  13985. /**
  13986. * @ngdoc method
  13987. * @name $sce#trustAsJs
  13988. *
  13989. * @description
  13990. * Shorthand method. `$sce.trustAsJs(value)` →
  13991. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  13992. *
  13993. * @param {*} value The value to trustAs.
  13994. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  13995. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  13996. * only accept expressions that are either literal constants or are the
  13997. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13998. */
  13999. /**
  14000. * @ngdoc method
  14001. * @name $sce#getTrusted
  14002. *
  14003. * @description
  14004. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  14005. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  14006. * originally supplied value if the queried context type is a supertype of the created type.
  14007. * If this condition isn't satisfied, throws an exception.
  14008. *
  14009. * @param {string} type The kind of context in which this value is to be used.
  14010. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  14011. * call.
  14012. * @returns {*} The value the was originally provided to
  14013. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  14014. * Otherwise, throws an exception.
  14015. */
  14016. /**
  14017. * @ngdoc method
  14018. * @name $sce#getTrustedHtml
  14019. *
  14020. * @description
  14021. * Shorthand method. `$sce.getTrustedHtml(value)` →
  14022. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  14023. *
  14024. * @param {*} value The value to pass to `$sce.getTrusted`.
  14025. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  14026. */
  14027. /**
  14028. * @ngdoc method
  14029. * @name $sce#getTrustedCss
  14030. *
  14031. * @description
  14032. * Shorthand method. `$sce.getTrustedCss(value)` →
  14033. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  14034. *
  14035. * @param {*} value The value to pass to `$sce.getTrusted`.
  14036. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  14037. */
  14038. /**
  14039. * @ngdoc method
  14040. * @name $sce#getTrustedUrl
  14041. *
  14042. * @description
  14043. * Shorthand method. `$sce.getTrustedUrl(value)` →
  14044. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  14045. *
  14046. * @param {*} value The value to pass to `$sce.getTrusted`.
  14047. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  14048. */
  14049. /**
  14050. * @ngdoc method
  14051. * @name $sce#getTrustedResourceUrl
  14052. *
  14053. * @description
  14054. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  14055. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  14056. *
  14057. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  14058. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  14059. */
  14060. /**
  14061. * @ngdoc method
  14062. * @name $sce#getTrustedJs
  14063. *
  14064. * @description
  14065. * Shorthand method. `$sce.getTrustedJs(value)` →
  14066. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  14067. *
  14068. * @param {*} value The value to pass to `$sce.getTrusted`.
  14069. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14070. */
  14071. /**
  14072. * @ngdoc method
  14073. * @name $sce#parseAsHtml
  14074. *
  14075. * @description
  14076. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14077. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14078. *
  14079. * @param {string} expression String expression to compile.
  14080. * @returns {function(context, locals)} a function which represents the compiled expression:
  14081. *
  14082. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14083. * are evaluated against (typically a scope object).
  14084. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14085. * `context`.
  14086. */
  14087. /**
  14088. * @ngdoc method
  14089. * @name $sce#parseAsCss
  14090. *
  14091. * @description
  14092. * Shorthand method. `$sce.parseAsCss(value)` →
  14093. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14094. *
  14095. * @param {string} expression String expression to compile.
  14096. * @returns {function(context, locals)} a function which represents the compiled expression:
  14097. *
  14098. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14099. * are evaluated against (typically a scope object).
  14100. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14101. * `context`.
  14102. */
  14103. /**
  14104. * @ngdoc method
  14105. * @name $sce#parseAsUrl
  14106. *
  14107. * @description
  14108. * Shorthand method. `$sce.parseAsUrl(value)` →
  14109. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14110. *
  14111. * @param {string} expression String expression to compile.
  14112. * @returns {function(context, locals)} a function which represents the compiled expression:
  14113. *
  14114. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14115. * are evaluated against (typically a scope object).
  14116. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14117. * `context`.
  14118. */
  14119. /**
  14120. * @ngdoc method
  14121. * @name $sce#parseAsResourceUrl
  14122. *
  14123. * @description
  14124. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14125. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14126. *
  14127. * @param {string} expression String expression to compile.
  14128. * @returns {function(context, locals)} a function which represents the compiled expression:
  14129. *
  14130. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14131. * are evaluated against (typically a scope object).
  14132. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14133. * `context`.
  14134. */
  14135. /**
  14136. * @ngdoc method
  14137. * @name $sce#parseAsJs
  14138. *
  14139. * @description
  14140. * Shorthand method. `$sce.parseAsJs(value)` →
  14141. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14142. *
  14143. * @param {string} expression String expression to compile.
  14144. * @returns {function(context, locals)} a function which represents the compiled expression:
  14145. *
  14146. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14147. * are evaluated against (typically a scope object).
  14148. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14149. * `context`.
  14150. */
  14151. // Shorthand delegations.
  14152. var parse = sce.parseAs,
  14153. getTrusted = sce.getTrusted,
  14154. trustAs = sce.trustAs;
  14155. forEach(SCE_CONTEXTS, function(enumValue, name) {
  14156. var lName = lowercase(name);
  14157. sce[camelCase("parse_as_" + lName)] = function(expr) {
  14158. return parse(enumValue, expr);
  14159. };
  14160. sce[camelCase("get_trusted_" + lName)] = function(value) {
  14161. return getTrusted(enumValue, value);
  14162. };
  14163. sce[camelCase("trust_as_" + lName)] = function(value) {
  14164. return trustAs(enumValue, value);
  14165. };
  14166. });
  14167. return sce;
  14168. }];
  14169. }
  14170. /**
  14171. * !!! This is an undocumented "private" service !!!
  14172. *
  14173. * @name $sniffer
  14174. * @requires $window
  14175. * @requires $document
  14176. *
  14177. * @property {boolean} history Does the browser support html5 history api ?
  14178. * @property {boolean} transitions Does the browser support CSS transition events ?
  14179. * @property {boolean} animations Does the browser support CSS animation events ?
  14180. *
  14181. * @description
  14182. * This is very simple implementation of testing browser's features.
  14183. */
  14184. function $SnifferProvider() {
  14185. this.$get = ['$window', '$document', function($window, $document) {
  14186. var eventSupport = {},
  14187. android =
  14188. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14189. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14190. document = $document[0] || {},
  14191. vendorPrefix,
  14192. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  14193. bodyStyle = document.body && document.body.style,
  14194. transitions = false,
  14195. animations = false,
  14196. match;
  14197. if (bodyStyle) {
  14198. for (var prop in bodyStyle) {
  14199. if (match = vendorRegex.exec(prop)) {
  14200. vendorPrefix = match[0];
  14201. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14202. break;
  14203. }
  14204. }
  14205. if (!vendorPrefix) {
  14206. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14207. }
  14208. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14209. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14210. if (android && (!transitions||!animations)) {
  14211. transitions = isString(document.body.style.webkitTransition);
  14212. animations = isString(document.body.style.webkitAnimation);
  14213. }
  14214. }
  14215. return {
  14216. // Android has history.pushState, but it does not update location correctly
  14217. // so let's not use the history API at all.
  14218. // http://code.google.com/p/android/issues/detail?id=17471
  14219. // https://github.com/angular/angular.js/issues/904
  14220. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14221. // so let's not use the history API also
  14222. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14223. // jshint -W018
  14224. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14225. // jshint +W018
  14226. hasEvent: function(event) {
  14227. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14228. // it. In particular the event is not fired when backspace or delete key are pressed or
  14229. // when cut operation is performed.
  14230. if (event == 'input' && msie == 9) return false;
  14231. if (isUndefined(eventSupport[event])) {
  14232. var divElm = document.createElement('div');
  14233. eventSupport[event] = 'on' + event in divElm;
  14234. }
  14235. return eventSupport[event];
  14236. },
  14237. csp: csp(),
  14238. vendorPrefix: vendorPrefix,
  14239. transitions: transitions,
  14240. animations: animations,
  14241. android: android
  14242. };
  14243. }];
  14244. }
  14245. var $compileMinErr = minErr('$compile');
  14246. /**
  14247. * @ngdoc service
  14248. * @name $templateRequest
  14249. *
  14250. * @description
  14251. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14252. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14253. * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted
  14254. * by setting the 2nd parameter of the function to true).
  14255. *
  14256. * @param {string} tpl The HTTP request template URL
  14257. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14258. *
  14259. * @return {Promise} the HTTP Promise for the given.
  14260. *
  14261. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14262. */
  14263. function $TemplateRequestProvider() {
  14264. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14265. function handleRequestFn(tpl, ignoreRequestError) {
  14266. var self = handleRequestFn;
  14267. self.totalPendingRequests++;
  14268. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  14269. if (isArray(transformResponse)) {
  14270. var original = transformResponse;
  14271. transformResponse = [];
  14272. for (var i=0; i<original.length; ++i) {
  14273. var transformer = original[i];
  14274. if (transformer !== defaultHttpResponseTransform) {
  14275. transformResponse.push(transformer);
  14276. }
  14277. }
  14278. } else if (transformResponse === defaultHttpResponseTransform) {
  14279. transformResponse = null;
  14280. }
  14281. var httpOptions = {
  14282. cache: $templateCache,
  14283. transformResponse: transformResponse
  14284. };
  14285. return $http.get(tpl, httpOptions)
  14286. .then(function(response) {
  14287. var html = response.data;
  14288. self.totalPendingRequests--;
  14289. $templateCache.put(tpl, html);
  14290. return html;
  14291. }, handleError);
  14292. function handleError() {
  14293. self.totalPendingRequests--;
  14294. if (!ignoreRequestError) {
  14295. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14296. }
  14297. return $q.reject();
  14298. }
  14299. }
  14300. handleRequestFn.totalPendingRequests = 0;
  14301. return handleRequestFn;
  14302. }];
  14303. }
  14304. function $$TestabilityProvider() {
  14305. this.$get = ['$rootScope', '$browser', '$location',
  14306. function($rootScope, $browser, $location) {
  14307. /**
  14308. * @name $testability
  14309. *
  14310. * @description
  14311. * The private $$testability service provides a collection of methods for use when debugging
  14312. * or by automated test and debugging tools.
  14313. */
  14314. var testability = {};
  14315. /**
  14316. * @name $$testability#findBindings
  14317. *
  14318. * @description
  14319. * Returns an array of elements that are bound (via ng-bind or {{}})
  14320. * to expressions matching the input.
  14321. *
  14322. * @param {Element} element The element root to search from.
  14323. * @param {string} expression The binding expression to match.
  14324. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14325. * for the expression. Filters and whitespace are ignored.
  14326. */
  14327. testability.findBindings = function(element, expression, opt_exactMatch) {
  14328. var bindings = element.getElementsByClassName('ng-binding');
  14329. var matches = [];
  14330. forEach(bindings, function(binding) {
  14331. var dataBinding = angular.element(binding).data('$binding');
  14332. if (dataBinding) {
  14333. forEach(dataBinding, function(bindingName) {
  14334. if (opt_exactMatch) {
  14335. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  14336. if (matcher.test(bindingName)) {
  14337. matches.push(binding);
  14338. }
  14339. } else {
  14340. if (bindingName.indexOf(expression) != -1) {
  14341. matches.push(binding);
  14342. }
  14343. }
  14344. });
  14345. }
  14346. });
  14347. return matches;
  14348. };
  14349. /**
  14350. * @name $$testability#findModels
  14351. *
  14352. * @description
  14353. * Returns an array of elements that are two-way found via ng-model to
  14354. * expressions matching the input.
  14355. *
  14356. * @param {Element} element The element root to search from.
  14357. * @param {string} expression The model expression to match.
  14358. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14359. * for the expression.
  14360. */
  14361. testability.findModels = function(element, expression, opt_exactMatch) {
  14362. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14363. for (var p = 0; p < prefixes.length; ++p) {
  14364. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14365. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14366. var elements = element.querySelectorAll(selector);
  14367. if (elements.length) {
  14368. return elements;
  14369. }
  14370. }
  14371. };
  14372. /**
  14373. * @name $$testability#getLocation
  14374. *
  14375. * @description
  14376. * Shortcut for getting the location in a browser agnostic way. Returns
  14377. * the path, search, and hash. (e.g. /path?a=b#hash)
  14378. */
  14379. testability.getLocation = function() {
  14380. return $location.url();
  14381. };
  14382. /**
  14383. * @name $$testability#setLocation
  14384. *
  14385. * @description
  14386. * Shortcut for navigating to a location without doing a full page reload.
  14387. *
  14388. * @param {string} url The location url (path, search and hash,
  14389. * e.g. /path?a=b#hash) to go to.
  14390. */
  14391. testability.setLocation = function(url) {
  14392. if (url !== $location.url()) {
  14393. $location.url(url);
  14394. $rootScope.$digest();
  14395. }
  14396. };
  14397. /**
  14398. * @name $$testability#whenStable
  14399. *
  14400. * @description
  14401. * Calls the callback when $timeout and $http requests are completed.
  14402. *
  14403. * @param {function} callback
  14404. */
  14405. testability.whenStable = function(callback) {
  14406. $browser.notifyWhenNoOutstandingRequests(callback);
  14407. };
  14408. return testability;
  14409. }];
  14410. }
  14411. function $TimeoutProvider() {
  14412. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14413. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14414. var deferreds = {};
  14415. /**
  14416. * @ngdoc service
  14417. * @name $timeout
  14418. *
  14419. * @description
  14420. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14421. * block and delegates any exceptions to
  14422. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14423. *
  14424. * The return value of registering a timeout function is a promise, which will be resolved when
  14425. * the timeout is reached and the timeout function is executed.
  14426. *
  14427. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14428. *
  14429. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14430. * synchronously flush the queue of deferred functions.
  14431. *
  14432. * @param {function()} fn A function, whose execution should be delayed.
  14433. * @param {number=} [delay=0] Delay in milliseconds.
  14434. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14435. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14436. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14437. * promise will be resolved with is the return value of the `fn` function.
  14438. *
  14439. */
  14440. function timeout(fn, delay, invokeApply) {
  14441. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14442. deferred = (skipApply ? $$q : $q).defer(),
  14443. promise = deferred.promise,
  14444. timeoutId;
  14445. timeoutId = $browser.defer(function() {
  14446. try {
  14447. deferred.resolve(fn());
  14448. } catch (e) {
  14449. deferred.reject(e);
  14450. $exceptionHandler(e);
  14451. }
  14452. finally {
  14453. delete deferreds[promise.$$timeoutId];
  14454. }
  14455. if (!skipApply) $rootScope.$apply();
  14456. }, delay);
  14457. promise.$$timeoutId = timeoutId;
  14458. deferreds[timeoutId] = deferred;
  14459. return promise;
  14460. }
  14461. /**
  14462. * @ngdoc method
  14463. * @name $timeout#cancel
  14464. *
  14465. * @description
  14466. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14467. * resolved with a rejection.
  14468. *
  14469. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14470. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14471. * canceled.
  14472. */
  14473. timeout.cancel = function(promise) {
  14474. if (promise && promise.$$timeoutId in deferreds) {
  14475. deferreds[promise.$$timeoutId].reject('canceled');
  14476. delete deferreds[promise.$$timeoutId];
  14477. return $browser.defer.cancel(promise.$$timeoutId);
  14478. }
  14479. return false;
  14480. };
  14481. return timeout;
  14482. }];
  14483. }
  14484. // NOTE: The usage of window and document instead of $window and $document here is
  14485. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14486. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14487. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14488. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14489. // exactly the behavior needed here. There is little value is mocking these out for this
  14490. // service.
  14491. var urlParsingNode = document.createElement("a");
  14492. var originUrl = urlResolve(window.location.href, true);
  14493. /**
  14494. *
  14495. * Implementation Notes for non-IE browsers
  14496. * ----------------------------------------
  14497. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14498. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14499. * URL will be resolved into an absolute URL in the context of the application document.
  14500. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14501. * properties are all populated to reflect the normalized URL. This approach has wide
  14502. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14503. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14504. *
  14505. * Implementation Notes for IE
  14506. * ---------------------------
  14507. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14508. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14509. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14510. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14511. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14512. * properties such as protocol, hostname, port, etc.
  14513. *
  14514. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14515. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14516. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14517. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14518. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14519. * method and IE < 8 is unsupported.
  14520. *
  14521. * References:
  14522. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14523. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14524. * http://url.spec.whatwg.org/#urlutils
  14525. * https://github.com/angular/angular.js/pull/2902
  14526. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14527. *
  14528. * @kind function
  14529. * @param {string} url The URL to be parsed.
  14530. * @description Normalizes and parses a URL.
  14531. * @returns {object} Returns the normalized URL as a dictionary.
  14532. *
  14533. * | member name | Description |
  14534. * |---------------|----------------|
  14535. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14536. * | protocol | The protocol including the trailing colon |
  14537. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14538. * | search | The search params, minus the question mark |
  14539. * | hash | The hash string, minus the hash symbol
  14540. * | hostname | The hostname
  14541. * | port | The port, without ":"
  14542. * | pathname | The pathname, beginning with "/"
  14543. *
  14544. */
  14545. function urlResolve(url, base) {
  14546. var href = url;
  14547. if (msie) {
  14548. // Normalize before parse. Refer Implementation Notes on why this is
  14549. // done in two steps on IE.
  14550. urlParsingNode.setAttribute("href", href);
  14551. href = urlParsingNode.href;
  14552. }
  14553. urlParsingNode.setAttribute('href', href);
  14554. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14555. return {
  14556. href: urlParsingNode.href,
  14557. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14558. host: urlParsingNode.host,
  14559. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14560. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14561. hostname: urlParsingNode.hostname,
  14562. port: urlParsingNode.port,
  14563. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14564. ? urlParsingNode.pathname
  14565. : '/' + urlParsingNode.pathname
  14566. };
  14567. }
  14568. /**
  14569. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14570. *
  14571. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14572. * or a parsed URL object.
  14573. * @returns {boolean} Whether the request is for the same origin as the application document.
  14574. */
  14575. function urlIsSameOrigin(requestUrl) {
  14576. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14577. return (parsed.protocol === originUrl.protocol &&
  14578. parsed.host === originUrl.host);
  14579. }
  14580. /**
  14581. * @ngdoc service
  14582. * @name $window
  14583. *
  14584. * @description
  14585. * A reference to the browser's `window` object. While `window`
  14586. * is globally available in JavaScript, it causes testability problems, because
  14587. * it is a global variable. In angular we always refer to it through the
  14588. * `$window` service, so it may be overridden, removed or mocked for testing.
  14589. *
  14590. * Expressions, like the one defined for the `ngClick` directive in the example
  14591. * below, are evaluated with respect to the current scope. Therefore, there is
  14592. * no risk of inadvertently coding in a dependency on a global value in such an
  14593. * expression.
  14594. *
  14595. * @example
  14596. <example module="windowExample">
  14597. <file name="index.html">
  14598. <script>
  14599. angular.module('windowExample', [])
  14600. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  14601. $scope.greeting = 'Hello, World!';
  14602. $scope.doGreeting = function(greeting) {
  14603. $window.alert(greeting);
  14604. };
  14605. }]);
  14606. </script>
  14607. <div ng-controller="ExampleController">
  14608. <input type="text" ng-model="greeting" />
  14609. <button ng-click="doGreeting(greeting)">ALERT</button>
  14610. </div>
  14611. </file>
  14612. <file name="protractor.js" type="protractor">
  14613. it('should display the greeting in the input box', function() {
  14614. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14615. // If we click the button it will block the test runner
  14616. // element(':button').click();
  14617. });
  14618. </file>
  14619. </example>
  14620. */
  14621. function $WindowProvider() {
  14622. this.$get = valueFn(window);
  14623. }
  14624. /* global currencyFilter: true,
  14625. dateFilter: true,
  14626. filterFilter: true,
  14627. jsonFilter: true,
  14628. limitToFilter: true,
  14629. lowercaseFilter: true,
  14630. numberFilter: true,
  14631. orderByFilter: true,
  14632. uppercaseFilter: true,
  14633. */
  14634. /**
  14635. * @ngdoc provider
  14636. * @name $filterProvider
  14637. * @description
  14638. *
  14639. * Filters are just functions which transform input to an output. However filters need to be
  14640. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14641. * annotated with dependencies and is responsible for creating a filter function.
  14642. *
  14643. * ```js
  14644. * // Filter registration
  14645. * function MyModule($provide, $filterProvider) {
  14646. * // create a service to demonstrate injection (not always needed)
  14647. * $provide.value('greet', function(name){
  14648. * return 'Hello ' + name + '!';
  14649. * });
  14650. *
  14651. * // register a filter factory which uses the
  14652. * // greet service to demonstrate DI.
  14653. * $filterProvider.register('greet', function(greet){
  14654. * // return the filter function which uses the greet service
  14655. * // to generate salutation
  14656. * return function(text) {
  14657. * // filters need to be forgiving so check input validity
  14658. * return text && greet(text) || text;
  14659. * };
  14660. * });
  14661. * }
  14662. * ```
  14663. *
  14664. * The filter function is registered with the `$injector` under the filter name suffix with
  14665. * `Filter`.
  14666. *
  14667. * ```js
  14668. * it('should be the same instance', inject(
  14669. * function($filterProvider) {
  14670. * $filterProvider.register('reverse', function(){
  14671. * return ...;
  14672. * });
  14673. * },
  14674. * function($filter, reverseFilter) {
  14675. * expect($filter('reverse')).toBe(reverseFilter);
  14676. * });
  14677. * ```
  14678. *
  14679. *
  14680. * For more information about how angular filters work, and how to create your own filters, see
  14681. * {@link guide/filter Filters} in the Angular Developer Guide.
  14682. */
  14683. /**
  14684. * @ngdoc service
  14685. * @name $filter
  14686. * @kind function
  14687. * @description
  14688. * Filters are used for formatting data displayed to the user.
  14689. *
  14690. * The general syntax in templates is as follows:
  14691. *
  14692. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14693. *
  14694. * @param {String} name Name of the filter function to retrieve
  14695. * @return {Function} the filter function
  14696. * @example
  14697. <example name="$filter" module="filterExample">
  14698. <file name="index.html">
  14699. <div ng-controller="MainCtrl">
  14700. <h3>{{ originalText }}</h3>
  14701. <h3>{{ filteredText }}</h3>
  14702. </div>
  14703. </file>
  14704. <file name="script.js">
  14705. angular.module('filterExample', [])
  14706. .controller('MainCtrl', function($scope, $filter) {
  14707. $scope.originalText = 'hello';
  14708. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14709. });
  14710. </file>
  14711. </example>
  14712. */
  14713. $FilterProvider.$inject = ['$provide'];
  14714. function $FilterProvider($provide) {
  14715. var suffix = 'Filter';
  14716. /**
  14717. * @ngdoc method
  14718. * @name $filterProvider#register
  14719. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14720. * the keys are the filter names and the values are the filter factories.
  14721. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14722. * of the registered filter instances.
  14723. */
  14724. function register(name, factory) {
  14725. if (isObject(name)) {
  14726. var filters = {};
  14727. forEach(name, function(filter, key) {
  14728. filters[key] = register(key, filter);
  14729. });
  14730. return filters;
  14731. } else {
  14732. return $provide.factory(name + suffix, factory);
  14733. }
  14734. }
  14735. this.register = register;
  14736. this.$get = ['$injector', function($injector) {
  14737. return function(name) {
  14738. return $injector.get(name + suffix);
  14739. };
  14740. }];
  14741. ////////////////////////////////////////
  14742. /* global
  14743. currencyFilter: false,
  14744. dateFilter: false,
  14745. filterFilter: false,
  14746. jsonFilter: false,
  14747. limitToFilter: false,
  14748. lowercaseFilter: false,
  14749. numberFilter: false,
  14750. orderByFilter: false,
  14751. uppercaseFilter: false,
  14752. */
  14753. register('currency', currencyFilter);
  14754. register('date', dateFilter);
  14755. register('filter', filterFilter);
  14756. register('json', jsonFilter);
  14757. register('limitTo', limitToFilter);
  14758. register('lowercase', lowercaseFilter);
  14759. register('number', numberFilter);
  14760. register('orderBy', orderByFilter);
  14761. register('uppercase', uppercaseFilter);
  14762. }
  14763. /**
  14764. * @ngdoc filter
  14765. * @name filter
  14766. * @kind function
  14767. *
  14768. * @description
  14769. * Selects a subset of items from `array` and returns it as a new array.
  14770. *
  14771. * @param {Array} array The source array.
  14772. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  14773. * `array`.
  14774. *
  14775. * Can be one of:
  14776. *
  14777. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  14778. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  14779. * will be returned. The predicate can be negated by prefixing the string with `!`.
  14780. *
  14781. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  14782. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  14783. * which have property `name` containing "M" and property `phone` containing "1". A special
  14784. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  14785. * property of the object. That's equivalent to the simple substring match with a `string`
  14786. * as described above. The predicate can be negated by prefixing the string with `!`.
  14787. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  14788. * not containing "M".
  14789. *
  14790. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  14791. * function is called for each element of `array`. The final result is an array of those
  14792. * elements that the predicate returned true for.
  14793. *
  14794. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  14795. * determining if the expected value (from the filter expression) and actual value (from
  14796. * the object in the array) should be considered a match.
  14797. *
  14798. * Can be one of:
  14799. *
  14800. * - `function(actual, expected)`:
  14801. * The function will be given the object value and the predicate value to compare and
  14802. * should return true if the item should be included in filtered result.
  14803. *
  14804. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  14805. * this is essentially strict comparison of expected and actual.
  14806. *
  14807. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  14808. * insensitive way.
  14809. *
  14810. * @example
  14811. <example>
  14812. <file name="index.html">
  14813. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  14814. {name:'Mary', phone:'800-BIG-MARY'},
  14815. {name:'Mike', phone:'555-4321'},
  14816. {name:'Adam', phone:'555-5678'},
  14817. {name:'Julie', phone:'555-8765'},
  14818. {name:'Juliette', phone:'555-5678'}]"></div>
  14819. Search: <input ng-model="searchText">
  14820. <table id="searchTextResults">
  14821. <tr><th>Name</th><th>Phone</th></tr>
  14822. <tr ng-repeat="friend in friends | filter:searchText">
  14823. <td>{{friend.name}}</td>
  14824. <td>{{friend.phone}}</td>
  14825. </tr>
  14826. </table>
  14827. <hr>
  14828. Any: <input ng-model="search.$"> <br>
  14829. Name only <input ng-model="search.name"><br>
  14830. Phone only <input ng-model="search.phone"><br>
  14831. Equality <input type="checkbox" ng-model="strict"><br>
  14832. <table id="searchObjResults">
  14833. <tr><th>Name</th><th>Phone</th></tr>
  14834. <tr ng-repeat="friendObj in friends | filter:search:strict">
  14835. <td>{{friendObj.name}}</td>
  14836. <td>{{friendObj.phone}}</td>
  14837. </tr>
  14838. </table>
  14839. </file>
  14840. <file name="protractor.js" type="protractor">
  14841. var expectFriendNames = function(expectedNames, key) {
  14842. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  14843. arr.forEach(function(wd, i) {
  14844. expect(wd.getText()).toMatch(expectedNames[i]);
  14845. });
  14846. });
  14847. };
  14848. it('should search across all fields when filtering with a string', function() {
  14849. var searchText = element(by.model('searchText'));
  14850. searchText.clear();
  14851. searchText.sendKeys('m');
  14852. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  14853. searchText.clear();
  14854. searchText.sendKeys('76');
  14855. expectFriendNames(['John', 'Julie'], 'friend');
  14856. });
  14857. it('should search in specific fields when filtering with a predicate object', function() {
  14858. var searchAny = element(by.model('search.$'));
  14859. searchAny.clear();
  14860. searchAny.sendKeys('i');
  14861. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  14862. });
  14863. it('should use a equal comparison when comparator is true', function() {
  14864. var searchName = element(by.model('search.name'));
  14865. var strict = element(by.model('strict'));
  14866. searchName.clear();
  14867. searchName.sendKeys('Julie');
  14868. strict.click();
  14869. expectFriendNames(['Julie'], 'friendObj');
  14870. });
  14871. </file>
  14872. </example>
  14873. */
  14874. function filterFilter() {
  14875. return function(array, expression, comparator) {
  14876. if (!isArray(array)) return array;
  14877. var comparatorType = typeof(comparator),
  14878. predicates = [];
  14879. predicates.check = function(value, index) {
  14880. for (var j = 0; j < predicates.length; j++) {
  14881. if (!predicates[j](value, index)) {
  14882. return false;
  14883. }
  14884. }
  14885. return true;
  14886. };
  14887. if (comparatorType !== 'function') {
  14888. if (comparatorType === 'boolean' && comparator) {
  14889. comparator = function(obj, text) {
  14890. return angular.equals(obj, text);
  14891. };
  14892. } else {
  14893. comparator = function(obj, text) {
  14894. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  14895. for (var objKey in obj) {
  14896. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  14897. comparator(obj[objKey], text[objKey])) {
  14898. return true;
  14899. }
  14900. }
  14901. return false;
  14902. }
  14903. text = (''+text).toLowerCase();
  14904. return (''+obj).toLowerCase().indexOf(text) > -1;
  14905. };
  14906. }
  14907. }
  14908. var search = function(obj, text) {
  14909. if (typeof text === 'string' && text.charAt(0) === '!') {
  14910. return !search(obj, text.substr(1));
  14911. }
  14912. switch (typeof obj) {
  14913. case 'boolean':
  14914. case 'number':
  14915. case 'string':
  14916. return comparator(obj, text);
  14917. case 'object':
  14918. switch (typeof text) {
  14919. case 'object':
  14920. return comparator(obj, text);
  14921. default:
  14922. for (var objKey in obj) {
  14923. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  14924. return true;
  14925. }
  14926. }
  14927. break;
  14928. }
  14929. return false;
  14930. case 'array':
  14931. for (var i = 0; i < obj.length; i++) {
  14932. if (search(obj[i], text)) {
  14933. return true;
  14934. }
  14935. }
  14936. return false;
  14937. default:
  14938. return false;
  14939. }
  14940. };
  14941. switch (typeof expression) {
  14942. case 'boolean':
  14943. case 'number':
  14944. case 'string':
  14945. // Set up expression object and fall through
  14946. expression = {$:expression};
  14947. // jshint -W086
  14948. case 'object':
  14949. // jshint +W086
  14950. for (var key in expression) {
  14951. (function(path) {
  14952. if (typeof expression[path] === 'undefined') return;
  14953. predicates.push(function(value) {
  14954. return search(path == '$' ? value : (value && value[path]), expression[path]);
  14955. });
  14956. })(key);
  14957. }
  14958. break;
  14959. case 'function':
  14960. predicates.push(expression);
  14961. break;
  14962. default:
  14963. return array;
  14964. }
  14965. var filtered = [];
  14966. for (var j = 0; j < array.length; j++) {
  14967. var value = array[j];
  14968. if (predicates.check(value, j)) {
  14969. filtered.push(value);
  14970. }
  14971. }
  14972. return filtered;
  14973. };
  14974. }
  14975. /**
  14976. * @ngdoc filter
  14977. * @name currency
  14978. * @kind function
  14979. *
  14980. * @description
  14981. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  14982. * symbol for current locale is used.
  14983. *
  14984. * @param {number} amount Input to filter.
  14985. * @param {string=} symbol Currency symbol or identifier to be displayed.
  14986. * @param {number=} fractionSize Number of decimal places to round the amount to.
  14987. * @returns {string} Formatted number.
  14988. *
  14989. *
  14990. * @example
  14991. <example module="currencyExample">
  14992. <file name="index.html">
  14993. <script>
  14994. angular.module('currencyExample', [])
  14995. .controller('ExampleController', ['$scope', function($scope) {
  14996. $scope.amount = 1234.56;
  14997. }]);
  14998. </script>
  14999. <div ng-controller="ExampleController">
  15000. <input type="number" ng-model="amount"> <br>
  15001. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  15002. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  15003. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  15004. </div>
  15005. </file>
  15006. <file name="protractor.js" type="protractor">
  15007. it('should init with 1234.56', function() {
  15008. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  15009. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  15010. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  15011. });
  15012. it('should update', function() {
  15013. if (browser.params.browser == 'safari') {
  15014. // Safari does not understand the minus key. See
  15015. // https://github.com/angular/protractor/issues/481
  15016. return;
  15017. }
  15018. element(by.model('amount')).clear();
  15019. element(by.model('amount')).sendKeys('-1234');
  15020. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  15021. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  15022. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  15023. });
  15024. </file>
  15025. </example>
  15026. */
  15027. currencyFilter.$inject = ['$locale'];
  15028. function currencyFilter($locale) {
  15029. var formats = $locale.NUMBER_FORMATS;
  15030. return function(amount, currencySymbol, fractionSize) {
  15031. if (isUndefined(currencySymbol)) {
  15032. currencySymbol = formats.CURRENCY_SYM;
  15033. }
  15034. if (isUndefined(fractionSize)) {
  15035. // TODO: read the default value from the locale file
  15036. fractionSize = 2;
  15037. }
  15038. // if null or undefined pass it through
  15039. return (amount == null)
  15040. ? amount
  15041. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  15042. replace(/\u00A4/g, currencySymbol);
  15043. };
  15044. }
  15045. /**
  15046. * @ngdoc filter
  15047. * @name number
  15048. * @kind function
  15049. *
  15050. * @description
  15051. * Formats a number as text.
  15052. *
  15053. * If the input is not a number an empty string is returned.
  15054. *
  15055. * @param {number|string} number Number to format.
  15056. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  15057. * If this is not provided then the fraction size is computed from the current locale's number
  15058. * formatting pattern. In the case of the default locale, it will be 3.
  15059. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  15060. *
  15061. * @example
  15062. <example module="numberFilterExample">
  15063. <file name="index.html">
  15064. <script>
  15065. angular.module('numberFilterExample', [])
  15066. .controller('ExampleController', ['$scope', function($scope) {
  15067. $scope.val = 1234.56789;
  15068. }]);
  15069. </script>
  15070. <div ng-controller="ExampleController">
  15071. Enter number: <input ng-model='val'><br>
  15072. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  15073. No fractions: <span>{{val | number:0}}</span><br>
  15074. Negative number: <span>{{-val | number:4}}</span>
  15075. </div>
  15076. </file>
  15077. <file name="protractor.js" type="protractor">
  15078. it('should format numbers', function() {
  15079. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  15080. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  15081. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  15082. });
  15083. it('should update', function() {
  15084. element(by.model('val')).clear();
  15085. element(by.model('val')).sendKeys('3374.333');
  15086. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15087. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15088. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15089. });
  15090. </file>
  15091. </example>
  15092. */
  15093. numberFilter.$inject = ['$locale'];
  15094. function numberFilter($locale) {
  15095. var formats = $locale.NUMBER_FORMATS;
  15096. return function(number, fractionSize) {
  15097. // if null or undefined pass it through
  15098. return (number == null)
  15099. ? number
  15100. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15101. fractionSize);
  15102. };
  15103. }
  15104. var DECIMAL_SEP = '.';
  15105. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15106. if (!isFinite(number) || isObject(number)) return '';
  15107. var isNegative = number < 0;
  15108. number = Math.abs(number);
  15109. var numStr = number + '',
  15110. formatedText = '',
  15111. parts = [];
  15112. var hasExponent = false;
  15113. if (numStr.indexOf('e') !== -1) {
  15114. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15115. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15116. numStr = '0';
  15117. number = 0;
  15118. } else {
  15119. formatedText = numStr;
  15120. hasExponent = true;
  15121. }
  15122. }
  15123. if (!hasExponent) {
  15124. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15125. // determine fractionSize if it is not specified
  15126. if (isUndefined(fractionSize)) {
  15127. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15128. }
  15129. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15130. // inspired by:
  15131. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15132. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15133. if (number === 0) {
  15134. isNegative = false;
  15135. }
  15136. var fraction = ('' + number).split(DECIMAL_SEP);
  15137. var whole = fraction[0];
  15138. fraction = fraction[1] || '';
  15139. var i, pos = 0,
  15140. lgroup = pattern.lgSize,
  15141. group = pattern.gSize;
  15142. if (whole.length >= (lgroup + group)) {
  15143. pos = whole.length - lgroup;
  15144. for (i = 0; i < pos; i++) {
  15145. if ((pos - i)%group === 0 && i !== 0) {
  15146. formatedText += groupSep;
  15147. }
  15148. formatedText += whole.charAt(i);
  15149. }
  15150. }
  15151. for (i = pos; i < whole.length; i++) {
  15152. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  15153. formatedText += groupSep;
  15154. }
  15155. formatedText += whole.charAt(i);
  15156. }
  15157. // format fraction part.
  15158. while (fraction.length < fractionSize) {
  15159. fraction += '0';
  15160. }
  15161. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15162. } else {
  15163. if (fractionSize > 0 && number > -1 && number < 1) {
  15164. formatedText = number.toFixed(fractionSize);
  15165. }
  15166. }
  15167. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  15168. parts.push(formatedText);
  15169. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  15170. return parts.join('');
  15171. }
  15172. function padNumber(num, digits, trim) {
  15173. var neg = '';
  15174. if (num < 0) {
  15175. neg = '-';
  15176. num = -num;
  15177. }
  15178. num = '' + num;
  15179. while (num.length < digits) num = '0' + num;
  15180. if (trim)
  15181. num = num.substr(num.length - digits);
  15182. return neg + num;
  15183. }
  15184. function dateGetter(name, size, offset, trim) {
  15185. offset = offset || 0;
  15186. return function(date) {
  15187. var value = date['get' + name]();
  15188. if (offset > 0 || value > -offset)
  15189. value += offset;
  15190. if (value === 0 && offset == -12) value = 12;
  15191. return padNumber(value, size, trim);
  15192. };
  15193. }
  15194. function dateStrGetter(name, shortForm) {
  15195. return function(date, formats) {
  15196. var value = date['get' + name]();
  15197. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15198. return formats[get][value];
  15199. };
  15200. }
  15201. function timeZoneGetter(date) {
  15202. var zone = -1 * date.getTimezoneOffset();
  15203. var paddedZone = (zone >= 0) ? "+" : "";
  15204. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15205. padNumber(Math.abs(zone % 60), 2);
  15206. return paddedZone;
  15207. }
  15208. function getFirstThursdayOfYear(year) {
  15209. // 0 = index of January
  15210. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15211. // 4 = index of Thursday (+1 to account for 1st = 5)
  15212. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15213. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15214. }
  15215. function getThursdayThisWeek(datetime) {
  15216. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15217. // 4 = index of Thursday
  15218. datetime.getDate() + (4 - datetime.getDay()));
  15219. }
  15220. function weekGetter(size) {
  15221. return function(date) {
  15222. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15223. thisThurs = getThursdayThisWeek(date);
  15224. var diff = +thisThurs - +firstThurs,
  15225. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15226. return padNumber(result, size);
  15227. };
  15228. }
  15229. function ampmGetter(date, formats) {
  15230. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15231. }
  15232. var DATE_FORMATS = {
  15233. yyyy: dateGetter('FullYear', 4),
  15234. yy: dateGetter('FullYear', 2, 0, true),
  15235. y: dateGetter('FullYear', 1),
  15236. MMMM: dateStrGetter('Month'),
  15237. MMM: dateStrGetter('Month', true),
  15238. MM: dateGetter('Month', 2, 1),
  15239. M: dateGetter('Month', 1, 1),
  15240. dd: dateGetter('Date', 2),
  15241. d: dateGetter('Date', 1),
  15242. HH: dateGetter('Hours', 2),
  15243. H: dateGetter('Hours', 1),
  15244. hh: dateGetter('Hours', 2, -12),
  15245. h: dateGetter('Hours', 1, -12),
  15246. mm: dateGetter('Minutes', 2),
  15247. m: dateGetter('Minutes', 1),
  15248. ss: dateGetter('Seconds', 2),
  15249. s: dateGetter('Seconds', 1),
  15250. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15251. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15252. sss: dateGetter('Milliseconds', 3),
  15253. EEEE: dateStrGetter('Day'),
  15254. EEE: dateStrGetter('Day', true),
  15255. a: ampmGetter,
  15256. Z: timeZoneGetter,
  15257. ww: weekGetter(2),
  15258. w: weekGetter(1)
  15259. };
  15260. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
  15261. NUMBER_STRING = /^\-?\d+$/;
  15262. /**
  15263. * @ngdoc filter
  15264. * @name date
  15265. * @kind function
  15266. *
  15267. * @description
  15268. * Formats `date` to a string based on the requested `format`.
  15269. *
  15270. * `format` string can be composed of the following elements:
  15271. *
  15272. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15273. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15274. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15275. * * `'MMMM'`: Month in year (January-December)
  15276. * * `'MMM'`: Month in year (Jan-Dec)
  15277. * * `'MM'`: Month in year, padded (01-12)
  15278. * * `'M'`: Month in year (1-12)
  15279. * * `'dd'`: Day in month, padded (01-31)
  15280. * * `'d'`: Day in month (1-31)
  15281. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15282. * * `'EEE'`: Day in Week, (Sun-Sat)
  15283. * * `'HH'`: Hour in day, padded (00-23)
  15284. * * `'H'`: Hour in day (0-23)
  15285. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15286. * * `'h'`: Hour in AM/PM, (1-12)
  15287. * * `'mm'`: Minute in hour, padded (00-59)
  15288. * * `'m'`: Minute in hour (0-59)
  15289. * * `'ss'`: Second in minute, padded (00-59)
  15290. * * `'s'`: Second in minute (0-59)
  15291. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  15292. * * `'a'`: AM/PM marker
  15293. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15294. * * `'ww'`: ISO-8601 week of year (00-53)
  15295. * * `'w'`: ISO-8601 week of year (0-53)
  15296. *
  15297. * `format` string can also be one of the following predefined
  15298. * {@link guide/i18n localizable formats}:
  15299. *
  15300. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15301. * (e.g. Sep 3, 2010 12:05:08 PM)
  15302. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15303. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15304. * (e.g. Friday, September 3, 2010)
  15305. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15306. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15307. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15308. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15309. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15310. *
  15311. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15312. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15313. * (e.g. `"h 'o''clock'"`).
  15314. *
  15315. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15316. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15317. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15318. * specified in the string input, the time is considered to be in the local timezone.
  15319. * @param {string=} format Formatting rules (see Description). If not specified,
  15320. * `mediumDate` is used.
  15321. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15322. * If not specified, the timezone of the browser will be used.
  15323. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15324. *
  15325. * @example
  15326. <example>
  15327. <file name="index.html">
  15328. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15329. <span>{{1288323623006 | date:'medium'}}</span><br>
  15330. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15331. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15332. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15333. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15334. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15335. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15336. </file>
  15337. <file name="protractor.js" type="protractor">
  15338. it('should format date', function() {
  15339. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15340. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15341. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15342. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15343. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15344. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15345. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15346. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15347. });
  15348. </file>
  15349. </example>
  15350. */
  15351. dateFilter.$inject = ['$locale'];
  15352. function dateFilter($locale) {
  15353. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15354. // 1 2 3 4 5 6 7 8 9 10 11
  15355. function jsonStringToDate(string) {
  15356. var match;
  15357. if (match = string.match(R_ISO8601_STR)) {
  15358. var date = new Date(0),
  15359. tzHour = 0,
  15360. tzMin = 0,
  15361. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15362. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15363. if (match[9]) {
  15364. tzHour = int(match[9] + match[10]);
  15365. tzMin = int(match[9] + match[11]);
  15366. }
  15367. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15368. var h = int(match[4]||0) - tzHour;
  15369. var m = int(match[5]||0) - tzMin;
  15370. var s = int(match[6]||0);
  15371. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  15372. timeSetter.call(date, h, m, s, ms);
  15373. return date;
  15374. }
  15375. return string;
  15376. }
  15377. return function(date, format, timezone) {
  15378. var text = '',
  15379. parts = [],
  15380. fn, match;
  15381. format = format || 'mediumDate';
  15382. format = $locale.DATETIME_FORMATS[format] || format;
  15383. if (isString(date)) {
  15384. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15385. }
  15386. if (isNumber(date)) {
  15387. date = new Date(date);
  15388. }
  15389. if (!isDate(date)) {
  15390. return date;
  15391. }
  15392. while (format) {
  15393. match = DATE_FORMATS_SPLIT.exec(format);
  15394. if (match) {
  15395. parts = concat(parts, match, 1);
  15396. format = parts.pop();
  15397. } else {
  15398. parts.push(format);
  15399. format = null;
  15400. }
  15401. }
  15402. if (timezone && timezone === 'UTC') {
  15403. date = new Date(date.getTime());
  15404. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15405. }
  15406. forEach(parts, function(value) {
  15407. fn = DATE_FORMATS[value];
  15408. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15409. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15410. });
  15411. return text;
  15412. };
  15413. }
  15414. /**
  15415. * @ngdoc filter
  15416. * @name json
  15417. * @kind function
  15418. *
  15419. * @description
  15420. * Allows you to convert a JavaScript object into JSON string.
  15421. *
  15422. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15423. * the binding is automatically converted to JSON.
  15424. *
  15425. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15426. * @returns {string} JSON string.
  15427. *
  15428. *
  15429. * @example
  15430. <example>
  15431. <file name="index.html">
  15432. <pre>{{ {'name':'value'} | json }}</pre>
  15433. </file>
  15434. <file name="protractor.js" type="protractor">
  15435. it('should jsonify filtered objects', function() {
  15436. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15437. });
  15438. </file>
  15439. </example>
  15440. *
  15441. */
  15442. function jsonFilter() {
  15443. return function(object) {
  15444. return toJson(object, true);
  15445. };
  15446. }
  15447. /**
  15448. * @ngdoc filter
  15449. * @name lowercase
  15450. * @kind function
  15451. * @description
  15452. * Converts string to lowercase.
  15453. * @see angular.lowercase
  15454. */
  15455. var lowercaseFilter = valueFn(lowercase);
  15456. /**
  15457. * @ngdoc filter
  15458. * @name uppercase
  15459. * @kind function
  15460. * @description
  15461. * Converts string to uppercase.
  15462. * @see angular.uppercase
  15463. */
  15464. var uppercaseFilter = valueFn(uppercase);
  15465. /**
  15466. * @ngdoc filter
  15467. * @name limitTo
  15468. * @kind function
  15469. *
  15470. * @description
  15471. * Creates a new array or string containing only a specified number of elements. The elements
  15472. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15473. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15474. * converted to a string.
  15475. *
  15476. * @param {Array|string|number} input Source array, string or number to be limited.
  15477. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15478. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15479. * If the number is negative, `limit` number of items from the end of the source array/string
  15480. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15481. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15482. * had less than `limit` elements.
  15483. *
  15484. * @example
  15485. <example module="limitToExample">
  15486. <file name="index.html">
  15487. <script>
  15488. angular.module('limitToExample', [])
  15489. .controller('ExampleController', ['$scope', function($scope) {
  15490. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15491. $scope.letters = "abcdefghi";
  15492. $scope.longNumber = 2345432342;
  15493. $scope.numLimit = 3;
  15494. $scope.letterLimit = 3;
  15495. $scope.longNumberLimit = 3;
  15496. }]);
  15497. </script>
  15498. <div ng-controller="ExampleController">
  15499. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15500. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15501. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15502. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15503. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15504. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15505. </div>
  15506. </file>
  15507. <file name="protractor.js" type="protractor">
  15508. var numLimitInput = element(by.model('numLimit'));
  15509. var letterLimitInput = element(by.model('letterLimit'));
  15510. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15511. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15512. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15513. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15514. it('should limit the number array to first three items', function() {
  15515. expect(numLimitInput.getAttribute('value')).toBe('3');
  15516. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15517. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15518. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15519. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15520. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15521. });
  15522. // There is a bug in safari and protractor that doesn't like the minus key
  15523. // it('should update the output when -3 is entered', function() {
  15524. // numLimitInput.clear();
  15525. // numLimitInput.sendKeys('-3');
  15526. // letterLimitInput.clear();
  15527. // letterLimitInput.sendKeys('-3');
  15528. // longNumberLimitInput.clear();
  15529. // longNumberLimitInput.sendKeys('-3');
  15530. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15531. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15532. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15533. // });
  15534. it('should not exceed the maximum size of input array', function() {
  15535. numLimitInput.clear();
  15536. numLimitInput.sendKeys('100');
  15537. letterLimitInput.clear();
  15538. letterLimitInput.sendKeys('100');
  15539. longNumberLimitInput.clear();
  15540. longNumberLimitInput.sendKeys('100');
  15541. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15542. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15543. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15544. });
  15545. </file>
  15546. </example>
  15547. */
  15548. function limitToFilter() {
  15549. return function(input, limit) {
  15550. if (isNumber(input)) input = input.toString();
  15551. if (!isArray(input) && !isString(input)) return input;
  15552. if (Math.abs(Number(limit)) === Infinity) {
  15553. limit = Number(limit);
  15554. } else {
  15555. limit = int(limit);
  15556. }
  15557. if (isString(input)) {
  15558. //NaN check on limit
  15559. if (limit) {
  15560. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  15561. } else {
  15562. return "";
  15563. }
  15564. }
  15565. var out = [],
  15566. i, n;
  15567. // if abs(limit) exceeds maximum length, trim it
  15568. if (limit > input.length)
  15569. limit = input.length;
  15570. else if (limit < -input.length)
  15571. limit = -input.length;
  15572. if (limit > 0) {
  15573. i = 0;
  15574. n = limit;
  15575. } else {
  15576. i = input.length + limit;
  15577. n = input.length;
  15578. }
  15579. for (; i<n; i++) {
  15580. out.push(input[i]);
  15581. }
  15582. return out;
  15583. };
  15584. }
  15585. /**
  15586. * @ngdoc filter
  15587. * @name orderBy
  15588. * @kind function
  15589. *
  15590. * @description
  15591. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15592. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15593. * correctly, make sure they are actually being saved as numbers and not strings.
  15594. *
  15595. * @param {Array} array The array to sort.
  15596. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15597. * used by the comparator to determine the order of elements.
  15598. *
  15599. * Can be one of:
  15600. *
  15601. * - `function`: Getter function. The result of this function will be sorted using the
  15602. * `<`, `=`, `>` operator.
  15603. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15604. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15605. * 3 first characters of a property called `name`). The result of a constant expression
  15606. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15607. * to sort object by the value of their `special name` property). An expression can be
  15608. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15609. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15610. * element itself is used to compare where sorting.
  15611. * - `Array`: An array of function or string predicates. The first predicate in the array
  15612. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15613. *
  15614. * If the predicate is missing or empty then it defaults to `'+'`.
  15615. *
  15616. * @param {boolean=} reverse Reverse the order of the array.
  15617. * @returns {Array} Sorted copy of the source array.
  15618. *
  15619. * @example
  15620. <example module="orderByExample">
  15621. <file name="index.html">
  15622. <script>
  15623. angular.module('orderByExample', [])
  15624. .controller('ExampleController', ['$scope', function($scope) {
  15625. $scope.friends =
  15626. [{name:'John', phone:'555-1212', age:10},
  15627. {name:'Mary', phone:'555-9876', age:19},
  15628. {name:'Mike', phone:'555-4321', age:21},
  15629. {name:'Adam', phone:'555-5678', age:35},
  15630. {name:'Julie', phone:'555-8765', age:29}];
  15631. $scope.predicate = '-age';
  15632. }]);
  15633. </script>
  15634. <div ng-controller="ExampleController">
  15635. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15636. <hr/>
  15637. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15638. <table class="friend">
  15639. <tr>
  15640. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15641. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15642. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15643. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15644. </tr>
  15645. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15646. <td>{{friend.name}}</td>
  15647. <td>{{friend.phone}}</td>
  15648. <td>{{friend.age}}</td>
  15649. </tr>
  15650. </table>
  15651. </div>
  15652. </file>
  15653. </example>
  15654. *
  15655. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15656. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15657. * desired parameters.
  15658. *
  15659. * Example:
  15660. *
  15661. * @example
  15662. <example module="orderByExample">
  15663. <file name="index.html">
  15664. <div ng-controller="ExampleController">
  15665. <table class="friend">
  15666. <tr>
  15667. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15668. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15669. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15670. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15671. </tr>
  15672. <tr ng-repeat="friend in friends">
  15673. <td>{{friend.name}}</td>
  15674. <td>{{friend.phone}}</td>
  15675. <td>{{friend.age}}</td>
  15676. </tr>
  15677. </table>
  15678. </div>
  15679. </file>
  15680. <file name="script.js">
  15681. angular.module('orderByExample', [])
  15682. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15683. var orderBy = $filter('orderBy');
  15684. $scope.friends = [
  15685. { name: 'John', phone: '555-1212', age: 10 },
  15686. { name: 'Mary', phone: '555-9876', age: 19 },
  15687. { name: 'Mike', phone: '555-4321', age: 21 },
  15688. { name: 'Adam', phone: '555-5678', age: 35 },
  15689. { name: 'Julie', phone: '555-8765', age: 29 }
  15690. ];
  15691. $scope.order = function(predicate, reverse) {
  15692. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15693. };
  15694. $scope.order('-age',false);
  15695. }]);
  15696. </file>
  15697. </example>
  15698. */
  15699. orderByFilter.$inject = ['$parse'];
  15700. function orderByFilter($parse) {
  15701. return function(array, sortPredicate, reverseOrder) {
  15702. if (!(isArrayLike(array))) return array;
  15703. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  15704. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15705. sortPredicate = sortPredicate.map(function(predicate) {
  15706. var descending = false, get = predicate || identity;
  15707. if (isString(predicate)) {
  15708. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15709. descending = predicate.charAt(0) == '-';
  15710. predicate = predicate.substring(1);
  15711. }
  15712. if (predicate === '') {
  15713. // Effectively no predicate was passed so we compare identity
  15714. return reverseComparator(function(a, b) {
  15715. return compare(a, b);
  15716. }, descending);
  15717. }
  15718. get = $parse(predicate);
  15719. if (get.constant) {
  15720. var key = get();
  15721. return reverseComparator(function(a, b) {
  15722. return compare(a[key], b[key]);
  15723. }, descending);
  15724. }
  15725. }
  15726. return reverseComparator(function(a, b) {
  15727. return compare(get(a),get(b));
  15728. }, descending);
  15729. });
  15730. var arrayCopy = [];
  15731. for (var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  15732. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  15733. function comparator(o1, o2) {
  15734. for (var i = 0; i < sortPredicate.length; i++) {
  15735. var comp = sortPredicate[i](o1, o2);
  15736. if (comp !== 0) return comp;
  15737. }
  15738. return 0;
  15739. }
  15740. function reverseComparator(comp, descending) {
  15741. return descending
  15742. ? function(a, b) {return comp(b,a);}
  15743. : comp;
  15744. }
  15745. function compare(v1, v2) {
  15746. var t1 = typeof v1;
  15747. var t2 = typeof v2;
  15748. if (t1 == t2) {
  15749. if (isDate(v1) && isDate(v2)) {
  15750. v1 = v1.valueOf();
  15751. v2 = v2.valueOf();
  15752. }
  15753. if (t1 == "string") {
  15754. v1 = v1.toLowerCase();
  15755. v2 = v2.toLowerCase();
  15756. }
  15757. if (v1 === v2) return 0;
  15758. return v1 < v2 ? -1 : 1;
  15759. } else {
  15760. return t1 < t2 ? -1 : 1;
  15761. }
  15762. }
  15763. };
  15764. }
  15765. function ngDirective(directive) {
  15766. if (isFunction(directive)) {
  15767. directive = {
  15768. link: directive
  15769. };
  15770. }
  15771. directive.restrict = directive.restrict || 'AC';
  15772. return valueFn(directive);
  15773. }
  15774. /**
  15775. * @ngdoc directive
  15776. * @name a
  15777. * @restrict E
  15778. *
  15779. * @description
  15780. * Modifies the default behavior of the html A tag so that the default action is prevented when
  15781. * the href attribute is empty.
  15782. *
  15783. * This change permits the easy creation of action links with the `ngClick` directive
  15784. * without changing the location or causing page reloads, e.g.:
  15785. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  15786. */
  15787. var htmlAnchorDirective = valueFn({
  15788. restrict: 'E',
  15789. compile: function(element, attr) {
  15790. if (!attr.href && !attr.xlinkHref && !attr.name) {
  15791. return function(scope, element) {
  15792. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  15793. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  15794. 'xlink:href' : 'href';
  15795. element.on('click', function(event) {
  15796. // if we have no href url, then don't navigate anywhere.
  15797. if (!element.attr(href)) {
  15798. event.preventDefault();
  15799. }
  15800. });
  15801. };
  15802. }
  15803. }
  15804. });
  15805. /**
  15806. * @ngdoc directive
  15807. * @name ngHref
  15808. * @restrict A
  15809. * @priority 99
  15810. *
  15811. * @description
  15812. * Using Angular markup like `{{hash}}` in an href attribute will
  15813. * make the link go to the wrong URL if the user clicks it before
  15814. * Angular has a chance to replace the `{{hash}}` markup with its
  15815. * value. Until Angular replaces the markup the link will be broken
  15816. * and will most likely return a 404 error.
  15817. *
  15818. * The `ngHref` directive solves this problem.
  15819. *
  15820. * The wrong way to write it:
  15821. * ```html
  15822. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15823. * ```
  15824. *
  15825. * The correct way to write it:
  15826. * ```html
  15827. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15828. * ```
  15829. *
  15830. * @element A
  15831. * @param {template} ngHref any string which can contain `{{}}` markup.
  15832. *
  15833. * @example
  15834. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  15835. * in links and their different behaviors:
  15836. <example>
  15837. <file name="index.html">
  15838. <input ng-model="value" /><br />
  15839. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  15840. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  15841. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  15842. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  15843. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  15844. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  15845. </file>
  15846. <file name="protractor.js" type="protractor">
  15847. it('should execute ng-click but not reload when href without value', function() {
  15848. element(by.id('link-1')).click();
  15849. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  15850. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  15851. });
  15852. it('should execute ng-click but not reload when href empty string', function() {
  15853. element(by.id('link-2')).click();
  15854. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  15855. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  15856. });
  15857. it('should execute ng-click and change url when ng-href specified', function() {
  15858. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  15859. element(by.id('link-3')).click();
  15860. // At this point, we navigate away from an Angular page, so we need
  15861. // to use browser.driver to get the base webdriver.
  15862. browser.wait(function() {
  15863. return browser.driver.getCurrentUrl().then(function(url) {
  15864. return url.match(/\/123$/);
  15865. });
  15866. }, 5000, 'page should navigate to /123');
  15867. });
  15868. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  15869. element(by.id('link-4')).click();
  15870. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  15871. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  15872. });
  15873. it('should execute ng-click but not reload when no href but name specified', function() {
  15874. element(by.id('link-5')).click();
  15875. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  15876. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  15877. });
  15878. it('should only change url when only ng-href', function() {
  15879. element(by.model('value')).clear();
  15880. element(by.model('value')).sendKeys('6');
  15881. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  15882. element(by.id('link-6')).click();
  15883. // At this point, we navigate away from an Angular page, so we need
  15884. // to use browser.driver to get the base webdriver.
  15885. browser.wait(function() {
  15886. return browser.driver.getCurrentUrl().then(function(url) {
  15887. return url.match(/\/6$/);
  15888. });
  15889. }, 5000, 'page should navigate to /6');
  15890. });
  15891. </file>
  15892. </example>
  15893. */
  15894. /**
  15895. * @ngdoc directive
  15896. * @name ngSrc
  15897. * @restrict A
  15898. * @priority 99
  15899. *
  15900. * @description
  15901. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  15902. * work right: The browser will fetch from the URL with the literal
  15903. * text `{{hash}}` until Angular replaces the expression inside
  15904. * `{{hash}}`. The `ngSrc` directive solves this problem.
  15905. *
  15906. * The buggy way to write it:
  15907. * ```html
  15908. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  15909. * ```
  15910. *
  15911. * The correct way to write it:
  15912. * ```html
  15913. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  15914. * ```
  15915. *
  15916. * @element IMG
  15917. * @param {template} ngSrc any string which can contain `{{}}` markup.
  15918. */
  15919. /**
  15920. * @ngdoc directive
  15921. * @name ngSrcset
  15922. * @restrict A
  15923. * @priority 99
  15924. *
  15925. * @description
  15926. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  15927. * work right: The browser will fetch from the URL with the literal
  15928. * text `{{hash}}` until Angular replaces the expression inside
  15929. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  15930. *
  15931. * The buggy way to write it:
  15932. * ```html
  15933. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  15934. * ```
  15935. *
  15936. * The correct way to write it:
  15937. * ```html
  15938. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  15939. * ```
  15940. *
  15941. * @element IMG
  15942. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  15943. */
  15944. /**
  15945. * @ngdoc directive
  15946. * @name ngDisabled
  15947. * @restrict A
  15948. * @priority 100
  15949. *
  15950. * @description
  15951. *
  15952. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  15953. * ```html
  15954. * <div ng-init="scope = { isDisabled: false }">
  15955. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  15956. * </div>
  15957. * ```
  15958. *
  15959. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15960. * such as disabled. (Their presence means true and their absence means false.)
  15961. * If we put an Angular interpolation expression into such an attribute then the
  15962. * binding information would be lost when the browser removes the attribute.
  15963. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  15964. * This complementary directive is not removed by the browser and so provides
  15965. * a permanent reliable place to store the binding information.
  15966. *
  15967. * @example
  15968. <example>
  15969. <file name="index.html">
  15970. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  15971. <button ng-model="button" ng-disabled="checked">Button</button>
  15972. </file>
  15973. <file name="protractor.js" type="protractor">
  15974. it('should toggle button', function() {
  15975. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  15976. element(by.model('checked')).click();
  15977. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  15978. });
  15979. </file>
  15980. </example>
  15981. *
  15982. * @element INPUT
  15983. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  15984. * then special attribute "disabled" will be set on the element
  15985. */
  15986. /**
  15987. * @ngdoc directive
  15988. * @name ngChecked
  15989. * @restrict A
  15990. * @priority 100
  15991. *
  15992. * @description
  15993. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15994. * such as checked. (Their presence means true and their absence means false.)
  15995. * If we put an Angular interpolation expression into such an attribute then the
  15996. * binding information would be lost when the browser removes the attribute.
  15997. * The `ngChecked` directive solves this problem for the `checked` attribute.
  15998. * This complementary directive is not removed by the browser and so provides
  15999. * a permanent reliable place to store the binding information.
  16000. * @example
  16001. <example>
  16002. <file name="index.html">
  16003. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  16004. <input id="checkSlave" type="checkbox" ng-checked="master">
  16005. </file>
  16006. <file name="protractor.js" type="protractor">
  16007. it('should check both checkBoxes', function() {
  16008. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  16009. element(by.model('master')).click();
  16010. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  16011. });
  16012. </file>
  16013. </example>
  16014. *
  16015. * @element INPUT
  16016. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  16017. * then special attribute "checked" will be set on the element
  16018. */
  16019. /**
  16020. * @ngdoc directive
  16021. * @name ngReadonly
  16022. * @restrict A
  16023. * @priority 100
  16024. *
  16025. * @description
  16026. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16027. * such as readonly. (Their presence means true and their absence means false.)
  16028. * If we put an Angular interpolation expression into such an attribute then the
  16029. * binding information would be lost when the browser removes the attribute.
  16030. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  16031. * This complementary directive is not removed by the browser and so provides
  16032. * a permanent reliable place to store the binding information.
  16033. * @example
  16034. <example>
  16035. <file name="index.html">
  16036. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  16037. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  16038. </file>
  16039. <file name="protractor.js" type="protractor">
  16040. it('should toggle readonly attr', function() {
  16041. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  16042. element(by.model('checked')).click();
  16043. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  16044. });
  16045. </file>
  16046. </example>
  16047. *
  16048. * @element INPUT
  16049. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  16050. * then special attribute "readonly" will be set on the element
  16051. */
  16052. /**
  16053. * @ngdoc directive
  16054. * @name ngSelected
  16055. * @restrict A
  16056. * @priority 100
  16057. *
  16058. * @description
  16059. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16060. * such as selected. (Their presence means true and their absence means false.)
  16061. * If we put an Angular interpolation expression into such an attribute then the
  16062. * binding information would be lost when the browser removes the attribute.
  16063. * The `ngSelected` directive solves this problem for the `selected` attribute.
  16064. * This complementary directive is not removed by the browser and so provides
  16065. * a permanent reliable place to store the binding information.
  16066. *
  16067. * @example
  16068. <example>
  16069. <file name="index.html">
  16070. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  16071. <select>
  16072. <option>Hello!</option>
  16073. <option id="greet" ng-selected="selected">Greetings!</option>
  16074. </select>
  16075. </file>
  16076. <file name="protractor.js" type="protractor">
  16077. it('should select Greetings!', function() {
  16078. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  16079. element(by.model('selected')).click();
  16080. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  16081. });
  16082. </file>
  16083. </example>
  16084. *
  16085. * @element OPTION
  16086. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16087. * then special attribute "selected" will be set on the element
  16088. */
  16089. /**
  16090. * @ngdoc directive
  16091. * @name ngOpen
  16092. * @restrict A
  16093. * @priority 100
  16094. *
  16095. * @description
  16096. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16097. * such as open. (Their presence means true and their absence means false.)
  16098. * If we put an Angular interpolation expression into such an attribute then the
  16099. * binding information would be lost when the browser removes the attribute.
  16100. * The `ngOpen` directive solves this problem for the `open` attribute.
  16101. * This complementary directive is not removed by the browser and so provides
  16102. * a permanent reliable place to store the binding information.
  16103. * @example
  16104. <example>
  16105. <file name="index.html">
  16106. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16107. <details id="details" ng-open="open">
  16108. <summary>Show/Hide me</summary>
  16109. </details>
  16110. </file>
  16111. <file name="protractor.js" type="protractor">
  16112. it('should toggle open', function() {
  16113. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16114. element(by.model('open')).click();
  16115. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16116. });
  16117. </file>
  16118. </example>
  16119. *
  16120. * @element DETAILS
  16121. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16122. * then special attribute "open" will be set on the element
  16123. */
  16124. var ngAttributeAliasDirectives = {};
  16125. // boolean attrs are evaluated
  16126. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16127. // binding to multiple is not supported
  16128. if (propName == "multiple") return;
  16129. var normalized = directiveNormalize('ng-' + attrName);
  16130. ngAttributeAliasDirectives[normalized] = function() {
  16131. return {
  16132. restrict: 'A',
  16133. priority: 100,
  16134. link: function(scope, element, attr) {
  16135. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16136. attr.$set(attrName, !!value);
  16137. });
  16138. }
  16139. };
  16140. };
  16141. });
  16142. // aliased input attrs are evaluated
  16143. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16144. ngAttributeAliasDirectives[ngAttr] = function() {
  16145. return {
  16146. priority: 100,
  16147. link: function(scope, element, attr) {
  16148. //special case ngPattern when a literal regular expression value
  16149. //is used as the expression (this way we don't have to watch anything).
  16150. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16151. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16152. if (match) {
  16153. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16154. return;
  16155. }
  16156. }
  16157. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16158. attr.$set(ngAttr, value);
  16159. });
  16160. }
  16161. };
  16162. };
  16163. });
  16164. // ng-src, ng-srcset, ng-href are interpolated
  16165. forEach(['src', 'srcset', 'href'], function(attrName) {
  16166. var normalized = directiveNormalize('ng-' + attrName);
  16167. ngAttributeAliasDirectives[normalized] = function() {
  16168. return {
  16169. priority: 99, // it needs to run after the attributes are interpolated
  16170. link: function(scope, element, attr) {
  16171. var propName = attrName,
  16172. name = attrName;
  16173. if (attrName === 'href' &&
  16174. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16175. name = 'xlinkHref';
  16176. attr.$attr[name] = 'xlink:href';
  16177. propName = null;
  16178. }
  16179. attr.$observe(normalized, function(value) {
  16180. if (!value) {
  16181. if (attrName === 'href') {
  16182. attr.$set(name, null);
  16183. }
  16184. return;
  16185. }
  16186. attr.$set(name, value);
  16187. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16188. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16189. // to set the property as well to achieve the desired effect.
  16190. // we use attr[attrName] value since $set can sanitize the url.
  16191. if (msie && propName) element.prop(propName, attr[name]);
  16192. });
  16193. }
  16194. };
  16195. };
  16196. });
  16197. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16198. */
  16199. var nullFormCtrl = {
  16200. $addControl: noop,
  16201. $$renameControl: nullFormRenameControl,
  16202. $removeControl: noop,
  16203. $setValidity: noop,
  16204. $setDirty: noop,
  16205. $setPristine: noop,
  16206. $setSubmitted: noop
  16207. },
  16208. SUBMITTED_CLASS = 'ng-submitted';
  16209. function nullFormRenameControl(control, name) {
  16210. control.$name = name;
  16211. }
  16212. /**
  16213. * @ngdoc type
  16214. * @name form.FormController
  16215. *
  16216. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16217. * @property {boolean} $dirty True if user has already interacted with the form.
  16218. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16219. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16220. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16221. *
  16222. * @property {Object} $error Is an object hash, containing references to controls or
  16223. * forms with failing validators, where:
  16224. *
  16225. * - keys are validation tokens (error names),
  16226. * - values are arrays of controls or forms that have a failing validator for given error name.
  16227. *
  16228. * Built-in validation tokens:
  16229. *
  16230. * - `email`
  16231. * - `max`
  16232. * - `maxlength`
  16233. * - `min`
  16234. * - `minlength`
  16235. * - `number`
  16236. * - `pattern`
  16237. * - `required`
  16238. * - `url`
  16239. * - `date`
  16240. * - `datetimelocal`
  16241. * - `time`
  16242. * - `week`
  16243. * - `month`
  16244. *
  16245. * @description
  16246. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16247. * such as being valid/invalid or dirty/pristine.
  16248. *
  16249. * Each {@link ng.directive:form form} directive creates an instance
  16250. * of `FormController`.
  16251. *
  16252. */
  16253. //asks for $scope to fool the BC controller module
  16254. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16255. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16256. var form = this,
  16257. controls = [];
  16258. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16259. // init state
  16260. form.$error = {};
  16261. form.$$success = {};
  16262. form.$pending = undefined;
  16263. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16264. form.$dirty = false;
  16265. form.$pristine = true;
  16266. form.$valid = true;
  16267. form.$invalid = false;
  16268. form.$submitted = false;
  16269. parentForm.$addControl(form);
  16270. /**
  16271. * @ngdoc method
  16272. * @name form.FormController#$rollbackViewValue
  16273. *
  16274. * @description
  16275. * Rollback all form controls pending updates to the `$modelValue`.
  16276. *
  16277. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16278. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16279. * a form that uses `ng-model-options` to pend updates.
  16280. */
  16281. form.$rollbackViewValue = function() {
  16282. forEach(controls, function(control) {
  16283. control.$rollbackViewValue();
  16284. });
  16285. };
  16286. /**
  16287. * @ngdoc method
  16288. * @name form.FormController#$commitViewValue
  16289. *
  16290. * @description
  16291. * Commit all form controls pending updates to the `$modelValue`.
  16292. *
  16293. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16294. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16295. * usually handles calling this in response to input events.
  16296. */
  16297. form.$commitViewValue = function() {
  16298. forEach(controls, function(control) {
  16299. control.$commitViewValue();
  16300. });
  16301. };
  16302. /**
  16303. * @ngdoc method
  16304. * @name form.FormController#$addControl
  16305. *
  16306. * @description
  16307. * Register a control with the form.
  16308. *
  16309. * Input elements using ngModelController do this automatically when they are linked.
  16310. */
  16311. form.$addControl = function(control) {
  16312. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16313. // and not added to the scope. Now we throw an error.
  16314. assertNotHasOwnProperty(control.$name, 'input');
  16315. controls.push(control);
  16316. if (control.$name) {
  16317. form[control.$name] = control;
  16318. }
  16319. };
  16320. // Private API: rename a form control
  16321. form.$$renameControl = function(control, newName) {
  16322. var oldName = control.$name;
  16323. if (form[oldName] === control) {
  16324. delete form[oldName];
  16325. }
  16326. form[newName] = control;
  16327. control.$name = newName;
  16328. };
  16329. /**
  16330. * @ngdoc method
  16331. * @name form.FormController#$removeControl
  16332. *
  16333. * @description
  16334. * Deregister a control from the form.
  16335. *
  16336. * Input elements using ngModelController do this automatically when they are destroyed.
  16337. */
  16338. form.$removeControl = function(control) {
  16339. if (control.$name && form[control.$name] === control) {
  16340. delete form[control.$name];
  16341. }
  16342. forEach(form.$pending, function(value, name) {
  16343. form.$setValidity(name, null, control);
  16344. });
  16345. forEach(form.$error, function(value, name) {
  16346. form.$setValidity(name, null, control);
  16347. });
  16348. arrayRemove(controls, control);
  16349. };
  16350. /**
  16351. * @ngdoc method
  16352. * @name form.FormController#$setValidity
  16353. *
  16354. * @description
  16355. * Sets the validity of a form control.
  16356. *
  16357. * This method will also propagate to parent forms.
  16358. */
  16359. addSetValidityMethod({
  16360. ctrl: this,
  16361. $element: element,
  16362. set: function(object, property, control) {
  16363. var list = object[property];
  16364. if (!list) {
  16365. object[property] = [control];
  16366. } else {
  16367. var index = list.indexOf(control);
  16368. if (index === -1) {
  16369. list.push(control);
  16370. }
  16371. }
  16372. },
  16373. unset: function(object, property, control) {
  16374. var list = object[property];
  16375. if (!list) {
  16376. return;
  16377. }
  16378. arrayRemove(list, control);
  16379. if (list.length === 0) {
  16380. delete object[property];
  16381. }
  16382. },
  16383. parentForm: parentForm,
  16384. $animate: $animate
  16385. });
  16386. /**
  16387. * @ngdoc method
  16388. * @name form.FormController#$setDirty
  16389. *
  16390. * @description
  16391. * Sets the form to a dirty state.
  16392. *
  16393. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16394. * state (ng-dirty class). This method will also propagate to parent forms.
  16395. */
  16396. form.$setDirty = function() {
  16397. $animate.removeClass(element, PRISTINE_CLASS);
  16398. $animate.addClass(element, DIRTY_CLASS);
  16399. form.$dirty = true;
  16400. form.$pristine = false;
  16401. parentForm.$setDirty();
  16402. };
  16403. /**
  16404. * @ngdoc method
  16405. * @name form.FormController#$setPristine
  16406. *
  16407. * @description
  16408. * Sets the form to its pristine state.
  16409. *
  16410. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16411. * state (ng-pristine class). This method will also propagate to all the controls contained
  16412. * in this form.
  16413. *
  16414. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16415. * saving or resetting it.
  16416. */
  16417. form.$setPristine = function() {
  16418. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16419. form.$dirty = false;
  16420. form.$pristine = true;
  16421. form.$submitted = false;
  16422. forEach(controls, function(control) {
  16423. control.$setPristine();
  16424. });
  16425. };
  16426. /**
  16427. * @ngdoc method
  16428. * @name form.FormController#$setUntouched
  16429. *
  16430. * @description
  16431. * Sets the form to its untouched state.
  16432. *
  16433. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16434. * untouched state (ng-untouched class).
  16435. *
  16436. * Setting a form controls back to their untouched state is often useful when setting the form
  16437. * back to its pristine state.
  16438. */
  16439. form.$setUntouched = function() {
  16440. forEach(controls, function(control) {
  16441. control.$setUntouched();
  16442. });
  16443. };
  16444. /**
  16445. * @ngdoc method
  16446. * @name form.FormController#$setSubmitted
  16447. *
  16448. * @description
  16449. * Sets the form to its submitted state.
  16450. */
  16451. form.$setSubmitted = function() {
  16452. $animate.addClass(element, SUBMITTED_CLASS);
  16453. form.$submitted = true;
  16454. parentForm.$setSubmitted();
  16455. };
  16456. }
  16457. /**
  16458. * @ngdoc directive
  16459. * @name ngForm
  16460. * @restrict EAC
  16461. *
  16462. * @description
  16463. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16464. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16465. * sub-group of controls needs to be determined.
  16466. *
  16467. * Note: the purpose of `ngForm` is to group controls,
  16468. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16469. * (e.g. posting to the server, ...).
  16470. *
  16471. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16472. * related scope, under this name.
  16473. *
  16474. */
  16475. /**
  16476. * @ngdoc directive
  16477. * @name form
  16478. * @restrict E
  16479. *
  16480. * @description
  16481. * Directive that instantiates
  16482. * {@link form.FormController FormController}.
  16483. *
  16484. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16485. * this name.
  16486. *
  16487. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16488. *
  16489. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  16490. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16491. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16492. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16493. * using Angular validation directives in forms that are dynamically generated using the
  16494. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16495. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16496. * `ngForm` directive and nest these in an outer `form` element.
  16497. *
  16498. *
  16499. * # CSS classes
  16500. * - `ng-valid` is set if the form is valid.
  16501. * - `ng-invalid` is set if the form is invalid.
  16502. * - `ng-pristine` is set if the form is pristine.
  16503. * - `ng-dirty` is set if the form is dirty.
  16504. * - `ng-submitted` is set if the form was submitted.
  16505. *
  16506. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16507. *
  16508. *
  16509. * # Submitting a form and preventing the default action
  16510. *
  16511. * Since the role of forms in client-side Angular applications is different than in classical
  16512. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16513. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16514. * to handle the form submission in an application-specific way.
  16515. *
  16516. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16517. * `<form>` element has an `action` attribute specified.
  16518. *
  16519. * You can use one of the following two ways to specify what javascript method should be called when
  16520. * a form is submitted:
  16521. *
  16522. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16523. * - {@link ng.directive:ngClick ngClick} directive on the first
  16524. * button or input field of type submit (input[type=submit])
  16525. *
  16526. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16527. * or {@link ng.directive:ngClick ngClick} directives.
  16528. * This is because of the following form submission rules in the HTML specification:
  16529. *
  16530. * - If a form has only one input field then hitting enter in this field triggers form submit
  16531. * (`ngSubmit`)
  16532. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16533. * doesn't trigger submit
  16534. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16535. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16536. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16537. *
  16538. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16539. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16540. * to have access to the updated model.
  16541. *
  16542. * ## Animation Hooks
  16543. *
  16544. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16545. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16546. * other validations that are performed within the form. Animations in ngForm are similar to how
  16547. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16548. * as JS animations.
  16549. *
  16550. * The following example shows a simple way to utilize CSS transitions to style a form element
  16551. * that has been rendered as invalid after it has been validated:
  16552. *
  16553. * <pre>
  16554. * //be sure to include ngAnimate as a module to hook into more
  16555. * //advanced animations
  16556. * .my-form {
  16557. * transition:0.5s linear all;
  16558. * background: white;
  16559. * }
  16560. * .my-form.ng-invalid {
  16561. * background: red;
  16562. * color:white;
  16563. * }
  16564. * </pre>
  16565. *
  16566. * @example
  16567. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16568. <file name="index.html">
  16569. <script>
  16570. angular.module('formExample', [])
  16571. .controller('FormController', ['$scope', function($scope) {
  16572. $scope.userType = 'guest';
  16573. }]);
  16574. </script>
  16575. <style>
  16576. .my-form {
  16577. -webkit-transition:all linear 0.5s;
  16578. transition:all linear 0.5s;
  16579. background: transparent;
  16580. }
  16581. .my-form.ng-invalid {
  16582. background: red;
  16583. }
  16584. </style>
  16585. <form name="myForm" ng-controller="FormController" class="my-form">
  16586. userType: <input name="input" ng-model="userType" required>
  16587. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16588. <tt>userType = {{userType}}</tt><br>
  16589. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16590. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16591. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16592. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16593. </form>
  16594. </file>
  16595. <file name="protractor.js" type="protractor">
  16596. it('should initialize to model', function() {
  16597. var userType = element(by.binding('userType'));
  16598. var valid = element(by.binding('myForm.input.$valid'));
  16599. expect(userType.getText()).toContain('guest');
  16600. expect(valid.getText()).toContain('true');
  16601. });
  16602. it('should be invalid if empty', function() {
  16603. var userType = element(by.binding('userType'));
  16604. var valid = element(by.binding('myForm.input.$valid'));
  16605. var userInput = element(by.model('userType'));
  16606. userInput.clear();
  16607. userInput.sendKeys('');
  16608. expect(userType.getText()).toEqual('userType =');
  16609. expect(valid.getText()).toContain('false');
  16610. });
  16611. </file>
  16612. </example>
  16613. *
  16614. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16615. * related scope, under this name.
  16616. */
  16617. var formDirectiveFactory = function(isNgForm) {
  16618. return ['$timeout', function($timeout) {
  16619. var formDirective = {
  16620. name: 'form',
  16621. restrict: isNgForm ? 'EAC' : 'E',
  16622. controller: FormController,
  16623. compile: function ngFormCompile(formElement) {
  16624. // Setup initial state of the control
  16625. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16626. return {
  16627. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16628. // if `action` attr is not present on the form, prevent the default action (submission)
  16629. if (!('action' in attr)) {
  16630. // we can't use jq events because if a form is destroyed during submission the default
  16631. // action is not prevented. see #1238
  16632. //
  16633. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16634. // page reload if the form was destroyed by submission of the form via a click handler
  16635. // on a button in the form. Looks like an IE9 specific bug.
  16636. var handleFormSubmission = function(event) {
  16637. scope.$apply(function() {
  16638. controller.$commitViewValue();
  16639. controller.$setSubmitted();
  16640. });
  16641. event.preventDefault
  16642. ? event.preventDefault()
  16643. : event.returnValue = false; // IE
  16644. };
  16645. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16646. // unregister the preventDefault listener so that we don't not leak memory but in a
  16647. // way that will achieve the prevention of the default action.
  16648. formElement.on('$destroy', function() {
  16649. $timeout(function() {
  16650. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16651. }, 0, false);
  16652. });
  16653. }
  16654. var parentFormCtrl = controller.$$parentForm,
  16655. alias = controller.$name;
  16656. if (alias) {
  16657. setter(scope, alias, controller, alias);
  16658. attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
  16659. if (alias === newValue) return;
  16660. setter(scope, alias, undefined, alias);
  16661. alias = newValue;
  16662. setter(scope, alias, controller, alias);
  16663. parentFormCtrl.$$renameControl(controller, alias);
  16664. });
  16665. }
  16666. formElement.on('$destroy', function() {
  16667. parentFormCtrl.$removeControl(controller);
  16668. if (alias) {
  16669. setter(scope, alias, undefined, alias);
  16670. }
  16671. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16672. });
  16673. }
  16674. };
  16675. }
  16676. };
  16677. return formDirective;
  16678. }];
  16679. };
  16680. var formDirective = formDirectiveFactory();
  16681. var ngFormDirective = formDirectiveFactory(true);
  16682. /* global VALID_CLASS: true,
  16683. INVALID_CLASS: true,
  16684. PRISTINE_CLASS: true,
  16685. DIRTY_CLASS: true,
  16686. UNTOUCHED_CLASS: true,
  16687. TOUCHED_CLASS: true,
  16688. */
  16689. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16690. 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)/;
  16691. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16692. 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;
  16693. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16694. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16695. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16696. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16697. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16698. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16699. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  16700. var $ngModelMinErr = new minErr('ngModel');
  16701. var inputType = {
  16702. /**
  16703. * @ngdoc input
  16704. * @name input[text]
  16705. *
  16706. * @description
  16707. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  16708. *
  16709. *
  16710. * @param {string} ngModel Assignable angular expression to data-bind to.
  16711. * @param {string=} name Property name of the form under which the control is published.
  16712. * @param {string=} required Adds `required` validation error key if the value is not entered.
  16713. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16714. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16715. * `required` when you want to data-bind to the `required` attribute.
  16716. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  16717. * minlength.
  16718. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  16719. * maxlength.
  16720. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  16721. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  16722. * patterns defined as scope expressions.
  16723. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16724. * interaction with the input element.
  16725. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  16726. * This parameter is ignored for input[type=password] controls, which will never trim the
  16727. * input.
  16728. *
  16729. * @example
  16730. <example name="text-input-directive" module="textInputExample">
  16731. <file name="index.html">
  16732. <script>
  16733. angular.module('textInputExample', [])
  16734. .controller('ExampleController', ['$scope', function($scope) {
  16735. $scope.text = 'guest';
  16736. $scope.word = /^\s*\w*\s*$/;
  16737. }]);
  16738. </script>
  16739. <form name="myForm" ng-controller="ExampleController">
  16740. Single word: <input type="text" name="input" ng-model="text"
  16741. ng-pattern="word" required ng-trim="false">
  16742. <span class="error" ng-show="myForm.input.$error.required">
  16743. Required!</span>
  16744. <span class="error" ng-show="myForm.input.$error.pattern">
  16745. Single word only!</span>
  16746. <tt>text = {{text}}</tt><br/>
  16747. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16748. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16749. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16750. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16751. </form>
  16752. </file>
  16753. <file name="protractor.js" type="protractor">
  16754. var text = element(by.binding('text'));
  16755. var valid = element(by.binding('myForm.input.$valid'));
  16756. var input = element(by.model('text'));
  16757. it('should initialize to model', function() {
  16758. expect(text.getText()).toContain('guest');
  16759. expect(valid.getText()).toContain('true');
  16760. });
  16761. it('should be invalid if empty', function() {
  16762. input.clear();
  16763. input.sendKeys('');
  16764. expect(text.getText()).toEqual('text =');
  16765. expect(valid.getText()).toContain('false');
  16766. });
  16767. it('should be invalid if multi word', function() {
  16768. input.clear();
  16769. input.sendKeys('hello world');
  16770. expect(valid.getText()).toContain('false');
  16771. });
  16772. </file>
  16773. </example>
  16774. */
  16775. 'text': textInputType,
  16776. /**
  16777. * @ngdoc input
  16778. * @name input[date]
  16779. *
  16780. * @description
  16781. * Input with date validation and transformation. In browsers that do not yet support
  16782. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  16783. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  16784. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  16785. * expected input format via a placeholder or label.
  16786. *
  16787. * The model must always be a Date object, otherwise Angular will throw an error.
  16788. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16789. *
  16790. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16791. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16792. *
  16793. * @param {string} ngModel Assignable angular expression to data-bind to.
  16794. * @param {string=} name Property name of the form under which the control is published.
  16795. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16796. * valid ISO date string (yyyy-MM-dd).
  16797. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16798. * a valid ISO date string (yyyy-MM-dd).
  16799. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16800. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16801. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16802. * `required` when you want to data-bind to the `required` attribute.
  16803. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16804. * interaction with the input element.
  16805. *
  16806. * @example
  16807. <example name="date-input-directive" module="dateInputExample">
  16808. <file name="index.html">
  16809. <script>
  16810. angular.module('dateInputExample', [])
  16811. .controller('DateController', ['$scope', function($scope) {
  16812. $scope.value = new Date(2013, 9, 22);
  16813. }]);
  16814. </script>
  16815. <form name="myForm" ng-controller="DateController as dateCtrl">
  16816. Pick a date in 2013:
  16817. <input type="date" id="exampleInput" name="input" ng-model="value"
  16818. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  16819. <span class="error" ng-show="myForm.input.$error.required">
  16820. Required!</span>
  16821. <span class="error" ng-show="myForm.input.$error.date">
  16822. Not a valid date!</span>
  16823. <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
  16824. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16825. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16826. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16827. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16828. </form>
  16829. </file>
  16830. <file name="protractor.js" type="protractor">
  16831. var value = element(by.binding('value | date: "yyyy-MM-dd"'));
  16832. var valid = element(by.binding('myForm.input.$valid'));
  16833. var input = element(by.model('value'));
  16834. // currently protractor/webdriver does not support
  16835. // sending keys to all known HTML5 input controls
  16836. // for various browsers (see https://github.com/angular/protractor/issues/562).
  16837. function setInput(val) {
  16838. // set the value of the element and force validation.
  16839. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16840. "ipt.value = '" + val + "';" +
  16841. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16842. browser.executeScript(scr);
  16843. }
  16844. it('should initialize to model', function() {
  16845. expect(value.getText()).toContain('2013-10-22');
  16846. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16847. });
  16848. it('should be invalid if empty', function() {
  16849. setInput('');
  16850. expect(value.getText()).toEqual('value =');
  16851. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16852. });
  16853. it('should be invalid if over max', function() {
  16854. setInput('2015-01-01');
  16855. expect(value.getText()).toContain('');
  16856. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16857. });
  16858. </file>
  16859. </example>
  16860. */
  16861. 'date': createDateInputType('date', DATE_REGEXP,
  16862. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  16863. 'yyyy-MM-dd'),
  16864. /**
  16865. * @ngdoc input
  16866. * @name input[datetime-local]
  16867. *
  16868. * @description
  16869. * Input with datetime validation and transformation. In browsers that do not yet support
  16870. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16871. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  16872. *
  16873. * The model must always be a Date object, otherwise Angular will throw an error.
  16874. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16875. *
  16876. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16877. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16878. *
  16879. * @param {string} ngModel Assignable angular expression to data-bind to.
  16880. * @param {string=} name Property name of the form under which the control is published.
  16881. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16882. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16883. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16884. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16885. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16886. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16887. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16888. * `required` when you want to data-bind to the `required` attribute.
  16889. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16890. * interaction with the input element.
  16891. *
  16892. * @example
  16893. <example name="datetimelocal-input-directive" module="dateExample">
  16894. <file name="index.html">
  16895. <script>
  16896. angular.module('dateExample', [])
  16897. .controller('DateController', ['$scope', function($scope) {
  16898. $scope.value = new Date(2010, 11, 28, 14, 57);
  16899. }]);
  16900. </script>
  16901. <form name="myForm" ng-controller="DateController as dateCtrl">
  16902. Pick a date between in 2013:
  16903. <input type="datetime-local" id="exampleInput" name="input" ng-model="value"
  16904. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  16905. <span class="error" ng-show="myForm.input.$error.required">
  16906. Required!</span>
  16907. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  16908. Not a valid date!</span>
  16909. <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  16910. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16911. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16912. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16913. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16914. </form>
  16915. </file>
  16916. <file name="protractor.js" type="protractor">
  16917. var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
  16918. var valid = element(by.binding('myForm.input.$valid'));
  16919. var input = element(by.model('value'));
  16920. // currently protractor/webdriver does not support
  16921. // sending keys to all known HTML5 input controls
  16922. // for various browsers (https://github.com/angular/protractor/issues/562).
  16923. function setInput(val) {
  16924. // set the value of the element and force validation.
  16925. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16926. "ipt.value = '" + val + "';" +
  16927. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16928. browser.executeScript(scr);
  16929. }
  16930. it('should initialize to model', function() {
  16931. expect(value.getText()).toContain('2010-12-28T14:57:00');
  16932. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16933. });
  16934. it('should be invalid if empty', function() {
  16935. setInput('');
  16936. expect(value.getText()).toEqual('value =');
  16937. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16938. });
  16939. it('should be invalid if over max', function() {
  16940. setInput('2015-01-01T23:59:00');
  16941. expect(value.getText()).toContain('');
  16942. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16943. });
  16944. </file>
  16945. </example>
  16946. */
  16947. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  16948. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  16949. 'yyyy-MM-ddTHH:mm:ss.sss'),
  16950. /**
  16951. * @ngdoc input
  16952. * @name input[time]
  16953. *
  16954. * @description
  16955. * Input with time validation and transformation. In browsers that do not yet support
  16956. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16957. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  16958. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  16959. *
  16960. * The model must always be a Date object, otherwise Angular will throw an error.
  16961. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  16962. *
  16963. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16964. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16965. *
  16966. * @param {string} ngModel Assignable angular expression to data-bind to.
  16967. * @param {string=} name Property name of the form under which the control is published.
  16968. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16969. * valid ISO time format (HH:mm:ss).
  16970. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  16971. * valid ISO time format (HH:mm:ss).
  16972. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16973. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16974. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16975. * `required` when you want to data-bind to the `required` attribute.
  16976. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16977. * interaction with the input element.
  16978. *
  16979. * @example
  16980. <example name="time-input-directive" module="timeExample">
  16981. <file name="index.html">
  16982. <script>
  16983. angular.module('timeExample', [])
  16984. .controller('DateController', ['$scope', function($scope) {
  16985. $scope.value = new Date(1970, 0, 1, 14, 57, 0);
  16986. }]);
  16987. </script>
  16988. <form name="myForm" ng-controller="DateController as dateCtrl">
  16989. Pick a between 8am and 5pm:
  16990. <input type="time" id="exampleInput" name="input" ng-model="value"
  16991. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  16992. <span class="error" ng-show="myForm.input.$error.required">
  16993. Required!</span>
  16994. <span class="error" ng-show="myForm.input.$error.time">
  16995. Not a valid date!</span>
  16996. <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
  16997. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16998. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16999. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17000. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17001. </form>
  17002. </file>
  17003. <file name="protractor.js" type="protractor">
  17004. var value = element(by.binding('value | date: "HH:mm:ss"'));
  17005. var valid = element(by.binding('myForm.input.$valid'));
  17006. var input = element(by.model('value'));
  17007. // currently protractor/webdriver does not support
  17008. // sending keys to all known HTML5 input controls
  17009. // for various browsers (https://github.com/angular/protractor/issues/562).
  17010. function setInput(val) {
  17011. // set the value of the element and force validation.
  17012. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17013. "ipt.value = '" + val + "';" +
  17014. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17015. browser.executeScript(scr);
  17016. }
  17017. it('should initialize to model', function() {
  17018. expect(value.getText()).toContain('14:57:00');
  17019. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17020. });
  17021. it('should be invalid if empty', function() {
  17022. setInput('');
  17023. expect(value.getText()).toEqual('value =');
  17024. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17025. });
  17026. it('should be invalid if over max', function() {
  17027. setInput('23:59:00');
  17028. expect(value.getText()).toContain('');
  17029. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17030. });
  17031. </file>
  17032. </example>
  17033. */
  17034. 'time': createDateInputType('time', TIME_REGEXP,
  17035. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  17036. 'HH:mm:ss.sss'),
  17037. /**
  17038. * @ngdoc input
  17039. * @name input[week]
  17040. *
  17041. * @description
  17042. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  17043. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17044. * week format (yyyy-W##), for example: `2013-W02`.
  17045. *
  17046. * The model must always be a Date object, otherwise Angular will throw an error.
  17047. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17048. *
  17049. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17050. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17051. *
  17052. * @param {string} ngModel Assignable angular expression to data-bind to.
  17053. * @param {string=} name Property name of the form under which the control is published.
  17054. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  17055. * valid ISO week format (yyyy-W##).
  17056. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  17057. * a valid ISO week format (yyyy-W##).
  17058. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17059. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17060. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17061. * `required` when you want to data-bind to the `required` attribute.
  17062. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17063. * interaction with the input element.
  17064. *
  17065. * @example
  17066. <example name="week-input-directive" module="weekExample">
  17067. <file name="index.html">
  17068. <script>
  17069. angular.module('weekExample', [])
  17070. .controller('DateController', ['$scope', function($scope) {
  17071. $scope.value = new Date(2013, 0, 3);
  17072. }]);
  17073. </script>
  17074. <form name="myForm" ng-controller="DateController as dateCtrl">
  17075. Pick a date between in 2013:
  17076. <input id="exampleInput" type="week" name="input" ng-model="value"
  17077. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  17078. <span class="error" ng-show="myForm.input.$error.required">
  17079. Required!</span>
  17080. <span class="error" ng-show="myForm.input.$error.week">
  17081. Not a valid date!</span>
  17082. <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
  17083. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17084. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17085. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17086. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17087. </form>
  17088. </file>
  17089. <file name="protractor.js" type="protractor">
  17090. var value = element(by.binding('value | date: "yyyy-Www"'));
  17091. var valid = element(by.binding('myForm.input.$valid'));
  17092. var input = element(by.model('value'));
  17093. // currently protractor/webdriver does not support
  17094. // sending keys to all known HTML5 input controls
  17095. // for various browsers (https://github.com/angular/protractor/issues/562).
  17096. function setInput(val) {
  17097. // set the value of the element and force validation.
  17098. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17099. "ipt.value = '" + val + "';" +
  17100. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17101. browser.executeScript(scr);
  17102. }
  17103. it('should initialize to model', function() {
  17104. expect(value.getText()).toContain('2013-W01');
  17105. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17106. });
  17107. it('should be invalid if empty', function() {
  17108. setInput('');
  17109. expect(value.getText()).toEqual('value =');
  17110. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17111. });
  17112. it('should be invalid if over max', function() {
  17113. setInput('2015-W01');
  17114. expect(value.getText()).toContain('');
  17115. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17116. });
  17117. </file>
  17118. </example>
  17119. */
  17120. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17121. /**
  17122. * @ngdoc input
  17123. * @name input[month]
  17124. *
  17125. * @description
  17126. * Input with month validation and transformation. In browsers that do not yet support
  17127. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17128. * month format (yyyy-MM), for example: `2009-01`.
  17129. *
  17130. * The model must always be a Date object, otherwise Angular will throw an error.
  17131. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  17132. * If the model is not set to the first of the month, the next view to model update will set it
  17133. * to the first of the month.
  17134. *
  17135. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17136. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17137. *
  17138. * @param {string} ngModel Assignable angular expression to data-bind to.
  17139. * @param {string=} name Property name of the form under which the control is published.
  17140. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17141. * a valid ISO month format (yyyy-MM).
  17142. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17143. * be a valid ISO month format (yyyy-MM).
  17144. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17145. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17146. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17147. * `required` when you want to data-bind to the `required` attribute.
  17148. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17149. * interaction with the input element.
  17150. *
  17151. * @example
  17152. <example name="month-input-directive" module="monthExample">
  17153. <file name="index.html">
  17154. <script>
  17155. angular.module('monthExample', [])
  17156. .controller('DateController', ['$scope', function($scope) {
  17157. $scope.value = new Date(2013, 9, 1);
  17158. }]);
  17159. </script>
  17160. <form name="myForm" ng-controller="DateController as dateCtrl">
  17161. Pick a month int 2013:
  17162. <input id="exampleInput" type="month" name="input" ng-model="value"
  17163. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17164. <span class="error" ng-show="myForm.input.$error.required">
  17165. Required!</span>
  17166. <span class="error" ng-show="myForm.input.$error.month">
  17167. Not a valid month!</span>
  17168. <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
  17169. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17170. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17171. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17172. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17173. </form>
  17174. </file>
  17175. <file name="protractor.js" type="protractor">
  17176. var value = element(by.binding('value | date: "yyyy-MM"'));
  17177. var valid = element(by.binding('myForm.input.$valid'));
  17178. var input = element(by.model('value'));
  17179. // currently protractor/webdriver does not support
  17180. // sending keys to all known HTML5 input controls
  17181. // for various browsers (https://github.com/angular/protractor/issues/562).
  17182. function setInput(val) {
  17183. // set the value of the element and force validation.
  17184. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17185. "ipt.value = '" + val + "';" +
  17186. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17187. browser.executeScript(scr);
  17188. }
  17189. it('should initialize to model', function() {
  17190. expect(value.getText()).toContain('2013-10');
  17191. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17192. });
  17193. it('should be invalid if empty', function() {
  17194. setInput('');
  17195. expect(value.getText()).toEqual('value =');
  17196. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17197. });
  17198. it('should be invalid if over max', function() {
  17199. setInput('2015-01');
  17200. expect(value.getText()).toContain('');
  17201. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17202. });
  17203. </file>
  17204. </example>
  17205. */
  17206. 'month': createDateInputType('month', MONTH_REGEXP,
  17207. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17208. 'yyyy-MM'),
  17209. /**
  17210. * @ngdoc input
  17211. * @name input[number]
  17212. *
  17213. * @description
  17214. * Text input with number validation and transformation. Sets the `number` validation
  17215. * error if not a valid number.
  17216. *
  17217. * The model must always be a number, otherwise Angular will throw an error.
  17218. *
  17219. * @param {string} ngModel Assignable angular expression to data-bind to.
  17220. * @param {string=} name Property name of the form under which the control is published.
  17221. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17222. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17223. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17224. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17225. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17226. * `required` when you want to data-bind to the `required` attribute.
  17227. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17228. * minlength.
  17229. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17230. * maxlength.
  17231. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17232. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17233. * patterns defined as scope expressions.
  17234. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17235. * interaction with the input element.
  17236. *
  17237. * @example
  17238. <example name="number-input-directive" module="numberExample">
  17239. <file name="index.html">
  17240. <script>
  17241. angular.module('numberExample', [])
  17242. .controller('ExampleController', ['$scope', function($scope) {
  17243. $scope.value = 12;
  17244. }]);
  17245. </script>
  17246. <form name="myForm" ng-controller="ExampleController">
  17247. Number: <input type="number" name="input" ng-model="value"
  17248. min="0" max="99" required>
  17249. <span class="error" ng-show="myForm.input.$error.required">
  17250. Required!</span>
  17251. <span class="error" ng-show="myForm.input.$error.number">
  17252. Not valid number!</span>
  17253. <tt>value = {{value}}</tt><br/>
  17254. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17255. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17256. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17257. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17258. </form>
  17259. </file>
  17260. <file name="protractor.js" type="protractor">
  17261. var value = element(by.binding('value'));
  17262. var valid = element(by.binding('myForm.input.$valid'));
  17263. var input = element(by.model('value'));
  17264. it('should initialize to model', function() {
  17265. expect(value.getText()).toContain('12');
  17266. expect(valid.getText()).toContain('true');
  17267. });
  17268. it('should be invalid if empty', function() {
  17269. input.clear();
  17270. input.sendKeys('');
  17271. expect(value.getText()).toEqual('value =');
  17272. expect(valid.getText()).toContain('false');
  17273. });
  17274. it('should be invalid if over max', function() {
  17275. input.clear();
  17276. input.sendKeys('123');
  17277. expect(value.getText()).toEqual('value =');
  17278. expect(valid.getText()).toContain('false');
  17279. });
  17280. </file>
  17281. </example>
  17282. */
  17283. 'number': numberInputType,
  17284. /**
  17285. * @ngdoc input
  17286. * @name input[url]
  17287. *
  17288. * @description
  17289. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17290. * valid URL.
  17291. *
  17292. * <div class="alert alert-warning">
  17293. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  17294. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  17295. * the built-in validators (see the {@link guide/forms Forms guide})
  17296. * </div>
  17297. *
  17298. * @param {string} ngModel Assignable angular expression to data-bind to.
  17299. * @param {string=} name Property name of the form under which the control is published.
  17300. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17301. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17302. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17303. * `required` when you want to data-bind to the `required` attribute.
  17304. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17305. * minlength.
  17306. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17307. * maxlength.
  17308. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17309. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17310. * patterns defined as scope expressions.
  17311. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17312. * interaction with the input element.
  17313. *
  17314. * @example
  17315. <example name="url-input-directive" module="urlExample">
  17316. <file name="index.html">
  17317. <script>
  17318. angular.module('urlExample', [])
  17319. .controller('ExampleController', ['$scope', function($scope) {
  17320. $scope.text = 'http://google.com';
  17321. }]);
  17322. </script>
  17323. <form name="myForm" ng-controller="ExampleController">
  17324. URL: <input type="url" name="input" ng-model="text" required>
  17325. <span class="error" ng-show="myForm.input.$error.required">
  17326. Required!</span>
  17327. <span class="error" ng-show="myForm.input.$error.url">
  17328. Not valid url!</span>
  17329. <tt>text = {{text}}</tt><br/>
  17330. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17331. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17332. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17333. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17334. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17335. </form>
  17336. </file>
  17337. <file name="protractor.js" type="protractor">
  17338. var text = element(by.binding('text'));
  17339. var valid = element(by.binding('myForm.input.$valid'));
  17340. var input = element(by.model('text'));
  17341. it('should initialize to model', function() {
  17342. expect(text.getText()).toContain('http://google.com');
  17343. expect(valid.getText()).toContain('true');
  17344. });
  17345. it('should be invalid if empty', function() {
  17346. input.clear();
  17347. input.sendKeys('');
  17348. expect(text.getText()).toEqual('text =');
  17349. expect(valid.getText()).toContain('false');
  17350. });
  17351. it('should be invalid if not url', function() {
  17352. input.clear();
  17353. input.sendKeys('box');
  17354. expect(valid.getText()).toContain('false');
  17355. });
  17356. </file>
  17357. </example>
  17358. */
  17359. 'url': urlInputType,
  17360. /**
  17361. * @ngdoc input
  17362. * @name input[email]
  17363. *
  17364. * @description
  17365. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17366. * address.
  17367. *
  17368. * <div class="alert alert-warning">
  17369. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  17370. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  17371. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  17372. * </div>
  17373. *
  17374. * @param {string} ngModel Assignable angular expression to data-bind to.
  17375. * @param {string=} name Property name of the form under which the control is published.
  17376. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17377. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17378. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17379. * `required` when you want to data-bind to the `required` attribute.
  17380. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17381. * minlength.
  17382. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17383. * maxlength.
  17384. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17385. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17386. * patterns defined as scope expressions.
  17387. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17388. * interaction with the input element.
  17389. *
  17390. * @example
  17391. <example name="email-input-directive" module="emailExample">
  17392. <file name="index.html">
  17393. <script>
  17394. angular.module('emailExample', [])
  17395. .controller('ExampleController', ['$scope', function($scope) {
  17396. $scope.text = 'me@example.com';
  17397. }]);
  17398. </script>
  17399. <form name="myForm" ng-controller="ExampleController">
  17400. Email: <input type="email" name="input" ng-model="text" required>
  17401. <span class="error" ng-show="myForm.input.$error.required">
  17402. Required!</span>
  17403. <span class="error" ng-show="myForm.input.$error.email">
  17404. Not valid email!</span>
  17405. <tt>text = {{text}}</tt><br/>
  17406. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17407. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17408. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17409. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17410. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17411. </form>
  17412. </file>
  17413. <file name="protractor.js" type="protractor">
  17414. var text = element(by.binding('text'));
  17415. var valid = element(by.binding('myForm.input.$valid'));
  17416. var input = element(by.model('text'));
  17417. it('should initialize to model', function() {
  17418. expect(text.getText()).toContain('me@example.com');
  17419. expect(valid.getText()).toContain('true');
  17420. });
  17421. it('should be invalid if empty', function() {
  17422. input.clear();
  17423. input.sendKeys('');
  17424. expect(text.getText()).toEqual('text =');
  17425. expect(valid.getText()).toContain('false');
  17426. });
  17427. it('should be invalid if not email', function() {
  17428. input.clear();
  17429. input.sendKeys('xxx');
  17430. expect(valid.getText()).toContain('false');
  17431. });
  17432. </file>
  17433. </example>
  17434. */
  17435. 'email': emailInputType,
  17436. /**
  17437. * @ngdoc input
  17438. * @name input[radio]
  17439. *
  17440. * @description
  17441. * HTML radio button.
  17442. *
  17443. * @param {string} ngModel Assignable angular expression to data-bind to.
  17444. * @param {string} value The value to which the expression should be set when selected.
  17445. * @param {string=} name Property name of the form under which the control is published.
  17446. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17447. * interaction with the input element.
  17448. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17449. * be set when selected.
  17450. *
  17451. * @example
  17452. <example name="radio-input-directive" module="radioExample">
  17453. <file name="index.html">
  17454. <script>
  17455. angular.module('radioExample', [])
  17456. .controller('ExampleController', ['$scope', function($scope) {
  17457. $scope.color = 'blue';
  17458. $scope.specialValue = {
  17459. "id": "12345",
  17460. "value": "green"
  17461. };
  17462. }]);
  17463. </script>
  17464. <form name="myForm" ng-controller="ExampleController">
  17465. <input type="radio" ng-model="color" value="red"> Red <br/>
  17466. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  17467. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  17468. <tt>color = {{color | json}}</tt><br/>
  17469. </form>
  17470. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17471. </file>
  17472. <file name="protractor.js" type="protractor">
  17473. it('should change state', function() {
  17474. var color = element(by.binding('color'));
  17475. expect(color.getText()).toContain('blue');
  17476. element.all(by.model('color')).get(0).click();
  17477. expect(color.getText()).toContain('red');
  17478. });
  17479. </file>
  17480. </example>
  17481. */
  17482. 'radio': radioInputType,
  17483. /**
  17484. * @ngdoc input
  17485. * @name input[checkbox]
  17486. *
  17487. * @description
  17488. * HTML checkbox.
  17489. *
  17490. * @param {string} ngModel Assignable angular expression to data-bind to.
  17491. * @param {string=} name Property name of the form under which the control is published.
  17492. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17493. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17494. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17495. * interaction with the input element.
  17496. *
  17497. * @example
  17498. <example name="checkbox-input-directive" module="checkboxExample">
  17499. <file name="index.html">
  17500. <script>
  17501. angular.module('checkboxExample', [])
  17502. .controller('ExampleController', ['$scope', function($scope) {
  17503. $scope.value1 = true;
  17504. $scope.value2 = 'YES'
  17505. }]);
  17506. </script>
  17507. <form name="myForm" ng-controller="ExampleController">
  17508. Value1: <input type="checkbox" ng-model="value1"> <br/>
  17509. Value2: <input type="checkbox" ng-model="value2"
  17510. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17511. <tt>value1 = {{value1}}</tt><br/>
  17512. <tt>value2 = {{value2}}</tt><br/>
  17513. </form>
  17514. </file>
  17515. <file name="protractor.js" type="protractor">
  17516. it('should change state', function() {
  17517. var value1 = element(by.binding('value1'));
  17518. var value2 = element(by.binding('value2'));
  17519. expect(value1.getText()).toContain('true');
  17520. expect(value2.getText()).toContain('YES');
  17521. element(by.model('value1')).click();
  17522. element(by.model('value2')).click();
  17523. expect(value1.getText()).toContain('false');
  17524. expect(value2.getText()).toContain('NO');
  17525. });
  17526. </file>
  17527. </example>
  17528. */
  17529. 'checkbox': checkboxInputType,
  17530. 'hidden': noop,
  17531. 'button': noop,
  17532. 'submit': noop,
  17533. 'reset': noop,
  17534. 'file': noop
  17535. };
  17536. function stringBasedInputType(ctrl) {
  17537. ctrl.$formatters.push(function(value) {
  17538. return ctrl.$isEmpty(value) ? value : value.toString();
  17539. });
  17540. }
  17541. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17542. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17543. stringBasedInputType(ctrl);
  17544. }
  17545. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17546. var placeholder = element[0].placeholder, noevent = {};
  17547. var type = lowercase(element[0].type);
  17548. // In composition mode, users are still inputing intermediate text buffer,
  17549. // hold the listener until composition is done.
  17550. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17551. if (!$sniffer.android) {
  17552. var composing = false;
  17553. element.on('compositionstart', function(data) {
  17554. composing = true;
  17555. });
  17556. element.on('compositionend', function() {
  17557. composing = false;
  17558. listener();
  17559. });
  17560. }
  17561. var listener = function(ev) {
  17562. if (composing) return;
  17563. var value = element.val(),
  17564. event = ev && ev.type;
  17565. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  17566. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  17567. // IE also sends input events for other non-input-related things, (such as focusing on a
  17568. // form control), so this change is not entirely enough to solve this.
  17569. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  17570. placeholder = element[0].placeholder;
  17571. return;
  17572. }
  17573. // By default we will trim the value
  17574. // If the attribute ng-trim exists we will avoid trimming
  17575. // If input type is 'password', the value is never trimmed
  17576. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17577. value = trim(value);
  17578. }
  17579. // If a control is suffering from bad input (due to native validators), browsers discard its
  17580. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17581. // control's value is the same empty value twice in a row.
  17582. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17583. ctrl.$setViewValue(value, event);
  17584. }
  17585. };
  17586. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17587. // input event on backspace, delete or cut
  17588. if ($sniffer.hasEvent('input')) {
  17589. element.on('input', listener);
  17590. } else {
  17591. var timeout;
  17592. var deferListener = function(ev) {
  17593. if (!timeout) {
  17594. timeout = $browser.defer(function() {
  17595. listener(ev);
  17596. timeout = null;
  17597. });
  17598. }
  17599. };
  17600. element.on('keydown', function(event) {
  17601. var key = event.keyCode;
  17602. // ignore
  17603. // command modifiers arrows
  17604. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17605. deferListener(event);
  17606. });
  17607. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17608. if ($sniffer.hasEvent('paste')) {
  17609. element.on('paste cut', deferListener);
  17610. }
  17611. }
  17612. // if user paste into input using mouse on older browser
  17613. // or form autocomplete on newer browser, we need "change" event to catch it
  17614. element.on('change', listener);
  17615. ctrl.$render = function() {
  17616. element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue);
  17617. };
  17618. }
  17619. function weekParser(isoWeek, existingDate) {
  17620. if (isDate(isoWeek)) {
  17621. return isoWeek;
  17622. }
  17623. if (isString(isoWeek)) {
  17624. WEEK_REGEXP.lastIndex = 0;
  17625. var parts = WEEK_REGEXP.exec(isoWeek);
  17626. if (parts) {
  17627. var year = +parts[1],
  17628. week = +parts[2],
  17629. hours = 0,
  17630. minutes = 0,
  17631. seconds = 0,
  17632. milliseconds = 0,
  17633. firstThurs = getFirstThursdayOfYear(year),
  17634. addDays = (week - 1) * 7;
  17635. if (existingDate) {
  17636. hours = existingDate.getHours();
  17637. minutes = existingDate.getMinutes();
  17638. seconds = existingDate.getSeconds();
  17639. milliseconds = existingDate.getMilliseconds();
  17640. }
  17641. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17642. }
  17643. }
  17644. return NaN;
  17645. }
  17646. function createDateParser(regexp, mapping) {
  17647. return function(iso, date) {
  17648. var parts, map;
  17649. if (isDate(iso)) {
  17650. return iso;
  17651. }
  17652. if (isString(iso)) {
  17653. // When a date is JSON'ified to wraps itself inside of an extra
  17654. // set of double quotes. This makes the date parsing code unable
  17655. // to match the date string and parse it as a date.
  17656. if (iso.charAt(0) == '"' && iso.charAt(iso.length-1) == '"') {
  17657. iso = iso.substring(1, iso.length-1);
  17658. }
  17659. if (ISO_DATE_REGEXP.test(iso)) {
  17660. return new Date(iso);
  17661. }
  17662. regexp.lastIndex = 0;
  17663. parts = regexp.exec(iso);
  17664. if (parts) {
  17665. parts.shift();
  17666. if (date) {
  17667. map = {
  17668. yyyy: date.getFullYear(),
  17669. MM: date.getMonth() + 1,
  17670. dd: date.getDate(),
  17671. HH: date.getHours(),
  17672. mm: date.getMinutes(),
  17673. ss: date.getSeconds(),
  17674. sss: date.getMilliseconds() / 1000
  17675. };
  17676. } else {
  17677. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  17678. }
  17679. forEach(parts, function(part, index) {
  17680. if (index < mapping.length) {
  17681. map[mapping[index]] = +part;
  17682. }
  17683. });
  17684. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  17685. }
  17686. }
  17687. return NaN;
  17688. };
  17689. }
  17690. function createDateInputType(type, regexp, parseDate, format) {
  17691. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  17692. badInputChecker(scope, element, attr, ctrl);
  17693. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17694. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  17695. var previousDate;
  17696. ctrl.$$parserName = type;
  17697. ctrl.$parsers.push(function(value) {
  17698. if (ctrl.$isEmpty(value)) return null;
  17699. if (regexp.test(value)) {
  17700. // Note: We cannot read ctrl.$modelValue, as there might be a different
  17701. // parser/formatter in the processing chain so that the model
  17702. // contains some different data format!
  17703. var parsedDate = parseDate(value, previousDate);
  17704. if (timezone === 'UTC') {
  17705. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  17706. }
  17707. return parsedDate;
  17708. }
  17709. return undefined;
  17710. });
  17711. ctrl.$formatters.push(function(value) {
  17712. if (!ctrl.$isEmpty(value)) {
  17713. if (!isDate(value)) {
  17714. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  17715. }
  17716. previousDate = value;
  17717. if (previousDate && timezone === 'UTC') {
  17718. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  17719. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  17720. }
  17721. return $filter('date')(value, format, timezone);
  17722. } else {
  17723. previousDate = null;
  17724. }
  17725. return '';
  17726. });
  17727. if (isDefined(attr.min) || attr.ngMin) {
  17728. var minVal;
  17729. ctrl.$validators.min = function(value) {
  17730. return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  17731. };
  17732. attr.$observe('min', function(val) {
  17733. minVal = parseObservedDateValue(val);
  17734. ctrl.$validate();
  17735. });
  17736. }
  17737. if (isDefined(attr.max) || attr.ngMax) {
  17738. var maxVal;
  17739. ctrl.$validators.max = function(value) {
  17740. return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  17741. };
  17742. attr.$observe('max', function(val) {
  17743. maxVal = parseObservedDateValue(val);
  17744. ctrl.$validate();
  17745. });
  17746. }
  17747. // Override the standard $isEmpty to detect invalid dates as well
  17748. ctrl.$isEmpty = function(value) {
  17749. // Invalid Date: getTime() returns NaN
  17750. return !value || (value.getTime && value.getTime() !== value.getTime());
  17751. };
  17752. function parseObservedDateValue(val) {
  17753. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  17754. }
  17755. };
  17756. }
  17757. function badInputChecker(scope, element, attr, ctrl) {
  17758. var node = element[0];
  17759. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  17760. if (nativeValidation) {
  17761. ctrl.$parsers.push(function(value) {
  17762. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  17763. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  17764. // - also sets validity.badInput (should only be validity.typeMismatch).
  17765. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  17766. // - can ignore this case as we can still read out the erroneous email...
  17767. return validity.badInput && !validity.typeMismatch ? undefined : value;
  17768. });
  17769. }
  17770. }
  17771. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17772. badInputChecker(scope, element, attr, ctrl);
  17773. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17774. ctrl.$$parserName = 'number';
  17775. ctrl.$parsers.push(function(value) {
  17776. if (ctrl.$isEmpty(value)) return null;
  17777. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  17778. return undefined;
  17779. });
  17780. ctrl.$formatters.push(function(value) {
  17781. if (!ctrl.$isEmpty(value)) {
  17782. if (!isNumber(value)) {
  17783. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  17784. }
  17785. value = value.toString();
  17786. }
  17787. return value;
  17788. });
  17789. if (attr.min || attr.ngMin) {
  17790. var minVal;
  17791. ctrl.$validators.min = function(value) {
  17792. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  17793. };
  17794. attr.$observe('min', function(val) {
  17795. if (isDefined(val) && !isNumber(val)) {
  17796. val = parseFloat(val, 10);
  17797. }
  17798. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17799. // TODO(matsko): implement validateLater to reduce number of validations
  17800. ctrl.$validate();
  17801. });
  17802. }
  17803. if (attr.max || attr.ngMax) {
  17804. var maxVal;
  17805. ctrl.$validators.max = function(value) {
  17806. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  17807. };
  17808. attr.$observe('max', function(val) {
  17809. if (isDefined(val) && !isNumber(val)) {
  17810. val = parseFloat(val, 10);
  17811. }
  17812. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17813. // TODO(matsko): implement validateLater to reduce number of validations
  17814. ctrl.$validate();
  17815. });
  17816. }
  17817. }
  17818. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17819. // Note: no badInputChecker here by purpose as `url` is only a validation
  17820. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17821. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17822. stringBasedInputType(ctrl);
  17823. ctrl.$$parserName = 'url';
  17824. ctrl.$validators.url = function(value) {
  17825. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  17826. };
  17827. }
  17828. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17829. // Note: no badInputChecker here by purpose as `url` is only a validation
  17830. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17831. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17832. stringBasedInputType(ctrl);
  17833. ctrl.$$parserName = 'email';
  17834. ctrl.$validators.email = function(value) {
  17835. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  17836. };
  17837. }
  17838. function radioInputType(scope, element, attr, ctrl) {
  17839. // make the name unique, if not defined
  17840. if (isUndefined(attr.name)) {
  17841. element.attr('name', nextUid());
  17842. }
  17843. var listener = function(ev) {
  17844. if (element[0].checked) {
  17845. ctrl.$setViewValue(attr.value, ev && ev.type);
  17846. }
  17847. };
  17848. element.on('click', listener);
  17849. ctrl.$render = function() {
  17850. var value = attr.value;
  17851. element[0].checked = (value == ctrl.$viewValue);
  17852. };
  17853. attr.$observe('value', ctrl.$render);
  17854. }
  17855. function parseConstantExpr($parse, context, name, expression, fallback) {
  17856. var parseFn;
  17857. if (isDefined(expression)) {
  17858. parseFn = $parse(expression);
  17859. if (!parseFn.constant) {
  17860. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  17861. '`{1}`.', name, expression);
  17862. }
  17863. return parseFn(context);
  17864. }
  17865. return fallback;
  17866. }
  17867. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  17868. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  17869. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  17870. var listener = function(ev) {
  17871. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  17872. };
  17873. element.on('click', listener);
  17874. ctrl.$render = function() {
  17875. element[0].checked = ctrl.$viewValue;
  17876. };
  17877. // Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue
  17878. ctrl.$isEmpty = function(value) {
  17879. return value !== trueValue;
  17880. };
  17881. ctrl.$formatters.push(function(value) {
  17882. return equals(value, trueValue);
  17883. });
  17884. ctrl.$parsers.push(function(value) {
  17885. return value ? trueValue : falseValue;
  17886. });
  17887. }
  17888. /**
  17889. * @ngdoc directive
  17890. * @name textarea
  17891. * @restrict E
  17892. *
  17893. * @description
  17894. * HTML textarea element control with angular data-binding. The data-binding and validation
  17895. * properties of this element are exactly the same as those of the
  17896. * {@link ng.directive:input input element}.
  17897. *
  17898. * @param {string} ngModel Assignable angular expression to data-bind to.
  17899. * @param {string=} name Property name of the form under which the control is published.
  17900. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17901. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17902. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17903. * `required` when you want to data-bind to the `required` attribute.
  17904. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17905. * minlength.
  17906. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17907. * maxlength.
  17908. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17909. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17910. * patterns defined as scope expressions.
  17911. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17912. * interaction with the input element.
  17913. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17914. */
  17915. /**
  17916. * @ngdoc directive
  17917. * @name input
  17918. * @restrict E
  17919. *
  17920. * @description
  17921. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  17922. * input state control, and validation.
  17923. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  17924. *
  17925. * <div class="alert alert-warning">
  17926. * **Note:** Not every feature offered is available for all input types.
  17927. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  17928. * </div>
  17929. *
  17930. * @param {string} ngModel Assignable angular expression to data-bind to.
  17931. * @param {string=} name Property name of the form under which the control is published.
  17932. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17933. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  17934. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17935. * minlength.
  17936. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17937. * maxlength.
  17938. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17939. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17940. * patterns defined as scope expressions.
  17941. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17942. * interaction with the input element.
  17943. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17944. * This parameter is ignored for input[type=password] controls, which will never trim the
  17945. * input.
  17946. *
  17947. * @example
  17948. <example name="input-directive" module="inputExample">
  17949. <file name="index.html">
  17950. <script>
  17951. angular.module('inputExample', [])
  17952. .controller('ExampleController', ['$scope', function($scope) {
  17953. $scope.user = {name: 'guest', last: 'visitor'};
  17954. }]);
  17955. </script>
  17956. <div ng-controller="ExampleController">
  17957. <form name="myForm">
  17958. User name: <input type="text" name="userName" ng-model="user.name" required>
  17959. <span class="error" ng-show="myForm.userName.$error.required">
  17960. Required!</span><br>
  17961. Last name: <input type="text" name="lastName" ng-model="user.last"
  17962. ng-minlength="3" ng-maxlength="10">
  17963. <span class="error" ng-show="myForm.lastName.$error.minlength">
  17964. Too short!</span>
  17965. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  17966. Too long!</span><br>
  17967. </form>
  17968. <hr>
  17969. <tt>user = {{user}}</tt><br/>
  17970. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  17971. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  17972. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  17973. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  17974. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  17975. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  17976. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  17977. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  17978. </div>
  17979. </file>
  17980. <file name="protractor.js" type="protractor">
  17981. var user = element(by.exactBinding('user'));
  17982. var userNameValid = element(by.binding('myForm.userName.$valid'));
  17983. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  17984. var lastNameError = element(by.binding('myForm.lastName.$error'));
  17985. var formValid = element(by.binding('myForm.$valid'));
  17986. var userNameInput = element(by.model('user.name'));
  17987. var userLastInput = element(by.model('user.last'));
  17988. it('should initialize to model', function() {
  17989. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  17990. expect(userNameValid.getText()).toContain('true');
  17991. expect(formValid.getText()).toContain('true');
  17992. });
  17993. it('should be invalid if empty when required', function() {
  17994. userNameInput.clear();
  17995. userNameInput.sendKeys('');
  17996. expect(user.getText()).toContain('{"last":"visitor"}');
  17997. expect(userNameValid.getText()).toContain('false');
  17998. expect(formValid.getText()).toContain('false');
  17999. });
  18000. it('should be valid if empty when min length is set', function() {
  18001. userLastInput.clear();
  18002. userLastInput.sendKeys('');
  18003. expect(user.getText()).toContain('{"name":"guest","last":""}');
  18004. expect(lastNameValid.getText()).toContain('true');
  18005. expect(formValid.getText()).toContain('true');
  18006. });
  18007. it('should be invalid if less than required min length', function() {
  18008. userLastInput.clear();
  18009. userLastInput.sendKeys('xx');
  18010. expect(user.getText()).toContain('{"name":"guest"}');
  18011. expect(lastNameValid.getText()).toContain('false');
  18012. expect(lastNameError.getText()).toContain('minlength');
  18013. expect(formValid.getText()).toContain('false');
  18014. });
  18015. it('should be invalid if longer than max length', function() {
  18016. userLastInput.clear();
  18017. userLastInput.sendKeys('some ridiculously long name');
  18018. expect(user.getText()).toContain('{"name":"guest"}');
  18019. expect(lastNameValid.getText()).toContain('false');
  18020. expect(lastNameError.getText()).toContain('maxlength');
  18021. expect(formValid.getText()).toContain('false');
  18022. });
  18023. </file>
  18024. </example>
  18025. */
  18026. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  18027. function($browser, $sniffer, $filter, $parse) {
  18028. return {
  18029. restrict: 'E',
  18030. require: ['?ngModel'],
  18031. link: {
  18032. pre: function(scope, element, attr, ctrls) {
  18033. if (ctrls[0]) {
  18034. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  18035. $browser, $filter, $parse);
  18036. }
  18037. }
  18038. }
  18039. };
  18040. }];
  18041. var VALID_CLASS = 'ng-valid',
  18042. INVALID_CLASS = 'ng-invalid',
  18043. PRISTINE_CLASS = 'ng-pristine',
  18044. DIRTY_CLASS = 'ng-dirty',
  18045. UNTOUCHED_CLASS = 'ng-untouched',
  18046. TOUCHED_CLASS = 'ng-touched',
  18047. PENDING_CLASS = 'ng-pending';
  18048. /**
  18049. * @ngdoc type
  18050. * @name ngModel.NgModelController
  18051. *
  18052. * @property {string} $viewValue Actual string value in the view.
  18053. * @property {*} $modelValue The value in the model that the control is bound to.
  18054. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  18055. the control reads value from the DOM. The functions are called in array order, each passing the value
  18056. through to the next. The last return value is forwarded to the $validators collection.
  18057. Used to sanitize / convert the value.
  18058. Returning undefined from a parser means a parse error occurred. No $validators will
  18059. run and the 'ngModel' will not be updated until the parse error is resolved. The parse error is stored
  18060. in 'ngModel.$error.parse'.
  18061. *
  18062. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  18063. the model value changes. The functions are called in reverse array order, each passing the value through to the
  18064. next. The last return value is used as the actual DOM value.
  18065. Used to format / convert values for display in the control.
  18066. * ```js
  18067. * function formatter(value) {
  18068. * if (value) {
  18069. * return value.toUpperCase();
  18070. * }
  18071. * }
  18072. * ngModel.$formatters.push(formatter);
  18073. * ```
  18074. *
  18075. * @property {Object.<string, function>} $validators A collection of validators that are applied
  18076. * whenever the model value changes. The key value within the object refers to the name of the
  18077. * validator while the function refers to the validation operation. The validation operation is
  18078. * provided with the model value as an argument and must return a true or false value depending
  18079. * on the response of that validation.
  18080. *
  18081. * ```js
  18082. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  18083. * var value = modelValue || viewValue;
  18084. * return /[0-9]+/.test(value) &&
  18085. * /[a-z]+/.test(value) &&
  18086. * /[A-Z]+/.test(value) &&
  18087. * /\W+/.test(value);
  18088. * };
  18089. * ```
  18090. *
  18091. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  18092. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  18093. * is expected to return a promise when it is run during the model validation process. Once the promise
  18094. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  18095. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  18096. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  18097. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  18098. * will only run once all synchronous validators have passed.
  18099. *
  18100. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  18101. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  18102. *
  18103. * ```js
  18104. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  18105. * var value = modelValue || viewValue;
  18106. *
  18107. * // Lookup user by username
  18108. * return $http.get('/api/users/' + value).
  18109. * then(function resolved() {
  18110. * //username exists, this means validation fails
  18111. * return $q.reject('exists');
  18112. * }, function rejected() {
  18113. * //username does not exist, therefore this validation passes
  18114. * return true;
  18115. * });
  18116. * };
  18117. * ```
  18118. *
  18119. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  18120. * view value has changed. It is called with no arguments, and its return value is ignored.
  18121. * This can be used in place of additional $watches against the model value.
  18122. *
  18123. * @property {Object} $error An object hash with all failing validator ids as keys.
  18124. * @property {Object} $pending An object hash with all pending validator ids as keys.
  18125. *
  18126. * @property {boolean} $untouched True if control has not lost focus yet.
  18127. * @property {boolean} $touched True if control has lost focus.
  18128. * @property {boolean} $pristine True if user has not interacted with the control yet.
  18129. * @property {boolean} $dirty True if user has already interacted with the control.
  18130. * @property {boolean} $valid True if there is no error.
  18131. * @property {boolean} $invalid True if at least one error on the control.
  18132. * @property {string} $name The name attribute of the control.
  18133. *
  18134. * @description
  18135. *
  18136. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  18137. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  18138. * purposefully does not contain any logic which deals with DOM rendering or listening to
  18139. * DOM events. Such DOM related logic should be provided by other directives which make use of
  18140. * `NgModelController` for data-binding.
  18141. *
  18142. * ## Custom Control Example
  18143. * This example shows how to use `NgModelController` with a custom control to achieve
  18144. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  18145. * collaborate together to achieve the desired result.
  18146. *
  18147. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  18148. * contents be edited in place by the user. This will not work on older browsers.
  18149. *
  18150. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  18151. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  18152. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  18153. * that content using the `$sce` service.
  18154. *
  18155. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  18156. <file name="style.css">
  18157. [contenteditable] {
  18158. border: 1px solid black;
  18159. background-color: white;
  18160. min-height: 20px;
  18161. }
  18162. .ng-invalid {
  18163. border: 1px solid red;
  18164. }
  18165. </file>
  18166. <file name="script.js">
  18167. angular.module('customControl', ['ngSanitize']).
  18168. directive('contenteditable', ['$sce', function($sce) {
  18169. return {
  18170. restrict: 'A', // only activate on element attribute
  18171. require: '?ngModel', // get a hold of NgModelController
  18172. link: function(scope, element, attrs, ngModel) {
  18173. if (!ngModel) return; // do nothing if no ng-model
  18174. // Specify how UI should be updated
  18175. ngModel.$render = function() {
  18176. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  18177. };
  18178. // Listen for change events to enable binding
  18179. element.on('blur keyup change', function() {
  18180. scope.$apply(read);
  18181. });
  18182. read(); // initialize
  18183. // Write data to the model
  18184. function read() {
  18185. var html = element.html();
  18186. // When we clear the content editable the browser leaves a <br> behind
  18187. // If strip-br attribute is provided then we strip this out
  18188. if ( attrs.stripBr && html == '<br>' ) {
  18189. html = '';
  18190. }
  18191. ngModel.$setViewValue(html);
  18192. }
  18193. }
  18194. };
  18195. }]);
  18196. </file>
  18197. <file name="index.html">
  18198. <form name="myForm">
  18199. <div contenteditable
  18200. name="myWidget" ng-model="userContent"
  18201. strip-br="true"
  18202. required>Change me!</div>
  18203. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  18204. <hr>
  18205. <textarea ng-model="userContent"></textarea>
  18206. </form>
  18207. </file>
  18208. <file name="protractor.js" type="protractor">
  18209. it('should data-bind and become invalid', function() {
  18210. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  18211. // SafariDriver can't handle contenteditable
  18212. // and Firefox driver can't clear contenteditables very well
  18213. return;
  18214. }
  18215. var contentEditable = element(by.css('[contenteditable]'));
  18216. var content = 'Change me!';
  18217. expect(contentEditable.getText()).toEqual(content);
  18218. contentEditable.clear();
  18219. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  18220. expect(contentEditable.getText()).toEqual('');
  18221. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  18222. });
  18223. </file>
  18224. * </example>
  18225. *
  18226. *
  18227. */
  18228. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  18229. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  18230. this.$viewValue = Number.NaN;
  18231. this.$modelValue = Number.NaN;
  18232. this.$validators = {};
  18233. this.$asyncValidators = {};
  18234. this.$parsers = [];
  18235. this.$formatters = [];
  18236. this.$viewChangeListeners = [];
  18237. this.$untouched = true;
  18238. this.$touched = false;
  18239. this.$pristine = true;
  18240. this.$dirty = false;
  18241. this.$valid = true;
  18242. this.$invalid = false;
  18243. this.$error = {}; // keep invalid keys here
  18244. this.$$success = {}; // keep valid keys here
  18245. this.$pending = undefined; // keep pending keys here
  18246. this.$name = $interpolate($attr.name || '', false)($scope);
  18247. var parsedNgModel = $parse($attr.ngModel),
  18248. pendingDebounce = null,
  18249. ctrl = this;
  18250. var ngModelGet = function ngModelGet() {
  18251. var modelValue = parsedNgModel($scope);
  18252. if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) {
  18253. modelValue = modelValue();
  18254. }
  18255. return modelValue;
  18256. };
  18257. var ngModelSet = function ngModelSet(newValue) {
  18258. var getterSetter;
  18259. if (ctrl.$options && ctrl.$options.getterSetter &&
  18260. isFunction(getterSetter = parsedNgModel($scope))) {
  18261. getterSetter(ctrl.$modelValue);
  18262. } else {
  18263. parsedNgModel.assign($scope, ctrl.$modelValue);
  18264. }
  18265. };
  18266. this.$$setOptions = function(options) {
  18267. ctrl.$options = options;
  18268. if (!parsedNgModel.assign && (!options || !options.getterSetter)) {
  18269. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  18270. $attr.ngModel, startingTag($element));
  18271. }
  18272. };
  18273. /**
  18274. * @ngdoc method
  18275. * @name ngModel.NgModelController#$render
  18276. *
  18277. * @description
  18278. * Called when the view needs to be updated. It is expected that the user of the ng-model
  18279. * directive will implement this method.
  18280. *
  18281. * The `$render()` method is invoked in the following situations:
  18282. *
  18283. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  18284. * committed value then `$render()` is called to update the input control.
  18285. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  18286. * the `$viewValue` are different to last time.
  18287. *
  18288. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  18289. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  18290. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  18291. * invoked if you only change a property on the objects.
  18292. */
  18293. this.$render = noop;
  18294. /**
  18295. * @ngdoc method
  18296. * @name ngModel.NgModelController#$isEmpty
  18297. *
  18298. * @description
  18299. * This is called when we need to determine if the value of the input is empty.
  18300. *
  18301. * For instance, the required directive does this to work out if the input has data or not.
  18302. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  18303. *
  18304. * You can override this for input directives whose concept of being empty is different to the
  18305. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  18306. * implies empty.
  18307. *
  18308. * @param {*} value Model value to check.
  18309. * @returns {boolean} True if `value` is empty.
  18310. */
  18311. this.$isEmpty = function(value) {
  18312. return isUndefined(value) || value === '' || value === null || value !== value;
  18313. };
  18314. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  18315. currentValidationRunId = 0;
  18316. /**
  18317. * @ngdoc method
  18318. * @name ngModel.NgModelController#$setValidity
  18319. *
  18320. * @description
  18321. * Change the validity state, and notify the form.
  18322. *
  18323. * This method can be called within $parsers/$formatters or a custom validation implementation.
  18324. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  18325. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  18326. *
  18327. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  18328. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  18329. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  18330. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  18331. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  18332. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  18333. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  18334. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  18335. * Skipped is used by Angular when validators do not run because of parse errors and
  18336. * when `$asyncValidators` do not run because any of the `$validators` failed.
  18337. */
  18338. addSetValidityMethod({
  18339. ctrl: this,
  18340. $element: $element,
  18341. set: function(object, property) {
  18342. object[property] = true;
  18343. },
  18344. unset: function(object, property) {
  18345. delete object[property];
  18346. },
  18347. parentForm: parentForm,
  18348. $animate: $animate
  18349. });
  18350. /**
  18351. * @ngdoc method
  18352. * @name ngModel.NgModelController#$setPristine
  18353. *
  18354. * @description
  18355. * Sets the control to its pristine state.
  18356. *
  18357. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  18358. * state (ng-pristine class). A model is considered to be pristine when the model has not been changed
  18359. * from when first compiled within then form.
  18360. */
  18361. this.$setPristine = function() {
  18362. ctrl.$dirty = false;
  18363. ctrl.$pristine = true;
  18364. $animate.removeClass($element, DIRTY_CLASS);
  18365. $animate.addClass($element, PRISTINE_CLASS);
  18366. };
  18367. /**
  18368. * @ngdoc method
  18369. * @name ngModel.NgModelController#$setUntouched
  18370. *
  18371. * @description
  18372. * Sets the control to its untouched state.
  18373. *
  18374. * This method can be called to remove the 'ng-touched' class and set the control to its
  18375. * untouched state (ng-untouched class). Upon compilation, a model is set as untouched
  18376. * by default, however this function can be used to restore that state if the model has
  18377. * already been touched by the user.
  18378. */
  18379. this.$setUntouched = function() {
  18380. ctrl.$touched = false;
  18381. ctrl.$untouched = true;
  18382. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  18383. };
  18384. /**
  18385. * @ngdoc method
  18386. * @name ngModel.NgModelController#$setTouched
  18387. *
  18388. * @description
  18389. * Sets the control to its touched state.
  18390. *
  18391. * This method can be called to remove the 'ng-untouched' class and set the control to its
  18392. * touched state (ng-touched class). A model is considered to be touched when the user has
  18393. * first interacted (focussed) on the model input element and then shifted focus away (blurred)
  18394. * from the input element.
  18395. */
  18396. this.$setTouched = function() {
  18397. ctrl.$touched = true;
  18398. ctrl.$untouched = false;
  18399. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  18400. };
  18401. /**
  18402. * @ngdoc method
  18403. * @name ngModel.NgModelController#$rollbackViewValue
  18404. *
  18405. * @description
  18406. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  18407. * which may be caused by a pending debounced event or because the input is waiting for a some
  18408. * future event.
  18409. *
  18410. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  18411. * as blur you can have a situation where there is a period when the `$viewValue`
  18412. * is out of synch with the ngModel's `$modelValue`.
  18413. *
  18414. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  18415. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  18416. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  18417. *
  18418. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  18419. * input which may have such events pending. This is important in order to make sure that the
  18420. * input field will be updated with the new model value and any pending operations are cancelled.
  18421. *
  18422. * <example name="ng-model-cancel-update" module="cancel-update-example">
  18423. * <file name="app.js">
  18424. * angular.module('cancel-update-example', [])
  18425. *
  18426. * .controller('CancelUpdateController', ['$scope', function($scope) {
  18427. * $scope.resetWithCancel = function(e) {
  18428. * if (e.keyCode == 27) {
  18429. * $scope.myForm.myInput1.$rollbackViewValue();
  18430. * $scope.myValue = '';
  18431. * }
  18432. * };
  18433. * $scope.resetWithoutCancel = function(e) {
  18434. * if (e.keyCode == 27) {
  18435. * $scope.myValue = '';
  18436. * }
  18437. * };
  18438. * }]);
  18439. * </file>
  18440. * <file name="index.html">
  18441. * <div ng-controller="CancelUpdateController">
  18442. * <p>Try typing something in each input. See that the model only updates when you
  18443. * blur off the input.
  18444. * </p>
  18445. * <p>Now see what happens if you start typing then press the Escape key</p>
  18446. *
  18447. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  18448. * <p>With $rollbackViewValue()</p>
  18449. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  18450. * myValue: "{{ myValue }}"
  18451. *
  18452. * <p>Without $rollbackViewValue()</p>
  18453. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  18454. * myValue: "{{ myValue }}"
  18455. * </form>
  18456. * </div>
  18457. * </file>
  18458. * </example>
  18459. */
  18460. this.$rollbackViewValue = function() {
  18461. $timeout.cancel(pendingDebounce);
  18462. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  18463. ctrl.$render();
  18464. };
  18465. /**
  18466. * @ngdoc method
  18467. * @name ngModel.NgModelController#$validate
  18468. *
  18469. * @description
  18470. * Runs each of the registered validators (first synchronous validators and then asynchronous validators).
  18471. */
  18472. this.$validate = function() {
  18473. // ignore $validate before model is initialized
  18474. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18475. return;
  18476. }
  18477. this.$$parseAndValidate();
  18478. };
  18479. this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
  18480. currentValidationRunId++;
  18481. var localValidationRunId = currentValidationRunId;
  18482. // check parser error
  18483. if (!processParseErrors(parseValid)) {
  18484. validationDone(false);
  18485. return;
  18486. }
  18487. if (!processSyncValidators()) {
  18488. validationDone(false);
  18489. return;
  18490. }
  18491. processAsyncValidators();
  18492. function processParseErrors(parseValid) {
  18493. var errorKey = ctrl.$$parserName || 'parse';
  18494. if (parseValid === undefined) {
  18495. setValidity(errorKey, null);
  18496. } else {
  18497. setValidity(errorKey, parseValid);
  18498. if (!parseValid) {
  18499. forEach(ctrl.$validators, function(v, name) {
  18500. setValidity(name, null);
  18501. });
  18502. forEach(ctrl.$asyncValidators, function(v, name) {
  18503. setValidity(name, null);
  18504. });
  18505. return false;
  18506. }
  18507. }
  18508. return true;
  18509. }
  18510. function processSyncValidators() {
  18511. var syncValidatorsValid = true;
  18512. forEach(ctrl.$validators, function(validator, name) {
  18513. var result = validator(modelValue, viewValue);
  18514. syncValidatorsValid = syncValidatorsValid && result;
  18515. setValidity(name, result);
  18516. });
  18517. if (!syncValidatorsValid) {
  18518. forEach(ctrl.$asyncValidators, function(v, name) {
  18519. setValidity(name, null);
  18520. });
  18521. return false;
  18522. }
  18523. return true;
  18524. }
  18525. function processAsyncValidators() {
  18526. var validatorPromises = [];
  18527. var allValid = true;
  18528. forEach(ctrl.$asyncValidators, function(validator, name) {
  18529. var promise = validator(modelValue, viewValue);
  18530. if (!isPromiseLike(promise)) {
  18531. throw $ngModelMinErr("$asyncValidators",
  18532. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  18533. }
  18534. setValidity(name, undefined);
  18535. validatorPromises.push(promise.then(function() {
  18536. setValidity(name, true);
  18537. }, function(error) {
  18538. allValid = false;
  18539. setValidity(name, false);
  18540. }));
  18541. });
  18542. if (!validatorPromises.length) {
  18543. validationDone(true);
  18544. } else {
  18545. $q.all(validatorPromises).then(function() {
  18546. validationDone(allValid);
  18547. }, noop);
  18548. }
  18549. }
  18550. function setValidity(name, isValid) {
  18551. if (localValidationRunId === currentValidationRunId) {
  18552. ctrl.$setValidity(name, isValid);
  18553. }
  18554. }
  18555. function validationDone(allValid) {
  18556. if (localValidationRunId === currentValidationRunId) {
  18557. doneCallback(allValid);
  18558. }
  18559. }
  18560. };
  18561. /**
  18562. * @ngdoc method
  18563. * @name ngModel.NgModelController#$commitViewValue
  18564. *
  18565. * @description
  18566. * Commit a pending update to the `$modelValue`.
  18567. *
  18568. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18569. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  18570. * usually handles calling this in response to input events.
  18571. */
  18572. this.$commitViewValue = function() {
  18573. var viewValue = ctrl.$viewValue;
  18574. $timeout.cancel(pendingDebounce);
  18575. // If the view value has not changed then we should just exit, except in the case where there is
  18576. // a native validator on the element. In this case the validation state may have changed even though
  18577. // the viewValue has stayed empty.
  18578. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  18579. return;
  18580. }
  18581. ctrl.$$lastCommittedViewValue = viewValue;
  18582. // change to dirty
  18583. if (ctrl.$pristine) {
  18584. ctrl.$dirty = true;
  18585. ctrl.$pristine = false;
  18586. $animate.removeClass($element, PRISTINE_CLASS);
  18587. $animate.addClass($element, DIRTY_CLASS);
  18588. parentForm.$setDirty();
  18589. }
  18590. this.$$parseAndValidate();
  18591. };
  18592. this.$$parseAndValidate = function() {
  18593. var viewValue = ctrl.$$lastCommittedViewValue;
  18594. var modelValue = viewValue;
  18595. var parserValid = isUndefined(modelValue) ? undefined : true;
  18596. if (parserValid) {
  18597. for (var i = 0; i < ctrl.$parsers.length; i++) {
  18598. modelValue = ctrl.$parsers[i](modelValue);
  18599. if (isUndefined(modelValue)) {
  18600. parserValid = false;
  18601. break;
  18602. }
  18603. }
  18604. }
  18605. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18606. // ctrl.$modelValue has not been touched yet...
  18607. ctrl.$modelValue = ngModelGet();
  18608. }
  18609. var prevModelValue = ctrl.$modelValue;
  18610. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18611. if (allowInvalid) {
  18612. ctrl.$modelValue = modelValue;
  18613. writeToModelIfNeeded();
  18614. }
  18615. ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
  18616. if (!allowInvalid) {
  18617. // Note: Don't check ctrl.$valid here, as we could have
  18618. // external validators (e.g. calculated on the server),
  18619. // that just call $setValidity and need the model value
  18620. // to calculate their validity.
  18621. ctrl.$modelValue = allValid ? modelValue : undefined;
  18622. writeToModelIfNeeded();
  18623. }
  18624. });
  18625. function writeToModelIfNeeded() {
  18626. if (ctrl.$modelValue !== prevModelValue) {
  18627. ctrl.$$writeModelToScope();
  18628. }
  18629. }
  18630. };
  18631. this.$$writeModelToScope = function() {
  18632. ngModelSet(ctrl.$modelValue);
  18633. forEach(ctrl.$viewChangeListeners, function(listener) {
  18634. try {
  18635. listener();
  18636. } catch (e) {
  18637. $exceptionHandler(e);
  18638. }
  18639. });
  18640. };
  18641. /**
  18642. * @ngdoc method
  18643. * @name ngModel.NgModelController#$setViewValue
  18644. *
  18645. * @description
  18646. * Update the view value.
  18647. *
  18648. * This method should be called when an input directive want to change the view value; typically,
  18649. * this is done from within a DOM event handler.
  18650. *
  18651. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  18652. * {@link ng.directive:select select} calls it when an option is selected.
  18653. *
  18654. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  18655. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  18656. * watch of objects, it only looks for a change of identity. If you only change the property of
  18657. * the object then ngModel will not realise that the object has changed and will not invoke the
  18658. * `$parsers` and `$validators` pipelines.
  18659. *
  18660. * For this reason, you should not change properties of the copy once it has been passed to
  18661. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  18662. *
  18663. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  18664. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  18665. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  18666. * **expression** specified in the `ng-model` attribute.
  18667. *
  18668. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  18669. *
  18670. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  18671. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  18672. * `updateOn` events is triggered on the DOM element.
  18673. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  18674. * directive is used with a custom debounce for this particular event.
  18675. *
  18676. * Note that calling this function does not trigger a `$digest`.
  18677. *
  18678. * @param {string} value Value from the view.
  18679. * @param {string} trigger Event that triggered the update.
  18680. */
  18681. this.$setViewValue = function(value, trigger) {
  18682. ctrl.$viewValue = value;
  18683. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  18684. ctrl.$$debounceViewValueCommit(trigger);
  18685. }
  18686. };
  18687. this.$$debounceViewValueCommit = function(trigger) {
  18688. var debounceDelay = 0,
  18689. options = ctrl.$options,
  18690. debounce;
  18691. if (options && isDefined(options.debounce)) {
  18692. debounce = options.debounce;
  18693. if (isNumber(debounce)) {
  18694. debounceDelay = debounce;
  18695. } else if (isNumber(debounce[trigger])) {
  18696. debounceDelay = debounce[trigger];
  18697. } else if (isNumber(debounce['default'])) {
  18698. debounceDelay = debounce['default'];
  18699. }
  18700. }
  18701. $timeout.cancel(pendingDebounce);
  18702. if (debounceDelay) {
  18703. pendingDebounce = $timeout(function() {
  18704. ctrl.$commitViewValue();
  18705. }, debounceDelay);
  18706. } else if ($rootScope.$$phase) {
  18707. ctrl.$commitViewValue();
  18708. } else {
  18709. $scope.$apply(function() {
  18710. ctrl.$commitViewValue();
  18711. });
  18712. }
  18713. };
  18714. // model -> value
  18715. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  18716. // 1. scope value is 'a'
  18717. // 2. user enters 'b'
  18718. // 3. ng-change kicks in and reverts scope value to 'a'
  18719. // -> scope value did not change since the last digest as
  18720. // ng-change executes in apply phase
  18721. // 4. view should be changed back to 'a'
  18722. $scope.$watch(function ngModelWatch() {
  18723. var modelValue = ngModelGet();
  18724. // if scope model value and ngModel value are out of sync
  18725. // TODO(perf): why not move this to the action fn?
  18726. if (modelValue !== ctrl.$modelValue) {
  18727. ctrl.$modelValue = modelValue;
  18728. var formatters = ctrl.$formatters,
  18729. idx = formatters.length;
  18730. var viewValue = modelValue;
  18731. while (idx--) {
  18732. viewValue = formatters[idx](viewValue);
  18733. }
  18734. if (ctrl.$viewValue !== viewValue) {
  18735. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  18736. ctrl.$render();
  18737. ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
  18738. }
  18739. }
  18740. return modelValue;
  18741. });
  18742. }];
  18743. /**
  18744. * @ngdoc directive
  18745. * @name ngModel
  18746. *
  18747. * @element input
  18748. * @priority 1
  18749. *
  18750. * @description
  18751. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  18752. * property on the scope using {@link ngModel.NgModelController NgModelController},
  18753. * which is created and exposed by this directive.
  18754. *
  18755. * `ngModel` is responsible for:
  18756. *
  18757. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  18758. * require.
  18759. * - Providing validation behavior (i.e. required, number, email, url).
  18760. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  18761. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  18762. * - Registering the control with its parent {@link ng.directive:form form}.
  18763. *
  18764. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  18765. * current scope. If the property doesn't already exist on this scope, it will be created
  18766. * implicitly and added to the scope.
  18767. *
  18768. * For best practices on using `ngModel`, see:
  18769. *
  18770. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  18771. *
  18772. * For basic examples, how to use `ngModel`, see:
  18773. *
  18774. * - {@link ng.directive:input input}
  18775. * - {@link input[text] text}
  18776. * - {@link input[checkbox] checkbox}
  18777. * - {@link input[radio] radio}
  18778. * - {@link input[number] number}
  18779. * - {@link input[email] email}
  18780. * - {@link input[url] url}
  18781. * - {@link input[date] date}
  18782. * - {@link input[datetime-local] datetime-local}
  18783. * - {@link input[time] time}
  18784. * - {@link input[month] month}
  18785. * - {@link input[week] week}
  18786. * - {@link ng.directive:select select}
  18787. * - {@link ng.directive:textarea textarea}
  18788. *
  18789. * # CSS classes
  18790. * The following CSS classes are added and removed on the associated input/select/textarea element
  18791. * depending on the validity of the model.
  18792. *
  18793. * - `ng-valid`: the model is valid
  18794. * - `ng-invalid`: the model is invalid
  18795. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  18796. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  18797. * - `ng-pristine`: the control hasn't been interacted with yet
  18798. * - `ng-dirty`: the control has been interacted with
  18799. * - `ng-touched`: the control has been blurred
  18800. * - `ng-untouched`: the control hasn't been blurred
  18801. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  18802. *
  18803. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18804. *
  18805. * ## Animation Hooks
  18806. *
  18807. * Animations within models are triggered when any of the associated CSS classes are added and removed
  18808. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  18809. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  18810. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  18811. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  18812. *
  18813. * The following example shows a simple way to utilize CSS transitions to style an input element
  18814. * that has been rendered as invalid after it has been validated:
  18815. *
  18816. * <pre>
  18817. * //be sure to include ngAnimate as a module to hook into more
  18818. * //advanced animations
  18819. * .my-input {
  18820. * transition:0.5s linear all;
  18821. * background: white;
  18822. * }
  18823. * .my-input.ng-invalid {
  18824. * background: red;
  18825. * color:white;
  18826. * }
  18827. * </pre>
  18828. *
  18829. * @example
  18830. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  18831. <file name="index.html">
  18832. <script>
  18833. angular.module('inputExample', [])
  18834. .controller('ExampleController', ['$scope', function($scope) {
  18835. $scope.val = '1';
  18836. }]);
  18837. </script>
  18838. <style>
  18839. .my-input {
  18840. -webkit-transition:all linear 0.5s;
  18841. transition:all linear 0.5s;
  18842. background: transparent;
  18843. }
  18844. .my-input.ng-invalid {
  18845. color:white;
  18846. background: red;
  18847. }
  18848. </style>
  18849. Update input to see transitions when valid/invalid.
  18850. Integer is a valid value.
  18851. <form name="testForm" ng-controller="ExampleController">
  18852. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  18853. </form>
  18854. </file>
  18855. * </example>
  18856. *
  18857. * ## Binding to a getter/setter
  18858. *
  18859. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  18860. * function that returns a representation of the model when called with zero arguments, and sets
  18861. * the internal state of a model when called with an argument. It's sometimes useful to use this
  18862. * for models that have an internal representation that's different than what the model exposes
  18863. * to the view.
  18864. *
  18865. * <div class="alert alert-success">
  18866. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  18867. * frequently than other parts of your code.
  18868. * </div>
  18869. *
  18870. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  18871. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  18872. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  18873. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  18874. *
  18875. * The following example shows how to use `ngModel` with a getter/setter:
  18876. *
  18877. * @example
  18878. * <example name="ngModel-getter-setter" module="getterSetterExample">
  18879. <file name="index.html">
  18880. <div ng-controller="ExampleController">
  18881. <form name="userForm">
  18882. Name:
  18883. <input type="text" name="userName"
  18884. ng-model="user.name"
  18885. ng-model-options="{ getterSetter: true }" />
  18886. </form>
  18887. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  18888. </div>
  18889. </file>
  18890. <file name="app.js">
  18891. angular.module('getterSetterExample', [])
  18892. .controller('ExampleController', ['$scope', function($scope) {
  18893. var _name = 'Brian';
  18894. $scope.user = {
  18895. name: function(newName) {
  18896. if (angular.isDefined(newName)) {
  18897. _name = newName;
  18898. }
  18899. return _name;
  18900. }
  18901. };
  18902. }]);
  18903. </file>
  18904. * </example>
  18905. */
  18906. var ngModelDirective = function() {
  18907. return {
  18908. restrict: 'A',
  18909. require: ['ngModel', '^?form', '^?ngModelOptions'],
  18910. controller: NgModelController,
  18911. // Prelink needs to run before any input directive
  18912. // so that we can set the NgModelOptions in NgModelController
  18913. // before anyone else uses it.
  18914. priority: 1,
  18915. compile: function ngModelCompile(element) {
  18916. // Setup initial state of the control
  18917. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  18918. return {
  18919. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  18920. var modelCtrl = ctrls[0],
  18921. formCtrl = ctrls[1] || nullFormCtrl;
  18922. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  18923. // notify others, especially parent forms
  18924. formCtrl.$addControl(modelCtrl);
  18925. attr.$observe('name', function(newValue) {
  18926. if (modelCtrl.$name !== newValue) {
  18927. formCtrl.$$renameControl(modelCtrl, newValue);
  18928. }
  18929. });
  18930. scope.$on('$destroy', function() {
  18931. formCtrl.$removeControl(modelCtrl);
  18932. });
  18933. },
  18934. post: function ngModelPostLink(scope, element, attr, ctrls) {
  18935. var modelCtrl = ctrls[0];
  18936. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  18937. element.on(modelCtrl.$options.updateOn, function(ev) {
  18938. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  18939. });
  18940. }
  18941. element.on('blur', function(ev) {
  18942. if (modelCtrl.$touched) return;
  18943. scope.$apply(function() {
  18944. modelCtrl.$setTouched();
  18945. });
  18946. });
  18947. }
  18948. };
  18949. }
  18950. };
  18951. };
  18952. /**
  18953. * @ngdoc directive
  18954. * @name ngChange
  18955. *
  18956. * @description
  18957. * Evaluate the given expression when the user changes the input.
  18958. * The expression is evaluated immediately, unlike the JavaScript onchange event
  18959. * which only triggers at the end of a change (usually, when the user leaves the
  18960. * form element or presses the return key).
  18961. *
  18962. * The `ngChange` expression is only evaluated when a change in the input value causes
  18963. * a new value to be committed to the model.
  18964. *
  18965. * It will not be evaluated:
  18966. * * if the value returned from the `$parsers` transformation pipeline has not changed
  18967. * * if the input has continued to be invalid since the model will stay `null`
  18968. * * if the model is changed programmatically and not by a change to the input value
  18969. *
  18970. *
  18971. * Note, this directive requires `ngModel` to be present.
  18972. *
  18973. * @element input
  18974. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  18975. * in input value.
  18976. *
  18977. * @example
  18978. * <example name="ngChange-directive" module="changeExample">
  18979. * <file name="index.html">
  18980. * <script>
  18981. * angular.module('changeExample', [])
  18982. * .controller('ExampleController', ['$scope', function($scope) {
  18983. * $scope.counter = 0;
  18984. * $scope.change = function() {
  18985. * $scope.counter++;
  18986. * };
  18987. * }]);
  18988. * </script>
  18989. * <div ng-controller="ExampleController">
  18990. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  18991. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  18992. * <label for="ng-change-example2">Confirmed</label><br />
  18993. * <tt>debug = {{confirmed}}</tt><br/>
  18994. * <tt>counter = {{counter}}</tt><br/>
  18995. * </div>
  18996. * </file>
  18997. * <file name="protractor.js" type="protractor">
  18998. * var counter = element(by.binding('counter'));
  18999. * var debug = element(by.binding('confirmed'));
  19000. *
  19001. * it('should evaluate the expression if changing from view', function() {
  19002. * expect(counter.getText()).toContain('0');
  19003. *
  19004. * element(by.id('ng-change-example1')).click();
  19005. *
  19006. * expect(counter.getText()).toContain('1');
  19007. * expect(debug.getText()).toContain('true');
  19008. * });
  19009. *
  19010. * it('should not evaluate the expression if changing from model', function() {
  19011. * element(by.id('ng-change-example2')).click();
  19012. * expect(counter.getText()).toContain('0');
  19013. * expect(debug.getText()).toContain('true');
  19014. * });
  19015. * </file>
  19016. * </example>
  19017. */
  19018. var ngChangeDirective = valueFn({
  19019. restrict: 'A',
  19020. require: 'ngModel',
  19021. link: function(scope, element, attr, ctrl) {
  19022. ctrl.$viewChangeListeners.push(function() {
  19023. scope.$eval(attr.ngChange);
  19024. });
  19025. }
  19026. });
  19027. var requiredDirective = function() {
  19028. return {
  19029. restrict: 'A',
  19030. require: '?ngModel',
  19031. link: function(scope, elm, attr, ctrl) {
  19032. if (!ctrl) return;
  19033. attr.required = true; // force truthy in case we are on non input element
  19034. ctrl.$validators.required = function(value) {
  19035. return !attr.required || !ctrl.$isEmpty(value);
  19036. };
  19037. attr.$observe('required', function() {
  19038. ctrl.$validate();
  19039. });
  19040. }
  19041. };
  19042. };
  19043. var patternDirective = function() {
  19044. return {
  19045. restrict: 'A',
  19046. require: '?ngModel',
  19047. link: function(scope, elm, attr, ctrl) {
  19048. if (!ctrl) return;
  19049. var regexp, patternExp = attr.ngPattern || attr.pattern;
  19050. attr.$observe('pattern', function(regex) {
  19051. if (isString(regex) && regex.length > 0) {
  19052. regex = new RegExp(regex);
  19053. }
  19054. if (regex && !regex.test) {
  19055. throw minErr('ngPattern')('noregexp',
  19056. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  19057. regex, startingTag(elm));
  19058. }
  19059. regexp = regex || undefined;
  19060. ctrl.$validate();
  19061. });
  19062. ctrl.$validators.pattern = function(value) {
  19063. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  19064. };
  19065. }
  19066. };
  19067. };
  19068. var maxlengthDirective = function() {
  19069. return {
  19070. restrict: 'A',
  19071. require: '?ngModel',
  19072. link: function(scope, elm, attr, ctrl) {
  19073. if (!ctrl) return;
  19074. var maxlength = 0;
  19075. attr.$observe('maxlength', function(value) {
  19076. maxlength = int(value) || 0;
  19077. ctrl.$validate();
  19078. });
  19079. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  19080. return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength;
  19081. };
  19082. }
  19083. };
  19084. };
  19085. var minlengthDirective = function() {
  19086. return {
  19087. restrict: 'A',
  19088. require: '?ngModel',
  19089. link: function(scope, elm, attr, ctrl) {
  19090. if (!ctrl) return;
  19091. var minlength = 0;
  19092. attr.$observe('minlength', function(value) {
  19093. minlength = int(value) || 0;
  19094. ctrl.$validate();
  19095. });
  19096. ctrl.$validators.minlength = function(modelValue, viewValue) {
  19097. return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength;
  19098. };
  19099. }
  19100. };
  19101. };
  19102. /**
  19103. * @ngdoc directive
  19104. * @name ngList
  19105. *
  19106. * @description
  19107. * Text input that converts between a delimited string and an array of strings. The default
  19108. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  19109. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  19110. *
  19111. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  19112. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  19113. * list item is respected. This implies that the user of the directive is responsible for
  19114. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  19115. * tab or newline character.
  19116. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  19117. * when joining the list items back together) and whitespace around each list item is stripped
  19118. * before it is added to the model.
  19119. *
  19120. * ### Example with Validation
  19121. *
  19122. * <example name="ngList-directive" module="listExample">
  19123. * <file name="app.js">
  19124. * angular.module('listExample', [])
  19125. * .controller('ExampleController', ['$scope', function($scope) {
  19126. * $scope.names = ['morpheus', 'neo', 'trinity'];
  19127. * }]);
  19128. * </file>
  19129. * <file name="index.html">
  19130. * <form name="myForm" ng-controller="ExampleController">
  19131. * List: <input name="namesInput" ng-model="names" ng-list required>
  19132. * <span class="error" ng-show="myForm.namesInput.$error.required">
  19133. * Required!</span>
  19134. * <br>
  19135. * <tt>names = {{names}}</tt><br/>
  19136. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  19137. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  19138. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19139. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19140. * </form>
  19141. * </file>
  19142. * <file name="protractor.js" type="protractor">
  19143. * var listInput = element(by.model('names'));
  19144. * var names = element(by.exactBinding('names'));
  19145. * var valid = element(by.binding('myForm.namesInput.$valid'));
  19146. * var error = element(by.css('span.error'));
  19147. *
  19148. * it('should initialize to model', function() {
  19149. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  19150. * expect(valid.getText()).toContain('true');
  19151. * expect(error.getCssValue('display')).toBe('none');
  19152. * });
  19153. *
  19154. * it('should be invalid if empty', function() {
  19155. * listInput.clear();
  19156. * listInput.sendKeys('');
  19157. *
  19158. * expect(names.getText()).toContain('');
  19159. * expect(valid.getText()).toContain('false');
  19160. * expect(error.getCssValue('display')).not.toBe('none');
  19161. * });
  19162. * </file>
  19163. * </example>
  19164. *
  19165. * ### Example - splitting on whitespace
  19166. * <example name="ngList-directive-newlines">
  19167. * <file name="index.html">
  19168. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  19169. * <pre>{{ list | json }}</pre>
  19170. * </file>
  19171. * <file name="protractor.js" type="protractor">
  19172. * it("should split the text by newlines", function() {
  19173. * var listInput = element(by.model('list'));
  19174. * var output = element(by.binding('list | json'));
  19175. * listInput.sendKeys('abc\ndef\nghi');
  19176. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  19177. * });
  19178. * </file>
  19179. * </example>
  19180. *
  19181. * @element input
  19182. * @param {string=} ngList optional delimiter that should be used to split the value.
  19183. */
  19184. var ngListDirective = function() {
  19185. return {
  19186. restrict: 'A',
  19187. priority: 100,
  19188. require: 'ngModel',
  19189. link: function(scope, element, attr, ctrl) {
  19190. // We want to control whitespace trimming so we use this convoluted approach
  19191. // to access the ngList attribute, which doesn't pre-trim the attribute
  19192. var ngList = element.attr(attr.$attr.ngList) || ', ';
  19193. var trimValues = attr.ngTrim !== 'false';
  19194. var separator = trimValues ? trim(ngList) : ngList;
  19195. var parse = function(viewValue) {
  19196. // If the viewValue is invalid (say required but empty) it will be `undefined`
  19197. if (isUndefined(viewValue)) return;
  19198. var list = [];
  19199. if (viewValue) {
  19200. forEach(viewValue.split(separator), function(value) {
  19201. if (value) list.push(trimValues ? trim(value) : value);
  19202. });
  19203. }
  19204. return list;
  19205. };
  19206. ctrl.$parsers.push(parse);
  19207. ctrl.$formatters.push(function(value) {
  19208. if (isArray(value)) {
  19209. return value.join(ngList);
  19210. }
  19211. return undefined;
  19212. });
  19213. // Override the standard $isEmpty because an empty array means the input is empty.
  19214. ctrl.$isEmpty = function(value) {
  19215. return !value || !value.length;
  19216. };
  19217. }
  19218. };
  19219. };
  19220. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19221. /**
  19222. * @ngdoc directive
  19223. * @name ngValue
  19224. *
  19225. * @description
  19226. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  19227. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  19228. * the bound value.
  19229. *
  19230. * `ngValue` is useful when dynamically generating lists of radio buttons using
  19231. * {@link ngRepeat `ngRepeat`}, as shown below.
  19232. *
  19233. * Likewise, `ngValue` can be used to generate `<option>` elements for
  19234. * the {@link select `select`} element. In that case however, only strings are supported
  19235. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  19236. * Support for `select` models with non-string values is available via `ngOptions`.
  19237. *
  19238. * @element input
  19239. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19240. * of the `input` element
  19241. *
  19242. * @example
  19243. <example name="ngValue-directive" module="valueExample">
  19244. <file name="index.html">
  19245. <script>
  19246. angular.module('valueExample', [])
  19247. .controller('ExampleController', ['$scope', function($scope) {
  19248. $scope.names = ['pizza', 'unicorns', 'robots'];
  19249. $scope.my = { favorite: 'unicorns' };
  19250. }]);
  19251. </script>
  19252. <form ng-controller="ExampleController">
  19253. <h2>Which is your favorite?</h2>
  19254. <label ng-repeat="name in names" for="{{name}}">
  19255. {{name}}
  19256. <input type="radio"
  19257. ng-model="my.favorite"
  19258. ng-value="name"
  19259. id="{{name}}"
  19260. name="favorite">
  19261. </label>
  19262. <div>You chose {{my.favorite}}</div>
  19263. </form>
  19264. </file>
  19265. <file name="protractor.js" type="protractor">
  19266. var favorite = element(by.binding('my.favorite'));
  19267. it('should initialize to model', function() {
  19268. expect(favorite.getText()).toContain('unicorns');
  19269. });
  19270. it('should bind the values to the inputs', function() {
  19271. element.all(by.model('my.favorite')).get(0).click();
  19272. expect(favorite.getText()).toContain('pizza');
  19273. });
  19274. </file>
  19275. </example>
  19276. */
  19277. var ngValueDirective = function() {
  19278. return {
  19279. restrict: 'A',
  19280. priority: 100,
  19281. compile: function(tpl, tplAttr) {
  19282. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  19283. return function ngValueConstantLink(scope, elm, attr) {
  19284. attr.$set('value', scope.$eval(attr.ngValue));
  19285. };
  19286. } else {
  19287. return function ngValueLink(scope, elm, attr) {
  19288. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  19289. attr.$set('value', value);
  19290. });
  19291. };
  19292. }
  19293. }
  19294. };
  19295. };
  19296. /**
  19297. * @ngdoc directive
  19298. * @name ngModelOptions
  19299. *
  19300. * @description
  19301. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  19302. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  19303. * takes place when a timer expires; this timer will be reset after another change takes place.
  19304. *
  19305. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  19306. * be different than the value in the actual model. This means that if you update the model you
  19307. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  19308. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  19309. *
  19310. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  19311. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  19312. * important because `form` controllers are published to the related scope under the name in their
  19313. * `name` attribute.
  19314. *
  19315. * Any pending changes will take place immediately when an enclosing form is submitted via the
  19316. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19317. * to have access to the updated model.
  19318. *
  19319. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  19320. *
  19321. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  19322. * - `updateOn`: string specifying which event should be the input bound to. You can set several
  19323. * events using an space delimited list. There is a special event called `default` that
  19324. * matches the default events belonging of the control.
  19325. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  19326. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  19327. * custom value for each event. For example:
  19328. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  19329. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  19330. * not validate correctly instead of the default behavior of setting the model to undefined.
  19331. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  19332. `ngModel` as getters/setters.
  19333. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  19334. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  19335. * otherwise the default timezone of the browser will be used.
  19336. *
  19337. * @example
  19338. The following example shows how to override immediate updates. Changes on the inputs within the
  19339. form will update the model only when the control loses focus (blur event). If `escape` key is
  19340. pressed while the input field is focused, the value is reset to the value in the current model.
  19341. <example name="ngModelOptions-directive-blur" module="optionsExample">
  19342. <file name="index.html">
  19343. <div ng-controller="ExampleController">
  19344. <form name="userForm">
  19345. Name:
  19346. <input type="text" name="userName"
  19347. ng-model="user.name"
  19348. ng-model-options="{ updateOn: 'blur' }"
  19349. ng-keyup="cancel($event)" /><br />
  19350. Other data:
  19351. <input type="text" ng-model="user.data" /><br />
  19352. </form>
  19353. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19354. </div>
  19355. </file>
  19356. <file name="app.js">
  19357. angular.module('optionsExample', [])
  19358. .controller('ExampleController', ['$scope', function($scope) {
  19359. $scope.user = { name: 'say', data: '' };
  19360. $scope.cancel = function(e) {
  19361. if (e.keyCode == 27) {
  19362. $scope.userForm.userName.$rollbackViewValue();
  19363. }
  19364. };
  19365. }]);
  19366. </file>
  19367. <file name="protractor.js" type="protractor">
  19368. var model = element(by.binding('user.name'));
  19369. var input = element(by.model('user.name'));
  19370. var other = element(by.model('user.data'));
  19371. it('should allow custom events', function() {
  19372. input.sendKeys(' hello');
  19373. input.click();
  19374. expect(model.getText()).toEqual('say');
  19375. other.click();
  19376. expect(model.getText()).toEqual('say hello');
  19377. });
  19378. it('should $rollbackViewValue when model changes', function() {
  19379. input.sendKeys(' hello');
  19380. expect(input.getAttribute('value')).toEqual('say hello');
  19381. input.sendKeys(protractor.Key.ESCAPE);
  19382. expect(input.getAttribute('value')).toEqual('say');
  19383. other.click();
  19384. expect(model.getText()).toEqual('say');
  19385. });
  19386. </file>
  19387. </example>
  19388. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  19389. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  19390. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  19391. <file name="index.html">
  19392. <div ng-controller="ExampleController">
  19393. <form name="userForm">
  19394. Name:
  19395. <input type="text" name="userName"
  19396. ng-model="user.name"
  19397. ng-model-options="{ debounce: 1000 }" />
  19398. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  19399. </form>
  19400. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19401. </div>
  19402. </file>
  19403. <file name="app.js">
  19404. angular.module('optionsExample', [])
  19405. .controller('ExampleController', ['$scope', function($scope) {
  19406. $scope.user = { name: 'say' };
  19407. }]);
  19408. </file>
  19409. </example>
  19410. This one shows how to bind to getter/setters:
  19411. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  19412. <file name="index.html">
  19413. <div ng-controller="ExampleController">
  19414. <form name="userForm">
  19415. Name:
  19416. <input type="text" name="userName"
  19417. ng-model="user.name"
  19418. ng-model-options="{ getterSetter: true }" />
  19419. </form>
  19420. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19421. </div>
  19422. </file>
  19423. <file name="app.js">
  19424. angular.module('getterSetterExample', [])
  19425. .controller('ExampleController', ['$scope', function($scope) {
  19426. var _name = 'Brian';
  19427. $scope.user = {
  19428. name: function(newName) {
  19429. return angular.isDefined(newName) ? (_name = newName) : _name;
  19430. }
  19431. };
  19432. }]);
  19433. </file>
  19434. </example>
  19435. */
  19436. var ngModelOptionsDirective = function() {
  19437. return {
  19438. restrict: 'A',
  19439. controller: ['$scope', '$attrs', function($scope, $attrs) {
  19440. var that = this;
  19441. this.$options = $scope.$eval($attrs.ngModelOptions);
  19442. // Allow adding/overriding bound events
  19443. if (this.$options.updateOn !== undefined) {
  19444. this.$options.updateOnDefault = false;
  19445. // extract "default" pseudo-event from list of events that can trigger a model update
  19446. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  19447. that.$options.updateOnDefault = true;
  19448. return ' ';
  19449. }));
  19450. } else {
  19451. this.$options.updateOnDefault = true;
  19452. }
  19453. }]
  19454. };
  19455. };
  19456. // helper methods
  19457. function addSetValidityMethod(context) {
  19458. var ctrl = context.ctrl,
  19459. $element = context.$element,
  19460. classCache = {},
  19461. set = context.set,
  19462. unset = context.unset,
  19463. parentForm = context.parentForm,
  19464. $animate = context.$animate;
  19465. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  19466. ctrl.$setValidity = setValidity;
  19467. function setValidity(validationErrorKey, state, options) {
  19468. if (state === undefined) {
  19469. createAndSet('$pending', validationErrorKey, options);
  19470. } else {
  19471. unsetAndCleanup('$pending', validationErrorKey, options);
  19472. }
  19473. if (!isBoolean(state)) {
  19474. unset(ctrl.$error, validationErrorKey, options);
  19475. unset(ctrl.$$success, validationErrorKey, options);
  19476. } else {
  19477. if (state) {
  19478. unset(ctrl.$error, validationErrorKey, options);
  19479. set(ctrl.$$success, validationErrorKey, options);
  19480. } else {
  19481. set(ctrl.$error, validationErrorKey, options);
  19482. unset(ctrl.$$success, validationErrorKey, options);
  19483. }
  19484. }
  19485. if (ctrl.$pending) {
  19486. cachedToggleClass(PENDING_CLASS, true);
  19487. ctrl.$valid = ctrl.$invalid = undefined;
  19488. toggleValidationCss('', null);
  19489. } else {
  19490. cachedToggleClass(PENDING_CLASS, false);
  19491. ctrl.$valid = isObjectEmpty(ctrl.$error);
  19492. ctrl.$invalid = !ctrl.$valid;
  19493. toggleValidationCss('', ctrl.$valid);
  19494. }
  19495. // re-read the state as the set/unset methods could have
  19496. // combined state in ctrl.$error[validationError] (used for forms),
  19497. // where setting/unsetting only increments/decrements the value,
  19498. // and does not replace it.
  19499. var combinedState;
  19500. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  19501. combinedState = undefined;
  19502. } else if (ctrl.$error[validationErrorKey]) {
  19503. combinedState = false;
  19504. } else if (ctrl.$$success[validationErrorKey]) {
  19505. combinedState = true;
  19506. } else {
  19507. combinedState = null;
  19508. }
  19509. toggleValidationCss(validationErrorKey, combinedState);
  19510. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  19511. }
  19512. function createAndSet(name, value, options) {
  19513. if (!ctrl[name]) {
  19514. ctrl[name] = {};
  19515. }
  19516. set(ctrl[name], value, options);
  19517. }
  19518. function unsetAndCleanup(name, value, options) {
  19519. if (ctrl[name]) {
  19520. unset(ctrl[name], value, options);
  19521. }
  19522. if (isObjectEmpty(ctrl[name])) {
  19523. ctrl[name] = undefined;
  19524. }
  19525. }
  19526. function cachedToggleClass(className, switchValue) {
  19527. if (switchValue && !classCache[className]) {
  19528. $animate.addClass($element, className);
  19529. classCache[className] = true;
  19530. } else if (!switchValue && classCache[className]) {
  19531. $animate.removeClass($element, className);
  19532. classCache[className] = false;
  19533. }
  19534. }
  19535. function toggleValidationCss(validationErrorKey, isValid) {
  19536. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  19537. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  19538. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  19539. }
  19540. }
  19541. function isObjectEmpty(obj) {
  19542. if (obj) {
  19543. for (var prop in obj) {
  19544. return false;
  19545. }
  19546. }
  19547. return true;
  19548. }
  19549. /**
  19550. * @ngdoc directive
  19551. * @name ngBind
  19552. * @restrict AC
  19553. *
  19554. * @description
  19555. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  19556. * with the value of a given expression, and to update the text content when the value of that
  19557. * expression changes.
  19558. *
  19559. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  19560. * `{{ expression }}` which is similar but less verbose.
  19561. *
  19562. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  19563. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  19564. * element attribute, it makes the bindings invisible to the user while the page is loading.
  19565. *
  19566. * An alternative solution to this problem would be using the
  19567. * {@link ng.directive:ngCloak ngCloak} directive.
  19568. *
  19569. *
  19570. * @element ANY
  19571. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  19572. *
  19573. * @example
  19574. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  19575. <example module="bindExample">
  19576. <file name="index.html">
  19577. <script>
  19578. angular.module('bindExample', [])
  19579. .controller('ExampleController', ['$scope', function($scope) {
  19580. $scope.name = 'Whirled';
  19581. }]);
  19582. </script>
  19583. <div ng-controller="ExampleController">
  19584. Enter name: <input type="text" ng-model="name"><br>
  19585. Hello <span ng-bind="name"></span>!
  19586. </div>
  19587. </file>
  19588. <file name="protractor.js" type="protractor">
  19589. it('should check ng-bind', function() {
  19590. var nameInput = element(by.model('name'));
  19591. expect(element(by.binding('name')).getText()).toBe('Whirled');
  19592. nameInput.clear();
  19593. nameInput.sendKeys('world');
  19594. expect(element(by.binding('name')).getText()).toBe('world');
  19595. });
  19596. </file>
  19597. </example>
  19598. */
  19599. var ngBindDirective = ['$compile', function($compile) {
  19600. return {
  19601. restrict: 'AC',
  19602. compile: function ngBindCompile(templateElement) {
  19603. $compile.$$addBindingClass(templateElement);
  19604. return function ngBindLink(scope, element, attr) {
  19605. $compile.$$addBindingInfo(element, attr.ngBind);
  19606. element = element[0];
  19607. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  19608. element.textContent = value === undefined ? '' : value;
  19609. });
  19610. };
  19611. }
  19612. };
  19613. }];
  19614. /**
  19615. * @ngdoc directive
  19616. * @name ngBindTemplate
  19617. *
  19618. * @description
  19619. * The `ngBindTemplate` directive specifies that the element
  19620. * text content should be replaced with the interpolation of the template
  19621. * in the `ngBindTemplate` attribute.
  19622. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  19623. * expressions. This directive is needed since some HTML elements
  19624. * (such as TITLE and OPTION) cannot contain SPAN elements.
  19625. *
  19626. * @element ANY
  19627. * @param {string} ngBindTemplate template of form
  19628. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  19629. *
  19630. * @example
  19631. * Try it here: enter text in text box and watch the greeting change.
  19632. <example module="bindExample">
  19633. <file name="index.html">
  19634. <script>
  19635. angular.module('bindExample', [])
  19636. .controller('ExampleController', ['$scope', function($scope) {
  19637. $scope.salutation = 'Hello';
  19638. $scope.name = 'World';
  19639. }]);
  19640. </script>
  19641. <div ng-controller="ExampleController">
  19642. Salutation: <input type="text" ng-model="salutation"><br>
  19643. Name: <input type="text" ng-model="name"><br>
  19644. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  19645. </div>
  19646. </file>
  19647. <file name="protractor.js" type="protractor">
  19648. it('should check ng-bind', function() {
  19649. var salutationElem = element(by.binding('salutation'));
  19650. var salutationInput = element(by.model('salutation'));
  19651. var nameInput = element(by.model('name'));
  19652. expect(salutationElem.getText()).toBe('Hello World!');
  19653. salutationInput.clear();
  19654. salutationInput.sendKeys('Greetings');
  19655. nameInput.clear();
  19656. nameInput.sendKeys('user');
  19657. expect(salutationElem.getText()).toBe('Greetings user!');
  19658. });
  19659. </file>
  19660. </example>
  19661. */
  19662. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  19663. return {
  19664. compile: function ngBindTemplateCompile(templateElement) {
  19665. $compile.$$addBindingClass(templateElement);
  19666. return function ngBindTemplateLink(scope, element, attr) {
  19667. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  19668. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  19669. element = element[0];
  19670. attr.$observe('ngBindTemplate', function(value) {
  19671. element.textContent = value === undefined ? '' : value;
  19672. });
  19673. };
  19674. }
  19675. };
  19676. }];
  19677. /**
  19678. * @ngdoc directive
  19679. * @name ngBindHtml
  19680. *
  19681. * @description
  19682. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  19683. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  19684. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  19685. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  19686. * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
  19687. * include "angular-sanitize.js" in your application.
  19688. *
  19689. * You may also bypass sanitization for values you know are safe. To do so, bind to
  19690. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  19691. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  19692. *
  19693. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  19694. * will have an exception (instead of an exploit.)
  19695. *
  19696. * @element ANY
  19697. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  19698. *
  19699. * @example
  19700. <example module="bindHtmlExample" deps="angular-sanitize.js">
  19701. <file name="index.html">
  19702. <div ng-controller="ExampleController">
  19703. <p ng-bind-html="myHTML"></p>
  19704. </div>
  19705. </file>
  19706. <file name="script.js">
  19707. angular.module('bindHtmlExample', ['ngSanitize'])
  19708. .controller('ExampleController', ['$scope', function($scope) {
  19709. $scope.myHTML =
  19710. 'I am an <code>HTML</code>string with ' +
  19711. '<a href="#">links!</a> and other <em>stuff</em>';
  19712. }]);
  19713. </file>
  19714. <file name="protractor.js" type="protractor">
  19715. it('should check ng-bind-html', function() {
  19716. expect(element(by.binding('myHTML')).getText()).toBe(
  19717. 'I am an HTMLstring with links! and other stuff');
  19718. });
  19719. </file>
  19720. </example>
  19721. */
  19722. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  19723. return {
  19724. restrict: 'A',
  19725. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  19726. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  19727. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  19728. return (value || '').toString();
  19729. });
  19730. $compile.$$addBindingClass(tElement);
  19731. return function ngBindHtmlLink(scope, element, attr) {
  19732. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  19733. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  19734. // we re-evaluate the expr because we want a TrustedValueHolderType
  19735. // for $sce, not a string
  19736. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  19737. });
  19738. };
  19739. }
  19740. };
  19741. }];
  19742. function classDirective(name, selector) {
  19743. name = 'ngClass' + name;
  19744. return ['$animate', function($animate) {
  19745. return {
  19746. restrict: 'AC',
  19747. link: function(scope, element, attr) {
  19748. var oldVal;
  19749. scope.$watch(attr[name], ngClassWatchAction, true);
  19750. attr.$observe('class', function(value) {
  19751. ngClassWatchAction(scope.$eval(attr[name]));
  19752. });
  19753. if (name !== 'ngClass') {
  19754. scope.$watch('$index', function($index, old$index) {
  19755. // jshint bitwise: false
  19756. var mod = $index & 1;
  19757. if (mod !== (old$index & 1)) {
  19758. var classes = arrayClasses(scope.$eval(attr[name]));
  19759. mod === selector ?
  19760. addClasses(classes) :
  19761. removeClasses(classes);
  19762. }
  19763. });
  19764. }
  19765. function addClasses(classes) {
  19766. var newClasses = digestClassCounts(classes, 1);
  19767. attr.$addClass(newClasses);
  19768. }
  19769. function removeClasses(classes) {
  19770. var newClasses = digestClassCounts(classes, -1);
  19771. attr.$removeClass(newClasses);
  19772. }
  19773. function digestClassCounts(classes, count) {
  19774. var classCounts = element.data('$classCounts') || {};
  19775. var classesToUpdate = [];
  19776. forEach(classes, function(className) {
  19777. if (count > 0 || classCounts[className]) {
  19778. classCounts[className] = (classCounts[className] || 0) + count;
  19779. if (classCounts[className] === +(count > 0)) {
  19780. classesToUpdate.push(className);
  19781. }
  19782. }
  19783. });
  19784. element.data('$classCounts', classCounts);
  19785. return classesToUpdate.join(' ');
  19786. }
  19787. function updateClasses(oldClasses, newClasses) {
  19788. var toAdd = arrayDifference(newClasses, oldClasses);
  19789. var toRemove = arrayDifference(oldClasses, newClasses);
  19790. toAdd = digestClassCounts(toAdd, 1);
  19791. toRemove = digestClassCounts(toRemove, -1);
  19792. if (toAdd && toAdd.length) {
  19793. $animate.addClass(element, toAdd);
  19794. }
  19795. if (toRemove && toRemove.length) {
  19796. $animate.removeClass(element, toRemove);
  19797. }
  19798. }
  19799. function ngClassWatchAction(newVal) {
  19800. if (selector === true || scope.$index % 2 === selector) {
  19801. var newClasses = arrayClasses(newVal || []);
  19802. if (!oldVal) {
  19803. addClasses(newClasses);
  19804. } else if (!equals(newVal,oldVal)) {
  19805. var oldClasses = arrayClasses(oldVal);
  19806. updateClasses(oldClasses, newClasses);
  19807. }
  19808. }
  19809. oldVal = shallowCopy(newVal);
  19810. }
  19811. }
  19812. };
  19813. function arrayDifference(tokens1, tokens2) {
  19814. var values = [];
  19815. outer:
  19816. for (var i = 0; i < tokens1.length; i++) {
  19817. var token = tokens1[i];
  19818. for (var j = 0; j < tokens2.length; j++) {
  19819. if (token == tokens2[j]) continue outer;
  19820. }
  19821. values.push(token);
  19822. }
  19823. return values;
  19824. }
  19825. function arrayClasses(classVal) {
  19826. if (isArray(classVal)) {
  19827. return classVal;
  19828. } else if (isString(classVal)) {
  19829. return classVal.split(' ');
  19830. } else if (isObject(classVal)) {
  19831. var classes = [];
  19832. forEach(classVal, function(v, k) {
  19833. if (v) {
  19834. classes = classes.concat(k.split(' '));
  19835. }
  19836. });
  19837. return classes;
  19838. }
  19839. return classVal;
  19840. }
  19841. }];
  19842. }
  19843. /**
  19844. * @ngdoc directive
  19845. * @name ngClass
  19846. * @restrict AC
  19847. *
  19848. * @description
  19849. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  19850. * an expression that represents all classes to be added.
  19851. *
  19852. * The directive operates in three different ways, depending on which of three types the expression
  19853. * evaluates to:
  19854. *
  19855. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  19856. * names.
  19857. *
  19858. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  19859. * one or more space-delimited class names.
  19860. *
  19861. * 3. If the expression evaluates to an object, then for each key-value pair of the
  19862. * object with a truthy value the corresponding key is used as a class name.
  19863. *
  19864. * The directive won't add duplicate classes if a particular class was already set.
  19865. *
  19866. * When the expression changes, the previously added classes are removed and only then the
  19867. * new classes are added.
  19868. *
  19869. * @animations
  19870. * add - happens just before the class is applied to the element
  19871. * remove - happens just before the class is removed from the element
  19872. *
  19873. * @element ANY
  19874. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  19875. * of the evaluation can be a string representing space delimited class
  19876. * names, an array, or a map of class names to boolean values. In the case of a map, the
  19877. * names of the properties whose values are truthy will be added as css classes to the
  19878. * element.
  19879. *
  19880. * @example Example that demonstrates basic bindings via ngClass directive.
  19881. <example>
  19882. <file name="index.html">
  19883. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  19884. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  19885. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  19886. <input type="checkbox" ng-model="error"> error (apply "red" class)
  19887. <hr>
  19888. <p ng-class="style">Using String Syntax</p>
  19889. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  19890. <hr>
  19891. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  19892. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  19893. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  19894. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  19895. </file>
  19896. <file name="style.css">
  19897. .strike {
  19898. text-decoration: line-through;
  19899. }
  19900. .bold {
  19901. font-weight: bold;
  19902. }
  19903. .red {
  19904. color: red;
  19905. }
  19906. </file>
  19907. <file name="protractor.js" type="protractor">
  19908. var ps = element.all(by.css('p'));
  19909. it('should let you toggle the class', function() {
  19910. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  19911. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  19912. element(by.model('important')).click();
  19913. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  19914. element(by.model('error')).click();
  19915. expect(ps.first().getAttribute('class')).toMatch(/red/);
  19916. });
  19917. it('should let you toggle string example', function() {
  19918. expect(ps.get(1).getAttribute('class')).toBe('');
  19919. element(by.model('style')).clear();
  19920. element(by.model('style')).sendKeys('red');
  19921. expect(ps.get(1).getAttribute('class')).toBe('red');
  19922. });
  19923. it('array example should have 3 classes', function() {
  19924. expect(ps.last().getAttribute('class')).toBe('');
  19925. element(by.model('style1')).sendKeys('bold');
  19926. element(by.model('style2')).sendKeys('strike');
  19927. element(by.model('style3')).sendKeys('red');
  19928. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  19929. });
  19930. </file>
  19931. </example>
  19932. ## Animations
  19933. The example below demonstrates how to perform animations using ngClass.
  19934. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19935. <file name="index.html">
  19936. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  19937. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  19938. <br>
  19939. <span class="base-class" ng-class="myVar">Sample Text</span>
  19940. </file>
  19941. <file name="style.css">
  19942. .base-class {
  19943. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19944. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19945. }
  19946. .base-class.my-class {
  19947. color: red;
  19948. font-size:3em;
  19949. }
  19950. </file>
  19951. <file name="protractor.js" type="protractor">
  19952. it('should check ng-class', function() {
  19953. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19954. toMatch(/my-class/);
  19955. element(by.id('setbtn')).click();
  19956. expect(element(by.css('.base-class')).getAttribute('class')).
  19957. toMatch(/my-class/);
  19958. element(by.id('clearbtn')).click();
  19959. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19960. toMatch(/my-class/);
  19961. });
  19962. </file>
  19963. </example>
  19964. ## ngClass and pre-existing CSS3 Transitions/Animations
  19965. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  19966. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  19967. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  19968. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  19969. {@link ng.$animate#removeClass $animate.removeClass}.
  19970. */
  19971. var ngClassDirective = classDirective('', true);
  19972. /**
  19973. * @ngdoc directive
  19974. * @name ngClassOdd
  19975. * @restrict AC
  19976. *
  19977. * @description
  19978. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19979. * {@link ng.directive:ngClass ngClass}, except they work in
  19980. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19981. *
  19982. * This directive can be applied only within the scope of an
  19983. * {@link ng.directive:ngRepeat ngRepeat}.
  19984. *
  19985. * @element ANY
  19986. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  19987. * of the evaluation can be a string representing space delimited class names or an array.
  19988. *
  19989. * @example
  19990. <example>
  19991. <file name="index.html">
  19992. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19993. <li ng-repeat="name in names">
  19994. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19995. {{name}}
  19996. </span>
  19997. </li>
  19998. </ol>
  19999. </file>
  20000. <file name="style.css">
  20001. .odd {
  20002. color: red;
  20003. }
  20004. .even {
  20005. color: blue;
  20006. }
  20007. </file>
  20008. <file name="protractor.js" type="protractor">
  20009. it('should check ng-class-odd and ng-class-even', function() {
  20010. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20011. toMatch(/odd/);
  20012. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20013. toMatch(/even/);
  20014. });
  20015. </file>
  20016. </example>
  20017. */
  20018. var ngClassOddDirective = classDirective('Odd', 0);
  20019. /**
  20020. * @ngdoc directive
  20021. * @name ngClassEven
  20022. * @restrict AC
  20023. *
  20024. * @description
  20025. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20026. * {@link ng.directive:ngClass ngClass}, except they work in
  20027. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20028. *
  20029. * This directive can be applied only within the scope of an
  20030. * {@link ng.directive:ngRepeat ngRepeat}.
  20031. *
  20032. * @element ANY
  20033. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20034. * result of the evaluation can be a string representing space delimited class names or an array.
  20035. *
  20036. * @example
  20037. <example>
  20038. <file name="index.html">
  20039. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20040. <li ng-repeat="name in names">
  20041. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20042. {{name}} &nbsp; &nbsp; &nbsp;
  20043. </span>
  20044. </li>
  20045. </ol>
  20046. </file>
  20047. <file name="style.css">
  20048. .odd {
  20049. color: red;
  20050. }
  20051. .even {
  20052. color: blue;
  20053. }
  20054. </file>
  20055. <file name="protractor.js" type="protractor">
  20056. it('should check ng-class-odd and ng-class-even', function() {
  20057. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20058. toMatch(/odd/);
  20059. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20060. toMatch(/even/);
  20061. });
  20062. </file>
  20063. </example>
  20064. */
  20065. var ngClassEvenDirective = classDirective('Even', 1);
  20066. /**
  20067. * @ngdoc directive
  20068. * @name ngCloak
  20069. * @restrict AC
  20070. *
  20071. * @description
  20072. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20073. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20074. * directive to avoid the undesirable flicker effect caused by the html template display.
  20075. *
  20076. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20077. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20078. * of the browser view.
  20079. *
  20080. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20081. * `angular.min.js`.
  20082. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20083. *
  20084. * ```css
  20085. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20086. * display: none !important;
  20087. * }
  20088. * ```
  20089. *
  20090. * When this css rule is loaded by the browser, all html elements (including their children) that
  20091. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20092. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20093. * the compiled element visible.
  20094. *
  20095. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20096. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20097. * application.
  20098. *
  20099. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  20100. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  20101. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  20102. *
  20103. * @element ANY
  20104. *
  20105. * @example
  20106. <example>
  20107. <file name="index.html">
  20108. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20109. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  20110. </file>
  20111. <file name="protractor.js" type="protractor">
  20112. it('should remove the template directive and css class', function() {
  20113. expect($('#template1').getAttribute('ng-cloak')).
  20114. toBeNull();
  20115. expect($('#template2').getAttribute('ng-cloak')).
  20116. toBeNull();
  20117. });
  20118. </file>
  20119. </example>
  20120. *
  20121. */
  20122. var ngCloakDirective = ngDirective({
  20123. compile: function(element, attr) {
  20124. attr.$set('ngCloak', undefined);
  20125. element.removeClass('ng-cloak');
  20126. }
  20127. });
  20128. /**
  20129. * @ngdoc directive
  20130. * @name ngController
  20131. *
  20132. * @description
  20133. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20134. * supports the principles behind the Model-View-Controller design pattern.
  20135. *
  20136. * MVC components in angular:
  20137. *
  20138. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20139. * are accessed through bindings.
  20140. * * View — The template (HTML with data bindings) that is rendered into the View.
  20141. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20142. * logic behind the application to decorate the scope with functions and values
  20143. *
  20144. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20145. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20146. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20147. * and executed twice.
  20148. *
  20149. * @element ANY
  20150. * @scope
  20151. * @priority 500
  20152. * @param {expression} ngController Name of a constructor function registered with the current
  20153. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20154. * that on the current scope evaluates to a constructor function.
  20155. *
  20156. * The controller instance can be published into a scope property by specifying
  20157. * `ng-controller="as propertyName"`.
  20158. *
  20159. * If the current `$controllerProvider` is configured to use globals (via
  20160. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20161. * also be the name of a globally accessible constructor function (not recommended).
  20162. *
  20163. * @example
  20164. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20165. * greeting are methods declared on the controller (see source tab). These methods can
  20166. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20167. * in the View without the need for a manual update.
  20168. *
  20169. * Two different declaration styles are included below:
  20170. *
  20171. * * one binds methods and properties directly onto the controller using `this`:
  20172. * `ng-controller="SettingsController1 as settings"`
  20173. * * one injects `$scope` into the controller:
  20174. * `ng-controller="SettingsController2"`
  20175. *
  20176. * The second option is more common in the Angular community, and is generally used in boilerplates
  20177. * and in this guide. However, there are advantages to binding properties directly to the controller
  20178. * and avoiding scope.
  20179. *
  20180. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20181. * multiple controllers apply to an element.
  20182. * * If you are writing your controllers as classes you have easier access to the properties and
  20183. * methods, which will appear on the scope, from inside the controller code.
  20184. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20185. * inheritance masking primitives.
  20186. *
  20187. * This example demonstrates the `controller as` syntax.
  20188. *
  20189. * <example name="ngControllerAs" module="controllerAsExample">
  20190. * <file name="index.html">
  20191. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20192. * Name: <input type="text" ng-model="settings.name"/>
  20193. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  20194. * Contact:
  20195. * <ul>
  20196. * <li ng-repeat="contact in settings.contacts">
  20197. * <select ng-model="contact.type">
  20198. * <option>phone</option>
  20199. * <option>email</option>
  20200. * </select>
  20201. * <input type="text" ng-model="contact.value"/>
  20202. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  20203. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  20204. * </li>
  20205. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  20206. * </ul>
  20207. * </div>
  20208. * </file>
  20209. * <file name="app.js">
  20210. * angular.module('controllerAsExample', [])
  20211. * .controller('SettingsController1', SettingsController1);
  20212. *
  20213. * function SettingsController1() {
  20214. * this.name = "John Smith";
  20215. * this.contacts = [
  20216. * {type: 'phone', value: '408 555 1212'},
  20217. * {type: 'email', value: 'john.smith@example.org'} ];
  20218. * }
  20219. *
  20220. * SettingsController1.prototype.greet = function() {
  20221. * alert(this.name);
  20222. * };
  20223. *
  20224. * SettingsController1.prototype.addContact = function() {
  20225. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20226. * };
  20227. *
  20228. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20229. * var index = this.contacts.indexOf(contactToRemove);
  20230. * this.contacts.splice(index, 1);
  20231. * };
  20232. *
  20233. * SettingsController1.prototype.clearContact = function(contact) {
  20234. * contact.type = 'phone';
  20235. * contact.value = '';
  20236. * };
  20237. * </file>
  20238. * <file name="protractor.js" type="protractor">
  20239. * it('should check controller as', function() {
  20240. * var container = element(by.id('ctrl-as-exmpl'));
  20241. * expect(container.element(by.model('settings.name'))
  20242. * .getAttribute('value')).toBe('John Smith');
  20243. *
  20244. * var firstRepeat =
  20245. * container.element(by.repeater('contact in settings.contacts').row(0));
  20246. * var secondRepeat =
  20247. * container.element(by.repeater('contact in settings.contacts').row(1));
  20248. *
  20249. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20250. * .toBe('408 555 1212');
  20251. *
  20252. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20253. * .toBe('john.smith@example.org');
  20254. *
  20255. * firstRepeat.element(by.linkText('clear')).click();
  20256. *
  20257. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20258. * .toBe('');
  20259. *
  20260. * container.element(by.linkText('add')).click();
  20261. *
  20262. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20263. * .element(by.model('contact.value'))
  20264. * .getAttribute('value'))
  20265. * .toBe('yourname@example.org');
  20266. * });
  20267. * </file>
  20268. * </example>
  20269. *
  20270. * This example demonstrates the "attach to `$scope`" style of controller.
  20271. *
  20272. * <example name="ngController" module="controllerExample">
  20273. * <file name="index.html">
  20274. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20275. * Name: <input type="text" ng-model="name"/>
  20276. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  20277. * Contact:
  20278. * <ul>
  20279. * <li ng-repeat="contact in contacts">
  20280. * <select ng-model="contact.type">
  20281. * <option>phone</option>
  20282. * <option>email</option>
  20283. * </select>
  20284. * <input type="text" ng-model="contact.value"/>
  20285. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  20286. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  20287. * </li>
  20288. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  20289. * </ul>
  20290. * </div>
  20291. * </file>
  20292. * <file name="app.js">
  20293. * angular.module('controllerExample', [])
  20294. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20295. *
  20296. * function SettingsController2($scope) {
  20297. * $scope.name = "John Smith";
  20298. * $scope.contacts = [
  20299. * {type:'phone', value:'408 555 1212'},
  20300. * {type:'email', value:'john.smith@example.org'} ];
  20301. *
  20302. * $scope.greet = function() {
  20303. * alert($scope.name);
  20304. * };
  20305. *
  20306. * $scope.addContact = function() {
  20307. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20308. * };
  20309. *
  20310. * $scope.removeContact = function(contactToRemove) {
  20311. * var index = $scope.contacts.indexOf(contactToRemove);
  20312. * $scope.contacts.splice(index, 1);
  20313. * };
  20314. *
  20315. * $scope.clearContact = function(contact) {
  20316. * contact.type = 'phone';
  20317. * contact.value = '';
  20318. * };
  20319. * }
  20320. * </file>
  20321. * <file name="protractor.js" type="protractor">
  20322. * it('should check controller', function() {
  20323. * var container = element(by.id('ctrl-exmpl'));
  20324. *
  20325. * expect(container.element(by.model('name'))
  20326. * .getAttribute('value')).toBe('John Smith');
  20327. *
  20328. * var firstRepeat =
  20329. * container.element(by.repeater('contact in contacts').row(0));
  20330. * var secondRepeat =
  20331. * container.element(by.repeater('contact in contacts').row(1));
  20332. *
  20333. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20334. * .toBe('408 555 1212');
  20335. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20336. * .toBe('john.smith@example.org');
  20337. *
  20338. * firstRepeat.element(by.linkText('clear')).click();
  20339. *
  20340. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20341. * .toBe('');
  20342. *
  20343. * container.element(by.linkText('add')).click();
  20344. *
  20345. * expect(container.element(by.repeater('contact in contacts').row(2))
  20346. * .element(by.model('contact.value'))
  20347. * .getAttribute('value'))
  20348. * .toBe('yourname@example.org');
  20349. * });
  20350. * </file>
  20351. *</example>
  20352. */
  20353. var ngControllerDirective = [function() {
  20354. return {
  20355. restrict: 'A',
  20356. scope: true,
  20357. controller: '@',
  20358. priority: 500
  20359. };
  20360. }];
  20361. /**
  20362. * @ngdoc directive
  20363. * @name ngCsp
  20364. *
  20365. * @element html
  20366. * @description
  20367. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20368. *
  20369. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20370. *
  20371. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20372. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20373. *
  20374. * - don't use `Function` constructor to generate optimized value getters
  20375. * - don't inject custom stylesheet into the document
  20376. *
  20377. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20378. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20379. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20380. * be raised.
  20381. *
  20382. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20383. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20384. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20385. *
  20386. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20387. * autodetection however triggers a CSP error to be logged in the console:
  20388. *
  20389. * ```
  20390. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20391. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20392. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20393. * ```
  20394. *
  20395. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20396. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20397. * appears first in the html document.
  20398. *
  20399. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20400. *
  20401. * @example
  20402. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20403. ```html
  20404. <!doctype html>
  20405. <html ng-app ng-csp>
  20406. ...
  20407. ...
  20408. </html>
  20409. ```
  20410. * @example
  20411. // Note: the suffix `.csp` in the example name triggers
  20412. // csp mode in our http server!
  20413. <example name="example.csp" module="cspExample" ng-csp="true">
  20414. <file name="index.html">
  20415. <div ng-controller="MainController as ctrl">
  20416. <div>
  20417. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  20418. <span id="counter">
  20419. {{ctrl.counter}}
  20420. </span>
  20421. </div>
  20422. <div>
  20423. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  20424. <span id="evilError">
  20425. {{ctrl.evilError}}
  20426. </span>
  20427. </div>
  20428. </div>
  20429. </file>
  20430. <file name="script.js">
  20431. angular.module('cspExample', [])
  20432. .controller('MainController', function() {
  20433. this.counter = 0;
  20434. this.inc = function() {
  20435. this.counter++;
  20436. };
  20437. this.evil = function() {
  20438. // jshint evil:true
  20439. try {
  20440. eval('1+2');
  20441. } catch (e) {
  20442. this.evilError = e.message;
  20443. }
  20444. };
  20445. });
  20446. </file>
  20447. <file name="protractor.js" type="protractor">
  20448. var util, webdriver;
  20449. var incBtn = element(by.id('inc'));
  20450. var counter = element(by.id('counter'));
  20451. var evilBtn = element(by.id('evil'));
  20452. var evilError = element(by.id('evilError'));
  20453. function getAndClearSevereErrors() {
  20454. return browser.manage().logs().get('browser').then(function(browserLog) {
  20455. return browserLog.filter(function(logEntry) {
  20456. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  20457. });
  20458. });
  20459. }
  20460. function clearErrors() {
  20461. getAndClearSevereErrors();
  20462. }
  20463. function expectNoErrors() {
  20464. getAndClearSevereErrors().then(function(filteredLog) {
  20465. expect(filteredLog.length).toEqual(0);
  20466. if (filteredLog.length) {
  20467. console.log('browser console errors: ' + util.inspect(filteredLog));
  20468. }
  20469. });
  20470. }
  20471. function expectError(regex) {
  20472. getAndClearSevereErrors().then(function(filteredLog) {
  20473. var found = false;
  20474. filteredLog.forEach(function(log) {
  20475. if (log.message.match(regex)) {
  20476. found = true;
  20477. }
  20478. });
  20479. if (!found) {
  20480. throw new Error('expected an error that matches ' + regex);
  20481. }
  20482. });
  20483. }
  20484. beforeEach(function() {
  20485. util = require('util');
  20486. webdriver = require('protractor/node_modules/selenium-webdriver');
  20487. });
  20488. // For now, we only test on Chrome,
  20489. // as Safari does not load the page with Protractor's injected scripts,
  20490. // and Firefox webdriver always disables content security policy (#6358)
  20491. if (browser.params.browser !== 'chrome') {
  20492. return;
  20493. }
  20494. it('should not report errors when the page is loaded', function() {
  20495. // clear errors so we are not dependent on previous tests
  20496. clearErrors();
  20497. // Need to reload the page as the page is already loaded when
  20498. // we come here
  20499. browser.driver.getCurrentUrl().then(function(url) {
  20500. browser.get(url);
  20501. });
  20502. expectNoErrors();
  20503. });
  20504. it('should evaluate expressions', function() {
  20505. expect(counter.getText()).toEqual('0');
  20506. incBtn.click();
  20507. expect(counter.getText()).toEqual('1');
  20508. expectNoErrors();
  20509. });
  20510. it('should throw and report an error when using "eval"', function() {
  20511. evilBtn.click();
  20512. expect(evilError.getText()).toMatch(/Content Security Policy/);
  20513. expectError(/Content Security Policy/);
  20514. });
  20515. </file>
  20516. </example>
  20517. */
  20518. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  20519. // bootstrap the system (before $parse is instantiated), for this reason we just have
  20520. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  20521. /**
  20522. * @ngdoc directive
  20523. * @name ngClick
  20524. *
  20525. * @description
  20526. * The ngClick directive allows you to specify custom behavior when
  20527. * an element is clicked.
  20528. *
  20529. * @element ANY
  20530. * @priority 0
  20531. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  20532. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  20533. *
  20534. * @example
  20535. <example>
  20536. <file name="index.html">
  20537. <button ng-click="count = count + 1" ng-init="count=0">
  20538. Increment
  20539. </button>
  20540. <span>
  20541. count: {{count}}
  20542. </span>
  20543. </file>
  20544. <file name="protractor.js" type="protractor">
  20545. it('should check ng-click', function() {
  20546. expect(element(by.binding('count')).getText()).toMatch('0');
  20547. element(by.css('button')).click();
  20548. expect(element(by.binding('count')).getText()).toMatch('1');
  20549. });
  20550. </file>
  20551. </example>
  20552. */
  20553. /*
  20554. * A collection of directives that allows creation of custom event handlers that are defined as
  20555. * angular expressions and are compiled and executed within the current scope.
  20556. */
  20557. var ngEventDirectives = {};
  20558. // For events that might fire synchronously during DOM manipulation
  20559. // we need to execute their event handlers asynchronously using $evalAsync,
  20560. // so that they are not executed in an inconsistent state.
  20561. var forceAsyncEvents = {
  20562. 'blur': true,
  20563. 'focus': true
  20564. };
  20565. forEach(
  20566. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  20567. function(eventName) {
  20568. var directiveName = directiveNormalize('ng-' + eventName);
  20569. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  20570. return {
  20571. restrict: 'A',
  20572. compile: function($element, attr) {
  20573. // We expose the powerful $event object on the scope that provides access to the Window,
  20574. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  20575. // checks at the cost of speed since event handler expressions are not executed as
  20576. // frequently as regular change detection.
  20577. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  20578. return function ngEventHandler(scope, element) {
  20579. element.on(eventName, function(event) {
  20580. var callback = function() {
  20581. fn(scope, {$event:event});
  20582. };
  20583. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  20584. scope.$evalAsync(callback);
  20585. } else {
  20586. scope.$apply(callback);
  20587. }
  20588. });
  20589. };
  20590. }
  20591. };
  20592. }];
  20593. }
  20594. );
  20595. /**
  20596. * @ngdoc directive
  20597. * @name ngDblclick
  20598. *
  20599. * @description
  20600. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  20601. *
  20602. * @element ANY
  20603. * @priority 0
  20604. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  20605. * a dblclick. (The Event object is available as `$event`)
  20606. *
  20607. * @example
  20608. <example>
  20609. <file name="index.html">
  20610. <button ng-dblclick="count = count + 1" ng-init="count=0">
  20611. Increment (on double click)
  20612. </button>
  20613. count: {{count}}
  20614. </file>
  20615. </example>
  20616. */
  20617. /**
  20618. * @ngdoc directive
  20619. * @name ngMousedown
  20620. *
  20621. * @description
  20622. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  20623. *
  20624. * @element ANY
  20625. * @priority 0
  20626. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  20627. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  20628. *
  20629. * @example
  20630. <example>
  20631. <file name="index.html">
  20632. <button ng-mousedown="count = count + 1" ng-init="count=0">
  20633. Increment (on mouse down)
  20634. </button>
  20635. count: {{count}}
  20636. </file>
  20637. </example>
  20638. */
  20639. /**
  20640. * @ngdoc directive
  20641. * @name ngMouseup
  20642. *
  20643. * @description
  20644. * Specify custom behavior on mouseup event.
  20645. *
  20646. * @element ANY
  20647. * @priority 0
  20648. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  20649. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  20650. *
  20651. * @example
  20652. <example>
  20653. <file name="index.html">
  20654. <button ng-mouseup="count = count + 1" ng-init="count=0">
  20655. Increment (on mouse up)
  20656. </button>
  20657. count: {{count}}
  20658. </file>
  20659. </example>
  20660. */
  20661. /**
  20662. * @ngdoc directive
  20663. * @name ngMouseover
  20664. *
  20665. * @description
  20666. * Specify custom behavior on mouseover event.
  20667. *
  20668. * @element ANY
  20669. * @priority 0
  20670. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  20671. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  20672. *
  20673. * @example
  20674. <example>
  20675. <file name="index.html">
  20676. <button ng-mouseover="count = count + 1" ng-init="count=0">
  20677. Increment (when mouse is over)
  20678. </button>
  20679. count: {{count}}
  20680. </file>
  20681. </example>
  20682. */
  20683. /**
  20684. * @ngdoc directive
  20685. * @name ngMouseenter
  20686. *
  20687. * @description
  20688. * Specify custom behavior on mouseenter event.
  20689. *
  20690. * @element ANY
  20691. * @priority 0
  20692. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  20693. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  20694. *
  20695. * @example
  20696. <example>
  20697. <file name="index.html">
  20698. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  20699. Increment (when mouse enters)
  20700. </button>
  20701. count: {{count}}
  20702. </file>
  20703. </example>
  20704. */
  20705. /**
  20706. * @ngdoc directive
  20707. * @name ngMouseleave
  20708. *
  20709. * @description
  20710. * Specify custom behavior on mouseleave event.
  20711. *
  20712. * @element ANY
  20713. * @priority 0
  20714. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  20715. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  20716. *
  20717. * @example
  20718. <example>
  20719. <file name="index.html">
  20720. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  20721. Increment (when mouse leaves)
  20722. </button>
  20723. count: {{count}}
  20724. </file>
  20725. </example>
  20726. */
  20727. /**
  20728. * @ngdoc directive
  20729. * @name ngMousemove
  20730. *
  20731. * @description
  20732. * Specify custom behavior on mousemove event.
  20733. *
  20734. * @element ANY
  20735. * @priority 0
  20736. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  20737. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  20738. *
  20739. * @example
  20740. <example>
  20741. <file name="index.html">
  20742. <button ng-mousemove="count = count + 1" ng-init="count=0">
  20743. Increment (when mouse moves)
  20744. </button>
  20745. count: {{count}}
  20746. </file>
  20747. </example>
  20748. */
  20749. /**
  20750. * @ngdoc directive
  20751. * @name ngKeydown
  20752. *
  20753. * @description
  20754. * Specify custom behavior on keydown event.
  20755. *
  20756. * @element ANY
  20757. * @priority 0
  20758. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  20759. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20760. *
  20761. * @example
  20762. <example>
  20763. <file name="index.html">
  20764. <input ng-keydown="count = count + 1" ng-init="count=0">
  20765. key down count: {{count}}
  20766. </file>
  20767. </example>
  20768. */
  20769. /**
  20770. * @ngdoc directive
  20771. * @name ngKeyup
  20772. *
  20773. * @description
  20774. * Specify custom behavior on keyup event.
  20775. *
  20776. * @element ANY
  20777. * @priority 0
  20778. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  20779. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20780. *
  20781. * @example
  20782. <example>
  20783. <file name="index.html">
  20784. <p>Typing in the input box below updates the key count</p>
  20785. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  20786. <p>Typing in the input box below updates the keycode</p>
  20787. <input ng-keyup="event=$event">
  20788. <p>event keyCode: {{ event.keyCode }}</p>
  20789. <p>event altKey: {{ event.altKey }}</p>
  20790. </file>
  20791. </example>
  20792. */
  20793. /**
  20794. * @ngdoc directive
  20795. * @name ngKeypress
  20796. *
  20797. * @description
  20798. * Specify custom behavior on keypress event.
  20799. *
  20800. * @element ANY
  20801. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  20802. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  20803. * and can be interrogated for keyCode, altKey, etc.)
  20804. *
  20805. * @example
  20806. <example>
  20807. <file name="index.html">
  20808. <input ng-keypress="count = count + 1" ng-init="count=0">
  20809. key press count: {{count}}
  20810. </file>
  20811. </example>
  20812. */
  20813. /**
  20814. * @ngdoc directive
  20815. * @name ngSubmit
  20816. *
  20817. * @description
  20818. * Enables binding angular expressions to onsubmit events.
  20819. *
  20820. * Additionally it prevents the default action (which for form means sending the request to the
  20821. * server and reloading the current page), but only if the form does not contain `action`,
  20822. * `data-action`, or `x-action` attributes.
  20823. *
  20824. * <div class="alert alert-warning">
  20825. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  20826. * `ngSubmit` handlers together. See the
  20827. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  20828. * for a detailed discussion of when `ngSubmit` may be triggered.
  20829. * </div>
  20830. *
  20831. * @element form
  20832. * @priority 0
  20833. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  20834. * ({@link guide/expression#-event- Event object is available as `$event`})
  20835. *
  20836. * @example
  20837. <example module="submitExample">
  20838. <file name="index.html">
  20839. <script>
  20840. angular.module('submitExample', [])
  20841. .controller('ExampleController', ['$scope', function($scope) {
  20842. $scope.list = [];
  20843. $scope.text = 'hello';
  20844. $scope.submit = function() {
  20845. if ($scope.text) {
  20846. $scope.list.push(this.text);
  20847. $scope.text = '';
  20848. }
  20849. };
  20850. }]);
  20851. </script>
  20852. <form ng-submit="submit()" ng-controller="ExampleController">
  20853. Enter text and hit enter:
  20854. <input type="text" ng-model="text" name="text" />
  20855. <input type="submit" id="submit" value="Submit" />
  20856. <pre>list={{list}}</pre>
  20857. </form>
  20858. </file>
  20859. <file name="protractor.js" type="protractor">
  20860. it('should check ng-submit', function() {
  20861. expect(element(by.binding('list')).getText()).toBe('list=[]');
  20862. element(by.css('#submit')).click();
  20863. expect(element(by.binding('list')).getText()).toContain('hello');
  20864. expect(element(by.model('text')).getAttribute('value')).toBe('');
  20865. });
  20866. it('should ignore empty strings', function() {
  20867. expect(element(by.binding('list')).getText()).toBe('list=[]');
  20868. element(by.css('#submit')).click();
  20869. element(by.css('#submit')).click();
  20870. expect(element(by.binding('list')).getText()).toContain('hello');
  20871. });
  20872. </file>
  20873. </example>
  20874. */
  20875. /**
  20876. * @ngdoc directive
  20877. * @name ngFocus
  20878. *
  20879. * @description
  20880. * Specify custom behavior on focus event.
  20881. *
  20882. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  20883. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  20884. * during an `$apply` to ensure a consistent state.
  20885. *
  20886. * @element window, input, select, textarea, a
  20887. * @priority 0
  20888. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  20889. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  20890. *
  20891. * @example
  20892. * See {@link ng.directive:ngClick ngClick}
  20893. */
  20894. /**
  20895. * @ngdoc directive
  20896. * @name ngBlur
  20897. *
  20898. * @description
  20899. * Specify custom behavior on blur event.
  20900. *
  20901. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  20902. * an element has lost focus.
  20903. *
  20904. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  20905. * (e.g. removing a focussed input),
  20906. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  20907. * during an `$apply` to ensure a consistent state.
  20908. *
  20909. * @element window, input, select, textarea, a
  20910. * @priority 0
  20911. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  20912. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  20913. *
  20914. * @example
  20915. * See {@link ng.directive:ngClick ngClick}
  20916. */
  20917. /**
  20918. * @ngdoc directive
  20919. * @name ngCopy
  20920. *
  20921. * @description
  20922. * Specify custom behavior on copy event.
  20923. *
  20924. * @element window, input, select, textarea, a
  20925. * @priority 0
  20926. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  20927. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  20928. *
  20929. * @example
  20930. <example>
  20931. <file name="index.html">
  20932. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  20933. copied: {{copied}}
  20934. </file>
  20935. </example>
  20936. */
  20937. /**
  20938. * @ngdoc directive
  20939. * @name ngCut
  20940. *
  20941. * @description
  20942. * Specify custom behavior on cut event.
  20943. *
  20944. * @element window, input, select, textarea, a
  20945. * @priority 0
  20946. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  20947. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  20948. *
  20949. * @example
  20950. <example>
  20951. <file name="index.html">
  20952. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  20953. cut: {{cut}}
  20954. </file>
  20955. </example>
  20956. */
  20957. /**
  20958. * @ngdoc directive
  20959. * @name ngPaste
  20960. *
  20961. * @description
  20962. * Specify custom behavior on paste event.
  20963. *
  20964. * @element window, input, select, textarea, a
  20965. * @priority 0
  20966. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  20967. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  20968. *
  20969. * @example
  20970. <example>
  20971. <file name="index.html">
  20972. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  20973. pasted: {{paste}}
  20974. </file>
  20975. </example>
  20976. */
  20977. /**
  20978. * @ngdoc directive
  20979. * @name ngIf
  20980. * @restrict A
  20981. *
  20982. * @description
  20983. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  20984. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  20985. * value then the element is removed from the DOM, otherwise a clone of the
  20986. * element is reinserted into the DOM.
  20987. *
  20988. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  20989. * element in the DOM rather than changing its visibility via the `display` css property. A common
  20990. * case when this difference is significant is when using css selectors that rely on an element's
  20991. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  20992. *
  20993. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  20994. * is created when the element is restored. The scope created within `ngIf` inherits from
  20995. * its parent scope using
  20996. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  20997. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  20998. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  20999. * variable within the child scope will override (hide) the value in the parent scope.
  21000. *
  21001. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21002. * is if an element's class attribute is directly modified after it's compiled, using something like
  21003. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21004. * the added class will be lost because the original compiled state is used to regenerate the element.
  21005. *
  21006. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21007. * and `leave` effects.
  21008. *
  21009. * @animations
  21010. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21011. * leave - happens just before the `ngIf` contents are removed from the DOM
  21012. *
  21013. * @element ANY
  21014. * @scope
  21015. * @priority 600
  21016. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21017. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21018. * element is added to the DOM tree.
  21019. *
  21020. * @example
  21021. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21022. <file name="index.html">
  21023. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  21024. Show when checked:
  21025. <span ng-if="checked" class="animate-if">
  21026. This is removed when the checkbox is unchecked.
  21027. </span>
  21028. </file>
  21029. <file name="animations.css">
  21030. .animate-if {
  21031. background:white;
  21032. border:1px solid black;
  21033. padding:10px;
  21034. }
  21035. .animate-if.ng-enter, .animate-if.ng-leave {
  21036. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21037. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21038. }
  21039. .animate-if.ng-enter,
  21040. .animate-if.ng-leave.ng-leave-active {
  21041. opacity:0;
  21042. }
  21043. .animate-if.ng-leave,
  21044. .animate-if.ng-enter.ng-enter-active {
  21045. opacity:1;
  21046. }
  21047. </file>
  21048. </example>
  21049. */
  21050. var ngIfDirective = ['$animate', function($animate) {
  21051. return {
  21052. multiElement: true,
  21053. transclude: 'element',
  21054. priority: 600,
  21055. terminal: true,
  21056. restrict: 'A',
  21057. $$tlb: true,
  21058. link: function($scope, $element, $attr, ctrl, $transclude) {
  21059. var block, childScope, previousElements;
  21060. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21061. if (value) {
  21062. if (!childScope) {
  21063. $transclude(function(clone, newScope) {
  21064. childScope = newScope;
  21065. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21066. // Note: We only need the first/last node of the cloned nodes.
  21067. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21068. // by a directive with templateUrl when its template arrives.
  21069. block = {
  21070. clone: clone
  21071. };
  21072. $animate.enter(clone, $element.parent(), $element);
  21073. });
  21074. }
  21075. } else {
  21076. if (previousElements) {
  21077. previousElements.remove();
  21078. previousElements = null;
  21079. }
  21080. if (childScope) {
  21081. childScope.$destroy();
  21082. childScope = null;
  21083. }
  21084. if (block) {
  21085. previousElements = getBlockNodes(block.clone);
  21086. $animate.leave(previousElements).then(function() {
  21087. previousElements = null;
  21088. });
  21089. block = null;
  21090. }
  21091. }
  21092. });
  21093. }
  21094. };
  21095. }];
  21096. /**
  21097. * @ngdoc directive
  21098. * @name ngInclude
  21099. * @restrict ECA
  21100. *
  21101. * @description
  21102. * Fetches, compiles and includes an external HTML fragment.
  21103. *
  21104. * By default, the template URL is restricted to the same domain and protocol as the
  21105. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21106. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21107. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21108. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21109. * ng.$sce Strict Contextual Escaping}.
  21110. *
  21111. * In addition, the browser's
  21112. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21113. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21114. * policy may further restrict whether the template is successfully loaded.
  21115. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21116. * access on some browsers.
  21117. *
  21118. * @animations
  21119. * enter - animation is used to bring new content into the browser.
  21120. * leave - animation is used to animate existing content away.
  21121. *
  21122. * The enter and leave animation occur concurrently.
  21123. *
  21124. * @scope
  21125. * @priority 400
  21126. *
  21127. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21128. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21129. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21130. *
  21131. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21132. * $anchorScroll} to scroll the viewport after the content is loaded.
  21133. *
  21134. * - If the attribute is not set, disable scrolling.
  21135. * - If the attribute is set without value, enable scrolling.
  21136. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21137. *
  21138. * @example
  21139. <example module="includeExample" deps="angular-animate.js" animations="true">
  21140. <file name="index.html">
  21141. <div ng-controller="ExampleController">
  21142. <select ng-model="template" ng-options="t.name for t in templates">
  21143. <option value="">(blank)</option>
  21144. </select>
  21145. url of the template: <tt>{{template.url}}</tt>
  21146. <hr/>
  21147. <div class="slide-animate-container">
  21148. <div class="slide-animate" ng-include="template.url"></div>
  21149. </div>
  21150. </div>
  21151. </file>
  21152. <file name="script.js">
  21153. angular.module('includeExample', ['ngAnimate'])
  21154. .controller('ExampleController', ['$scope', function($scope) {
  21155. $scope.templates =
  21156. [ { name: 'template1.html', url: 'template1.html'},
  21157. { name: 'template2.html', url: 'template2.html'} ];
  21158. $scope.template = $scope.templates[0];
  21159. }]);
  21160. </file>
  21161. <file name="template1.html">
  21162. Content of template1.html
  21163. </file>
  21164. <file name="template2.html">
  21165. Content of template2.html
  21166. </file>
  21167. <file name="animations.css">
  21168. .slide-animate-container {
  21169. position:relative;
  21170. background:white;
  21171. border:1px solid black;
  21172. height:40px;
  21173. overflow:hidden;
  21174. }
  21175. .slide-animate {
  21176. padding:10px;
  21177. }
  21178. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21179. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21180. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21181. position:absolute;
  21182. top:0;
  21183. left:0;
  21184. right:0;
  21185. bottom:0;
  21186. display:block;
  21187. padding:10px;
  21188. }
  21189. .slide-animate.ng-enter {
  21190. top:-50px;
  21191. }
  21192. .slide-animate.ng-enter.ng-enter-active {
  21193. top:0;
  21194. }
  21195. .slide-animate.ng-leave {
  21196. top:0;
  21197. }
  21198. .slide-animate.ng-leave.ng-leave-active {
  21199. top:50px;
  21200. }
  21201. </file>
  21202. <file name="protractor.js" type="protractor">
  21203. var templateSelect = element(by.model('template'));
  21204. var includeElem = element(by.css('[ng-include]'));
  21205. it('should load template1.html', function() {
  21206. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21207. });
  21208. it('should load template2.html', function() {
  21209. if (browser.params.browser == 'firefox') {
  21210. // Firefox can't handle using selects
  21211. // See https://github.com/angular/protractor/issues/480
  21212. return;
  21213. }
  21214. templateSelect.click();
  21215. templateSelect.all(by.css('option')).get(2).click();
  21216. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21217. });
  21218. it('should change to blank', function() {
  21219. if (browser.params.browser == 'firefox') {
  21220. // Firefox can't handle using selects
  21221. return;
  21222. }
  21223. templateSelect.click();
  21224. templateSelect.all(by.css('option')).get(0).click();
  21225. expect(includeElem.isPresent()).toBe(false);
  21226. });
  21227. </file>
  21228. </example>
  21229. */
  21230. /**
  21231. * @ngdoc event
  21232. * @name ngInclude#$includeContentRequested
  21233. * @eventType emit on the scope ngInclude was declared in
  21234. * @description
  21235. * Emitted every time the ngInclude content is requested.
  21236. *
  21237. * @param {Object} angularEvent Synthetic event object.
  21238. * @param {String} src URL of content to load.
  21239. */
  21240. /**
  21241. * @ngdoc event
  21242. * @name ngInclude#$includeContentLoaded
  21243. * @eventType emit on the current ngInclude scope
  21244. * @description
  21245. * Emitted every time the ngInclude content is reloaded.
  21246. *
  21247. * @param {Object} angularEvent Synthetic event object.
  21248. * @param {String} src URL of content to load.
  21249. */
  21250. /**
  21251. * @ngdoc event
  21252. * @name ngInclude#$includeContentError
  21253. * @eventType emit on the scope ngInclude was declared in
  21254. * @description
  21255. * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
  21256. *
  21257. * @param {Object} angularEvent Synthetic event object.
  21258. * @param {String} src URL of content to load.
  21259. */
  21260. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21261. function($templateRequest, $anchorScroll, $animate, $sce) {
  21262. return {
  21263. restrict: 'ECA',
  21264. priority: 400,
  21265. terminal: true,
  21266. transclude: 'element',
  21267. controller: angular.noop,
  21268. compile: function(element, attr) {
  21269. var srcExp = attr.ngInclude || attr.src,
  21270. onloadExp = attr.onload || '',
  21271. autoScrollExp = attr.autoscroll;
  21272. return function(scope, $element, $attr, ctrl, $transclude) {
  21273. var changeCounter = 0,
  21274. currentScope,
  21275. previousElement,
  21276. currentElement;
  21277. var cleanupLastIncludeContent = function() {
  21278. if (previousElement) {
  21279. previousElement.remove();
  21280. previousElement = null;
  21281. }
  21282. if (currentScope) {
  21283. currentScope.$destroy();
  21284. currentScope = null;
  21285. }
  21286. if (currentElement) {
  21287. $animate.leave(currentElement).then(function() {
  21288. previousElement = null;
  21289. });
  21290. previousElement = currentElement;
  21291. currentElement = null;
  21292. }
  21293. };
  21294. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21295. var afterAnimation = function() {
  21296. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21297. $anchorScroll();
  21298. }
  21299. };
  21300. var thisChangeId = ++changeCounter;
  21301. if (src) {
  21302. //set the 2nd param to true to ignore the template request error so that the inner
  21303. //contents and scope can be cleaned up.
  21304. $templateRequest(src, true).then(function(response) {
  21305. if (thisChangeId !== changeCounter) return;
  21306. var newScope = scope.$new();
  21307. ctrl.template = response;
  21308. // Note: This will also link all children of ng-include that were contained in the original
  21309. // html. If that content contains controllers, ... they could pollute/change the scope.
  21310. // However, using ng-include on an element with additional content does not make sense...
  21311. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21312. // function is called before linking the content, which would apply child
  21313. // directives to non existing elements.
  21314. var clone = $transclude(newScope, function(clone) {
  21315. cleanupLastIncludeContent();
  21316. $animate.enter(clone, null, $element).then(afterAnimation);
  21317. });
  21318. currentScope = newScope;
  21319. currentElement = clone;
  21320. currentScope.$emit('$includeContentLoaded', src);
  21321. scope.$eval(onloadExp);
  21322. }, function() {
  21323. if (thisChangeId === changeCounter) {
  21324. cleanupLastIncludeContent();
  21325. scope.$emit('$includeContentError', src);
  21326. }
  21327. });
  21328. scope.$emit('$includeContentRequested', src);
  21329. } else {
  21330. cleanupLastIncludeContent();
  21331. ctrl.template = null;
  21332. }
  21333. });
  21334. };
  21335. }
  21336. };
  21337. }];
  21338. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21339. // It will replace and compile the content of the element with the loaded template.
  21340. // We need this directive so that the element content is already filled when
  21341. // the link function of another directive on the same element as ngInclude
  21342. // is called.
  21343. var ngIncludeFillContentDirective = ['$compile',
  21344. function($compile) {
  21345. return {
  21346. restrict: 'ECA',
  21347. priority: -400,
  21348. require: 'ngInclude',
  21349. link: function(scope, $element, $attr, ctrl) {
  21350. if (/SVG/.test($element[0].toString())) {
  21351. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21352. // support innerHTML, so detect this here and try to generate the contents
  21353. // specially.
  21354. $element.empty();
  21355. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21356. function namespaceAdaptedClone(clone) {
  21357. $element.append(clone);
  21358. }, {futureParentElement: $element});
  21359. return;
  21360. }
  21361. $element.html(ctrl.template);
  21362. $compile($element.contents())(scope);
  21363. }
  21364. };
  21365. }];
  21366. /**
  21367. * @ngdoc directive
  21368. * @name ngInit
  21369. * @restrict AC
  21370. *
  21371. * @description
  21372. * The `ngInit` directive allows you to evaluate an expression in the
  21373. * current scope.
  21374. *
  21375. * <div class="alert alert-error">
  21376. * The only appropriate use of `ngInit` is for aliasing special properties of
  21377. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21378. * should use {@link guide/controller controllers} rather than `ngInit`
  21379. * to initialize values on a scope.
  21380. * </div>
  21381. * <div class="alert alert-warning">
  21382. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21383. * sure you have parenthesis for correct precedence:
  21384. * <pre class="prettyprint">
  21385. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  21386. * </pre>
  21387. * </div>
  21388. *
  21389. * @priority 450
  21390. *
  21391. * @element ANY
  21392. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21393. *
  21394. * @example
  21395. <example module="initExample">
  21396. <file name="index.html">
  21397. <script>
  21398. angular.module('initExample', [])
  21399. .controller('ExampleController', ['$scope', function($scope) {
  21400. $scope.list = [['a', 'b'], ['c', 'd']];
  21401. }]);
  21402. </script>
  21403. <div ng-controller="ExampleController">
  21404. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  21405. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  21406. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  21407. </div>
  21408. </div>
  21409. </div>
  21410. </file>
  21411. <file name="protractor.js" type="protractor">
  21412. it('should alias index positions', function() {
  21413. var elements = element.all(by.css('.example-init'));
  21414. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  21415. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  21416. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  21417. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  21418. });
  21419. </file>
  21420. </example>
  21421. */
  21422. var ngInitDirective = ngDirective({
  21423. priority: 450,
  21424. compile: function() {
  21425. return {
  21426. pre: function(scope, element, attrs) {
  21427. scope.$eval(attrs.ngInit);
  21428. }
  21429. };
  21430. }
  21431. });
  21432. /**
  21433. * @ngdoc directive
  21434. * @name ngNonBindable
  21435. * @restrict AC
  21436. * @priority 1000
  21437. *
  21438. * @description
  21439. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21440. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21441. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21442. * displays snippets of code, for instance.
  21443. *
  21444. * @element ANY
  21445. *
  21446. * @example
  21447. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21448. * but the one wrapped in `ngNonBindable` is left alone.
  21449. *
  21450. * @example
  21451. <example>
  21452. <file name="index.html">
  21453. <div>Normal: {{1 + 2}}</div>
  21454. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21455. </file>
  21456. <file name="protractor.js" type="protractor">
  21457. it('should check ng-non-bindable', function() {
  21458. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21459. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21460. });
  21461. </file>
  21462. </example>
  21463. */
  21464. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21465. /**
  21466. * @ngdoc directive
  21467. * @name ngPluralize
  21468. * @restrict EA
  21469. *
  21470. * @description
  21471. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21472. * These rules are bundled with angular.js, but can be overridden
  21473. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21474. * by specifying the mappings between
  21475. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21476. * and the strings to be displayed.
  21477. *
  21478. * # Plural categories and explicit number rules
  21479. * There are two
  21480. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21481. * in Angular's default en-US locale: "one" and "other".
  21482. *
  21483. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21484. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21485. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21486. * and explicit number rules throughout the rest of this documentation.
  21487. *
  21488. * # Configuring ngPluralize
  21489. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21490. * You can also provide an optional attribute, `offset`.
  21491. *
  21492. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21493. * Angular expression}; these are evaluated on the current scope for its bound value.
  21494. *
  21495. * The `when` attribute specifies the mappings between plural categories and the actual
  21496. * string to be displayed. The value of the attribute should be a JSON object.
  21497. *
  21498. * The following example shows how to configure ngPluralize:
  21499. *
  21500. * ```html
  21501. * <ng-pluralize count="personCount"
  21502. when="{'0': 'Nobody is viewing.',
  21503. * 'one': '1 person is viewing.',
  21504. * 'other': '{} people are viewing.'}">
  21505. * </ng-pluralize>
  21506. *```
  21507. *
  21508. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21509. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21510. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21511. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21512. * show "a dozen people are viewing".
  21513. *
  21514. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21515. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21516. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21517. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21518. *
  21519. * # Configuring ngPluralize with offset
  21520. * The `offset` attribute allows further customization of pluralized text, which can result in
  21521. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21522. * you might display "John, Kate and 2 others are viewing this document".
  21523. * The offset attribute allows you to offset a number by any desired value.
  21524. * Let's take a look at an example:
  21525. *
  21526. * ```html
  21527. * <ng-pluralize count="personCount" offset=2
  21528. * when="{'0': 'Nobody is viewing.',
  21529. * '1': '{{person1}} is viewing.',
  21530. * '2': '{{person1}} and {{person2}} are viewing.',
  21531. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21532. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21533. * </ng-pluralize>
  21534. * ```
  21535. *
  21536. * Notice that we are still using two plural categories(one, other), but we added
  21537. * three explicit number rules 0, 1 and 2.
  21538. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21539. * When three people view the document, no explicit number rule is found, so
  21540. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21541. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21542. * is shown.
  21543. *
  21544. * Note that when you specify offsets, you must provide explicit number rules for
  21545. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21546. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21547. * plural categories "one" and "other".
  21548. *
  21549. * @param {string|expression} count The variable to be bound to.
  21550. * @param {string} when The mapping between plural category to its corresponding strings.
  21551. * @param {number=} offset Offset to deduct from the total number.
  21552. *
  21553. * @example
  21554. <example module="pluralizeExample">
  21555. <file name="index.html">
  21556. <script>
  21557. angular.module('pluralizeExample', [])
  21558. .controller('ExampleController', ['$scope', function($scope) {
  21559. $scope.person1 = 'Igor';
  21560. $scope.person2 = 'Misko';
  21561. $scope.personCount = 1;
  21562. }]);
  21563. </script>
  21564. <div ng-controller="ExampleController">
  21565. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21566. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21567. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21568. <!--- Example with simple pluralization rules for en locale --->
  21569. Without Offset:
  21570. <ng-pluralize count="personCount"
  21571. when="{'0': 'Nobody is viewing.',
  21572. 'one': '1 person is viewing.',
  21573. 'other': '{} people are viewing.'}">
  21574. </ng-pluralize><br>
  21575. <!--- Example with offset --->
  21576. With Offset(2):
  21577. <ng-pluralize count="personCount" offset=2
  21578. when="{'0': 'Nobody is viewing.',
  21579. '1': '{{person1}} is viewing.',
  21580. '2': '{{person1}} and {{person2}} are viewing.',
  21581. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21582. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21583. </ng-pluralize>
  21584. </div>
  21585. </file>
  21586. <file name="protractor.js" type="protractor">
  21587. it('should show correct pluralized string', function() {
  21588. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21589. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21590. var countInput = element(by.model('personCount'));
  21591. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21592. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21593. countInput.clear();
  21594. countInput.sendKeys('0');
  21595. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21596. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21597. countInput.clear();
  21598. countInput.sendKeys('2');
  21599. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21600. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21601. countInput.clear();
  21602. countInput.sendKeys('3');
  21603. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21604. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21605. countInput.clear();
  21606. countInput.sendKeys('4');
  21607. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21608. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21609. });
  21610. it('should show data-bound names', function() {
  21611. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21612. var personCount = element(by.model('personCount'));
  21613. var person1 = element(by.model('person1'));
  21614. var person2 = element(by.model('person2'));
  21615. personCount.clear();
  21616. personCount.sendKeys('4');
  21617. person1.clear();
  21618. person1.sendKeys('Di');
  21619. person2.clear();
  21620. person2.sendKeys('Vojta');
  21621. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21622. });
  21623. </file>
  21624. </example>
  21625. */
  21626. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21627. var BRACE = /{}/g;
  21628. return {
  21629. restrict: 'EA',
  21630. link: function(scope, element, attr) {
  21631. var numberExp = attr.count,
  21632. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21633. offset = attr.offset || 0,
  21634. whens = scope.$eval(whenExp) || {},
  21635. whensExpFns = {},
  21636. startSymbol = $interpolate.startSymbol(),
  21637. endSymbol = $interpolate.endSymbol(),
  21638. isWhen = /^when(Minus)?(.+)$/;
  21639. forEach(attr, function(expression, attributeName) {
  21640. if (isWhen.test(attributeName)) {
  21641. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  21642. element.attr(attr.$attr[attributeName]);
  21643. }
  21644. });
  21645. forEach(whens, function(expression, key) {
  21646. whensExpFns[key] =
  21647. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  21648. offset + endSymbol));
  21649. });
  21650. scope.$watch(function ngPluralizeWatch() {
  21651. var value = parseFloat(scope.$eval(numberExp));
  21652. if (!isNaN(value)) {
  21653. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  21654. //check it against pluralization rules in $locale service
  21655. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  21656. return whensExpFns[value](scope);
  21657. } else {
  21658. return '';
  21659. }
  21660. }, function ngPluralizeWatchAction(newVal) {
  21661. element.text(newVal);
  21662. });
  21663. }
  21664. };
  21665. }];
  21666. /**
  21667. * @ngdoc directive
  21668. * @name ngRepeat
  21669. *
  21670. * @description
  21671. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  21672. * instance gets its own scope, where the given loop variable is set to the current collection item,
  21673. * and `$index` is set to the item index or key.
  21674. *
  21675. * Special properties are exposed on the local scope of each template instance, including:
  21676. *
  21677. * | Variable | Type | Details |
  21678. * |-----------|-----------------|-----------------------------------------------------------------------------|
  21679. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  21680. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  21681. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  21682. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  21683. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  21684. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  21685. *
  21686. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  21687. * This may be useful when, for instance, nesting ngRepeats.
  21688. *
  21689. * # Special repeat start and end points
  21690. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  21691. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  21692. * 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)
  21693. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  21694. *
  21695. * The example below makes use of this feature:
  21696. * ```html
  21697. * <header ng-repeat-start="item in items">
  21698. * Header {{ item }}
  21699. * </header>
  21700. * <div class="body">
  21701. * Body {{ item }}
  21702. * </div>
  21703. * <footer ng-repeat-end>
  21704. * Footer {{ item }}
  21705. * </footer>
  21706. * ```
  21707. *
  21708. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  21709. * ```html
  21710. * <header>
  21711. * Header A
  21712. * </header>
  21713. * <div class="body">
  21714. * Body A
  21715. * </div>
  21716. * <footer>
  21717. * Footer A
  21718. * </footer>
  21719. * <header>
  21720. * Header B
  21721. * </header>
  21722. * <div class="body">
  21723. * Body B
  21724. * </div>
  21725. * <footer>
  21726. * Footer B
  21727. * </footer>
  21728. * ```
  21729. *
  21730. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  21731. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  21732. *
  21733. * @animations
  21734. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  21735. *
  21736. * **.leave** - when an item is removed from the list or when an item is filtered out
  21737. *
  21738. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  21739. *
  21740. * @element ANY
  21741. * @scope
  21742. * @priority 1000
  21743. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  21744. * formats are currently supported:
  21745. *
  21746. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  21747. * is a scope expression giving the collection to enumerate.
  21748. *
  21749. * For example: `album in artist.albums`.
  21750. *
  21751. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  21752. * and `expression` is the scope expression giving the collection to enumerate.
  21753. *
  21754. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  21755. *
  21756. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  21757. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  21758. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  21759. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  21760. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  21761. * before specifying a tracking expression.
  21762. *
  21763. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  21764. * will be associated by item identity in the array.
  21765. *
  21766. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  21767. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  21768. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  21769. * element in the same way in the DOM.
  21770. *
  21771. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  21772. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  21773. * property is same.
  21774. *
  21775. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  21776. * to items in conjunction with a tracking expression.
  21777. *
  21778. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  21779. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  21780. * when a filter is active on the repeater, but the filtered result set is empty.
  21781. *
  21782. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  21783. * the items have been processed through the filter.
  21784. *
  21785. * @example
  21786. * This example initializes the scope to a list of names and
  21787. * then uses `ngRepeat` to display every person:
  21788. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21789. <file name="index.html">
  21790. <div ng-init="friends = [
  21791. {name:'John', age:25, gender:'boy'},
  21792. {name:'Jessie', age:30, gender:'girl'},
  21793. {name:'Johanna', age:28, gender:'girl'},
  21794. {name:'Joy', age:15, gender:'girl'},
  21795. {name:'Mary', age:28, gender:'girl'},
  21796. {name:'Peter', age:95, gender:'boy'},
  21797. {name:'Sebastian', age:50, gender:'boy'},
  21798. {name:'Erika', age:27, gender:'girl'},
  21799. {name:'Patrick', age:40, gender:'boy'},
  21800. {name:'Samantha', age:60, gender:'girl'}
  21801. ]">
  21802. I have {{friends.length}} friends. They are:
  21803. <input type="search" ng-model="q" placeholder="filter friends..." />
  21804. <ul class="example-animate-container">
  21805. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  21806. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  21807. </li>
  21808. <li class="animate-repeat" ng-if="results.length == 0">
  21809. <strong>No results found...</strong>
  21810. </li>
  21811. </ul>
  21812. </div>
  21813. </file>
  21814. <file name="animations.css">
  21815. .example-animate-container {
  21816. background:white;
  21817. border:1px solid black;
  21818. list-style:none;
  21819. margin:0;
  21820. padding:0 10px;
  21821. }
  21822. .animate-repeat {
  21823. line-height:40px;
  21824. list-style:none;
  21825. box-sizing:border-box;
  21826. }
  21827. .animate-repeat.ng-move,
  21828. .animate-repeat.ng-enter,
  21829. .animate-repeat.ng-leave {
  21830. -webkit-transition:all linear 0.5s;
  21831. transition:all linear 0.5s;
  21832. }
  21833. .animate-repeat.ng-leave.ng-leave-active,
  21834. .animate-repeat.ng-move,
  21835. .animate-repeat.ng-enter {
  21836. opacity:0;
  21837. max-height:0;
  21838. }
  21839. .animate-repeat.ng-leave,
  21840. .animate-repeat.ng-move.ng-move-active,
  21841. .animate-repeat.ng-enter.ng-enter-active {
  21842. opacity:1;
  21843. max-height:40px;
  21844. }
  21845. </file>
  21846. <file name="protractor.js" type="protractor">
  21847. var friends = element.all(by.repeater('friend in friends'));
  21848. it('should render initial data set', function() {
  21849. expect(friends.count()).toBe(10);
  21850. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  21851. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  21852. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  21853. expect(element(by.binding('friends.length')).getText())
  21854. .toMatch("I have 10 friends. They are:");
  21855. });
  21856. it('should update repeater when filter predicate changes', function() {
  21857. expect(friends.count()).toBe(10);
  21858. element(by.model('q')).sendKeys('ma');
  21859. expect(friends.count()).toBe(2);
  21860. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  21861. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  21862. });
  21863. </file>
  21864. </example>
  21865. */
  21866. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  21867. var NG_REMOVED = '$$NG_REMOVED';
  21868. var ngRepeatMinErr = minErr('ngRepeat');
  21869. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  21870. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  21871. scope[valueIdentifier] = value;
  21872. if (keyIdentifier) scope[keyIdentifier] = key;
  21873. scope.$index = index;
  21874. scope.$first = (index === 0);
  21875. scope.$last = (index === (arrayLength - 1));
  21876. scope.$middle = !(scope.$first || scope.$last);
  21877. // jshint bitwise: false
  21878. scope.$odd = !(scope.$even = (index&1) === 0);
  21879. // jshint bitwise: true
  21880. };
  21881. var getBlockStart = function(block) {
  21882. return block.clone[0];
  21883. };
  21884. var getBlockEnd = function(block) {
  21885. return block.clone[block.clone.length - 1];
  21886. };
  21887. return {
  21888. restrict: 'A',
  21889. multiElement: true,
  21890. transclude: 'element',
  21891. priority: 1000,
  21892. terminal: true,
  21893. $$tlb: true,
  21894. compile: function ngRepeatCompile($element, $attr) {
  21895. var expression = $attr.ngRepeat;
  21896. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  21897. 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*$/);
  21898. if (!match) {
  21899. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  21900. expression);
  21901. }
  21902. var lhs = match[1];
  21903. var rhs = match[2];
  21904. var aliasAs = match[3];
  21905. var trackByExp = match[4];
  21906. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  21907. if (!match) {
  21908. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  21909. lhs);
  21910. }
  21911. var valueIdentifier = match[3] || match[1];
  21912. var keyIdentifier = match[2];
  21913. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  21914. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) {
  21915. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  21916. aliasAs);
  21917. }
  21918. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  21919. var hashFnLocals = {$id: hashKey};
  21920. if (trackByExp) {
  21921. trackByExpGetter = $parse(trackByExp);
  21922. } else {
  21923. trackByIdArrayFn = function(key, value) {
  21924. return hashKey(value);
  21925. };
  21926. trackByIdObjFn = function(key) {
  21927. return key;
  21928. };
  21929. }
  21930. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  21931. if (trackByExpGetter) {
  21932. trackByIdExpFn = function(key, value, index) {
  21933. // assign key, value, and $index to the locals so that they can be used in hash functions
  21934. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  21935. hashFnLocals[valueIdentifier] = value;
  21936. hashFnLocals.$index = index;
  21937. return trackByExpGetter($scope, hashFnLocals);
  21938. };
  21939. }
  21940. // Store a list of elements from previous run. This is a hash where key is the item from the
  21941. // iterator, and the value is objects with following properties.
  21942. // - scope: bound scope
  21943. // - element: previous element.
  21944. // - index: position
  21945. //
  21946. // We are using no-proto object so that we don't need to guard against inherited props via
  21947. // hasOwnProperty.
  21948. var lastBlockMap = createMap();
  21949. //watch props
  21950. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  21951. var index, length,
  21952. previousNode = $element[0], // node that cloned nodes should be inserted after
  21953. // initialized to the comment node anchor
  21954. nextNode,
  21955. // Same as lastBlockMap but it has the current state. It will become the
  21956. // lastBlockMap on the next iteration.
  21957. nextBlockMap = createMap(),
  21958. collectionLength,
  21959. key, value, // key/value of iteration
  21960. trackById,
  21961. trackByIdFn,
  21962. collectionKeys,
  21963. block, // last object information {scope, element, id}
  21964. nextBlockOrder,
  21965. elementsToRemove;
  21966. if (aliasAs) {
  21967. $scope[aliasAs] = collection;
  21968. }
  21969. if (isArrayLike(collection)) {
  21970. collectionKeys = collection;
  21971. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  21972. } else {
  21973. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  21974. // if object, extract keys, sort them and use to determine order of iteration over obj props
  21975. collectionKeys = [];
  21976. for (var itemKey in collection) {
  21977. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  21978. collectionKeys.push(itemKey);
  21979. }
  21980. }
  21981. collectionKeys.sort();
  21982. }
  21983. collectionLength = collectionKeys.length;
  21984. nextBlockOrder = new Array(collectionLength);
  21985. // locate existing items
  21986. for (index = 0; index < collectionLength; index++) {
  21987. key = (collection === collectionKeys) ? index : collectionKeys[index];
  21988. value = collection[key];
  21989. trackById = trackByIdFn(key, value, index);
  21990. if (lastBlockMap[trackById]) {
  21991. // found previously seen block
  21992. block = lastBlockMap[trackById];
  21993. delete lastBlockMap[trackById];
  21994. nextBlockMap[trackById] = block;
  21995. nextBlockOrder[index] = block;
  21996. } else if (nextBlockMap[trackById]) {
  21997. // if collision detected. restore lastBlockMap and throw an error
  21998. forEach(nextBlockOrder, function(block) {
  21999. if (block && block.scope) lastBlockMap[block.id] = block;
  22000. });
  22001. throw ngRepeatMinErr('dupes',
  22002. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  22003. expression, trackById, toJson(value));
  22004. } else {
  22005. // new never before seen block
  22006. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  22007. nextBlockMap[trackById] = true;
  22008. }
  22009. }
  22010. // remove leftover items
  22011. for (var blockKey in lastBlockMap) {
  22012. block = lastBlockMap[blockKey];
  22013. elementsToRemove = getBlockNodes(block.clone);
  22014. $animate.leave(elementsToRemove);
  22015. if (elementsToRemove[0].parentNode) {
  22016. // if the element was not removed yet because of pending animation, mark it as deleted
  22017. // so that we can ignore it later
  22018. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  22019. elementsToRemove[index][NG_REMOVED] = true;
  22020. }
  22021. }
  22022. block.scope.$destroy();
  22023. }
  22024. // we are not using forEach for perf reasons (trying to avoid #call)
  22025. for (index = 0; index < collectionLength; index++) {
  22026. key = (collection === collectionKeys) ? index : collectionKeys[index];
  22027. value = collection[key];
  22028. block = nextBlockOrder[index];
  22029. if (block.scope) {
  22030. // if we have already seen this object, then we need to reuse the
  22031. // associated scope/element
  22032. nextNode = previousNode;
  22033. // skip nodes that are already pending removal via leave animation
  22034. do {
  22035. nextNode = nextNode.nextSibling;
  22036. } while (nextNode && nextNode[NG_REMOVED]);
  22037. if (getBlockStart(block) != nextNode) {
  22038. // existing item which got moved
  22039. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  22040. }
  22041. previousNode = getBlockEnd(block);
  22042. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22043. } else {
  22044. // new item which we don't know about
  22045. $transclude(function ngRepeatTransclude(clone, scope) {
  22046. block.scope = scope;
  22047. // http://jsperf.com/clone-vs-createcomment
  22048. var endNode = ngRepeatEndComment.cloneNode(false);
  22049. clone[clone.length++] = endNode;
  22050. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  22051. $animate.enter(clone, null, jqLite(previousNode));
  22052. previousNode = endNode;
  22053. // Note: We only need the first/last node of the cloned nodes.
  22054. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22055. // by a directive with templateUrl when its template arrives.
  22056. block.clone = clone;
  22057. nextBlockMap[block.id] = block;
  22058. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  22059. });
  22060. }
  22061. }
  22062. lastBlockMap = nextBlockMap;
  22063. });
  22064. };
  22065. }
  22066. };
  22067. }];
  22068. var NG_HIDE_CLASS = 'ng-hide';
  22069. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  22070. /**
  22071. * @ngdoc directive
  22072. * @name ngShow
  22073. *
  22074. * @description
  22075. * The `ngShow` directive shows or hides the given HTML element based on the expression
  22076. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  22077. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22078. * in AngularJS and sets the display style to none (using an !important flag).
  22079. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22080. *
  22081. * ```html
  22082. * <!-- when $scope.myValue is truthy (element is visible) -->
  22083. * <div ng-show="myValue"></div>
  22084. *
  22085. * <!-- when $scope.myValue is falsy (element is hidden) -->
  22086. * <div ng-show="myValue" class="ng-hide"></div>
  22087. * ```
  22088. *
  22089. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  22090. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  22091. * from the element causing the element not to appear hidden.
  22092. *
  22093. * ## Why is !important used?
  22094. *
  22095. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22096. * can be easily overridden by heavier selectors. For example, something as simple
  22097. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22098. * This also becomes a bigger issue when dealing with CSS frameworks.
  22099. *
  22100. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22101. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22102. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22103. *
  22104. * ### Overriding `.ng-hide`
  22105. *
  22106. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  22107. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22108. * class in CSS:
  22109. *
  22110. * ```css
  22111. * .ng-hide {
  22112. * /&#42; this is just another form of hiding an element &#42;/
  22113. * display:block!important;
  22114. * position:absolute;
  22115. * top:-9999px;
  22116. * left:-9999px;
  22117. * }
  22118. * ```
  22119. *
  22120. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22121. *
  22122. * ## A note about animations with `ngShow`
  22123. *
  22124. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22125. * is true and false. This system works like the animation system present with ngClass except that
  22126. * you must also include the !important flag to override the display property
  22127. * so that you can perform an animation when the element is hidden during the time of the animation.
  22128. *
  22129. * ```css
  22130. * //
  22131. * //a working example can be found at the bottom of this page
  22132. * //
  22133. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22134. * /&#42; this is required as of 1.3x to properly
  22135. * apply all styling in a show/hide animation &#42;/
  22136. * transition:0s linear all;
  22137. * }
  22138. *
  22139. * .my-element.ng-hide-add-active,
  22140. * .my-element.ng-hide-remove-active {
  22141. * /&#42; the transition is defined in the active class &#42;/
  22142. * transition:1s linear all;
  22143. * }
  22144. *
  22145. * .my-element.ng-hide-add { ... }
  22146. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22147. * .my-element.ng-hide-remove { ... }
  22148. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22149. * ```
  22150. *
  22151. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22152. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22153. *
  22154. * @animations
  22155. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22156. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22157. *
  22158. * @element ANY
  22159. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22160. * then the element is shown or hidden respectively.
  22161. *
  22162. * @example
  22163. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22164. <file name="index.html">
  22165. Click me: <input type="checkbox" ng-model="checked"><br/>
  22166. <div>
  22167. Show:
  22168. <div class="check-element animate-show" ng-show="checked">
  22169. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22170. </div>
  22171. </div>
  22172. <div>
  22173. Hide:
  22174. <div class="check-element animate-show" ng-hide="checked">
  22175. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22176. </div>
  22177. </div>
  22178. </file>
  22179. <file name="glyphicons.css">
  22180. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22181. </file>
  22182. <file name="animations.css">
  22183. .animate-show {
  22184. line-height:20px;
  22185. opacity:1;
  22186. padding:10px;
  22187. border:1px solid black;
  22188. background:white;
  22189. }
  22190. .animate-show.ng-hide-add.ng-hide-add-active,
  22191. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22192. -webkit-transition:all linear 0.5s;
  22193. transition:all linear 0.5s;
  22194. }
  22195. .animate-show.ng-hide {
  22196. line-height:0;
  22197. opacity:0;
  22198. padding:0 10px;
  22199. }
  22200. .check-element {
  22201. padding:10px;
  22202. border:1px solid black;
  22203. background:white;
  22204. }
  22205. </file>
  22206. <file name="protractor.js" type="protractor">
  22207. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22208. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22209. it('should check ng-show / ng-hide', function() {
  22210. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22211. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22212. element(by.model('checked')).click();
  22213. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22214. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22215. });
  22216. </file>
  22217. </example>
  22218. */
  22219. var ngShowDirective = ['$animate', function($animate) {
  22220. return {
  22221. restrict: 'A',
  22222. multiElement: true,
  22223. link: function(scope, element, attr) {
  22224. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  22225. // we're adding a temporary, animation-specific class for ng-hide since this way
  22226. // we can control when the element is actually displayed on screen without having
  22227. // to have a global/greedy CSS selector that breaks when other animations are run.
  22228. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22229. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22230. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22231. });
  22232. });
  22233. }
  22234. };
  22235. }];
  22236. /**
  22237. * @ngdoc directive
  22238. * @name ngHide
  22239. *
  22240. * @description
  22241. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22242. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22243. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22244. * in AngularJS and sets the display style to none (using an !important flag).
  22245. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22246. *
  22247. * ```html
  22248. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22249. * <div ng-hide="myValue" class="ng-hide"></div>
  22250. *
  22251. * <!-- when $scope.myValue is falsy (element is visible) -->
  22252. * <div ng-hide="myValue"></div>
  22253. * ```
  22254. *
  22255. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22256. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22257. * from the element causing the element not to appear hidden.
  22258. *
  22259. * ## Why is !important used?
  22260. *
  22261. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22262. * can be easily overridden by heavier selectors. For example, something as simple
  22263. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22264. * This also becomes a bigger issue when dealing with CSS frameworks.
  22265. *
  22266. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22267. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22268. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22269. *
  22270. * ### Overriding `.ng-hide`
  22271. *
  22272. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  22273. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22274. * class in CSS:
  22275. *
  22276. * ```css
  22277. * .ng-hide {
  22278. * /&#42; this is just another form of hiding an element &#42;/
  22279. * display:block!important;
  22280. * position:absolute;
  22281. * top:-9999px;
  22282. * left:-9999px;
  22283. * }
  22284. * ```
  22285. *
  22286. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22287. *
  22288. * ## A note about animations with `ngHide`
  22289. *
  22290. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22291. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22292. * CSS class is added and removed for you instead of your own CSS class.
  22293. *
  22294. * ```css
  22295. * //
  22296. * //a working example can be found at the bottom of this page
  22297. * //
  22298. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22299. * transition:0.5s linear all;
  22300. * }
  22301. *
  22302. * .my-element.ng-hide-add { ... }
  22303. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22304. * .my-element.ng-hide-remove { ... }
  22305. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22306. * ```
  22307. *
  22308. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22309. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22310. *
  22311. * @animations
  22312. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22313. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22314. *
  22315. * @element ANY
  22316. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22317. * the element is shown or hidden respectively.
  22318. *
  22319. * @example
  22320. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22321. <file name="index.html">
  22322. Click me: <input type="checkbox" ng-model="checked"><br/>
  22323. <div>
  22324. Show:
  22325. <div class="check-element animate-hide" ng-show="checked">
  22326. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22327. </div>
  22328. </div>
  22329. <div>
  22330. Hide:
  22331. <div class="check-element animate-hide" ng-hide="checked">
  22332. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22333. </div>
  22334. </div>
  22335. </file>
  22336. <file name="glyphicons.css">
  22337. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  22338. </file>
  22339. <file name="animations.css">
  22340. .animate-hide {
  22341. -webkit-transition:all linear 0.5s;
  22342. transition:all linear 0.5s;
  22343. line-height:20px;
  22344. opacity:1;
  22345. padding:10px;
  22346. border:1px solid black;
  22347. background:white;
  22348. }
  22349. .animate-hide.ng-hide {
  22350. line-height:0;
  22351. opacity:0;
  22352. padding:0 10px;
  22353. }
  22354. .check-element {
  22355. padding:10px;
  22356. border:1px solid black;
  22357. background:white;
  22358. }
  22359. </file>
  22360. <file name="protractor.js" type="protractor">
  22361. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22362. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22363. it('should check ng-show / ng-hide', function() {
  22364. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22365. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22366. element(by.model('checked')).click();
  22367. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22368. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22369. });
  22370. </file>
  22371. </example>
  22372. */
  22373. var ngHideDirective = ['$animate', function($animate) {
  22374. return {
  22375. restrict: 'A',
  22376. multiElement: true,
  22377. link: function(scope, element, attr) {
  22378. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  22379. // The comment inside of the ngShowDirective explains why we add and
  22380. // remove a temporary class for the show/hide animation
  22381. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22382. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  22383. });
  22384. });
  22385. }
  22386. };
  22387. }];
  22388. /**
  22389. * @ngdoc directive
  22390. * @name ngStyle
  22391. * @restrict AC
  22392. *
  22393. * @description
  22394. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22395. *
  22396. * @element ANY
  22397. * @param {expression} ngStyle
  22398. *
  22399. * {@link guide/expression Expression} which evals to an
  22400. * object whose keys are CSS style names and values are corresponding values for those CSS
  22401. * keys.
  22402. *
  22403. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22404. * See the 'background-color' style in the example below.
  22405. *
  22406. * @example
  22407. <example>
  22408. <file name="index.html">
  22409. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22410. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22411. <input type="button" value="clear" ng-click="myStyle={}">
  22412. <br/>
  22413. <span ng-style="myStyle">Sample Text</span>
  22414. <pre>myStyle={{myStyle}}</pre>
  22415. </file>
  22416. <file name="style.css">
  22417. span {
  22418. color: black;
  22419. }
  22420. </file>
  22421. <file name="protractor.js" type="protractor">
  22422. var colorSpan = element(by.css('span'));
  22423. it('should check ng-style', function() {
  22424. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22425. element(by.css('input[value=\'set color\']')).click();
  22426. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22427. element(by.css('input[value=clear]')).click();
  22428. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22429. });
  22430. </file>
  22431. </example>
  22432. */
  22433. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22434. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22435. if (oldStyles && (newStyles !== oldStyles)) {
  22436. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22437. }
  22438. if (newStyles) element.css(newStyles);
  22439. }, true);
  22440. });
  22441. /**
  22442. * @ngdoc directive
  22443. * @name ngSwitch
  22444. * @restrict EA
  22445. *
  22446. * @description
  22447. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22448. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22449. * as specified in the template.
  22450. *
  22451. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22452. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22453. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22454. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22455. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22456. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22457. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22458. * attribute is displayed.
  22459. *
  22460. * <div class="alert alert-info">
  22461. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22462. * as literal string values to match against.
  22463. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22464. * value of the expression `$scope.someVal`.
  22465. * </div>
  22466. * @animations
  22467. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22468. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22469. *
  22470. * @usage
  22471. *
  22472. * ```
  22473. * <ANY ng-switch="expression">
  22474. * <ANY ng-switch-when="matchValue1">...</ANY>
  22475. * <ANY ng-switch-when="matchValue2">...</ANY>
  22476. * <ANY ng-switch-default>...</ANY>
  22477. * </ANY>
  22478. * ```
  22479. *
  22480. *
  22481. * @scope
  22482. * @priority 1200
  22483. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22484. * On child elements add:
  22485. *
  22486. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22487. * case will be displayed. If the same match appears multiple times, all the
  22488. * elements will be displayed.
  22489. * * `ngSwitchDefault`: the default case when no other case match. If there
  22490. * are multiple default cases, all of them will be displayed when no other
  22491. * case match.
  22492. *
  22493. *
  22494. * @example
  22495. <example module="switchExample" deps="angular-animate.js" animations="true">
  22496. <file name="index.html">
  22497. <div ng-controller="ExampleController">
  22498. <select ng-model="selection" ng-options="item for item in items">
  22499. </select>
  22500. <tt>selection={{selection}}</tt>
  22501. <hr/>
  22502. <div class="animate-switch-container"
  22503. ng-switch on="selection">
  22504. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22505. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22506. <div class="animate-switch" ng-switch-default>default</div>
  22507. </div>
  22508. </div>
  22509. </file>
  22510. <file name="script.js">
  22511. angular.module('switchExample', ['ngAnimate'])
  22512. .controller('ExampleController', ['$scope', function($scope) {
  22513. $scope.items = ['settings', 'home', 'other'];
  22514. $scope.selection = $scope.items[0];
  22515. }]);
  22516. </file>
  22517. <file name="animations.css">
  22518. .animate-switch-container {
  22519. position:relative;
  22520. background:white;
  22521. border:1px solid black;
  22522. height:40px;
  22523. overflow:hidden;
  22524. }
  22525. .animate-switch {
  22526. padding:10px;
  22527. }
  22528. .animate-switch.ng-animate {
  22529. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22530. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22531. position:absolute;
  22532. top:0;
  22533. left:0;
  22534. right:0;
  22535. bottom:0;
  22536. }
  22537. .animate-switch.ng-leave.ng-leave-active,
  22538. .animate-switch.ng-enter {
  22539. top:-50px;
  22540. }
  22541. .animate-switch.ng-leave,
  22542. .animate-switch.ng-enter.ng-enter-active {
  22543. top:0;
  22544. }
  22545. </file>
  22546. <file name="protractor.js" type="protractor">
  22547. var switchElem = element(by.css('[ng-switch]'));
  22548. var select = element(by.model('selection'));
  22549. it('should start in settings', function() {
  22550. expect(switchElem.getText()).toMatch(/Settings Div/);
  22551. });
  22552. it('should change to home', function() {
  22553. select.all(by.css('option')).get(1).click();
  22554. expect(switchElem.getText()).toMatch(/Home Span/);
  22555. });
  22556. it('should select default', function() {
  22557. select.all(by.css('option')).get(2).click();
  22558. expect(switchElem.getText()).toMatch(/default/);
  22559. });
  22560. </file>
  22561. </example>
  22562. */
  22563. var ngSwitchDirective = ['$animate', function($animate) {
  22564. return {
  22565. restrict: 'EA',
  22566. require: 'ngSwitch',
  22567. // asks for $scope to fool the BC controller module
  22568. controller: ['$scope', function ngSwitchController() {
  22569. this.cases = {};
  22570. }],
  22571. link: function(scope, element, attr, ngSwitchController) {
  22572. var watchExpr = attr.ngSwitch || attr.on,
  22573. selectedTranscludes = [],
  22574. selectedElements = [],
  22575. previousLeaveAnimations = [],
  22576. selectedScopes = [];
  22577. var spliceFactory = function(array, index) {
  22578. return function() { array.splice(index, 1); };
  22579. };
  22580. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  22581. var i, ii;
  22582. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  22583. $animate.cancel(previousLeaveAnimations[i]);
  22584. }
  22585. previousLeaveAnimations.length = 0;
  22586. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  22587. var selected = getBlockNodes(selectedElements[i].clone);
  22588. selectedScopes[i].$destroy();
  22589. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  22590. promise.then(spliceFactory(previousLeaveAnimations, i));
  22591. }
  22592. selectedElements.length = 0;
  22593. selectedScopes.length = 0;
  22594. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  22595. forEach(selectedTranscludes, function(selectedTransclude) {
  22596. selectedTransclude.transclude(function(caseElement, selectedScope) {
  22597. selectedScopes.push(selectedScope);
  22598. var anchor = selectedTransclude.element;
  22599. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  22600. var block = { clone: caseElement };
  22601. selectedElements.push(block);
  22602. $animate.enter(caseElement, anchor.parent(), anchor);
  22603. });
  22604. });
  22605. }
  22606. });
  22607. }
  22608. };
  22609. }];
  22610. var ngSwitchWhenDirective = ngDirective({
  22611. transclude: 'element',
  22612. priority: 1200,
  22613. require: '^ngSwitch',
  22614. multiElement: true,
  22615. link: function(scope, element, attrs, ctrl, $transclude) {
  22616. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  22617. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  22618. }
  22619. });
  22620. var ngSwitchDefaultDirective = ngDirective({
  22621. transclude: 'element',
  22622. priority: 1200,
  22623. require: '^ngSwitch',
  22624. multiElement: true,
  22625. link: function(scope, element, attr, ctrl, $transclude) {
  22626. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  22627. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  22628. }
  22629. });
  22630. /**
  22631. * @ngdoc directive
  22632. * @name ngTransclude
  22633. * @restrict EAC
  22634. *
  22635. * @description
  22636. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  22637. *
  22638. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  22639. *
  22640. * @element ANY
  22641. *
  22642. * @example
  22643. <example module="transcludeExample">
  22644. <file name="index.html">
  22645. <script>
  22646. angular.module('transcludeExample', [])
  22647. .directive('pane', function(){
  22648. return {
  22649. restrict: 'E',
  22650. transclude: true,
  22651. scope: { title:'@' },
  22652. template: '<div style="border: 1px solid black;">' +
  22653. '<div style="background-color: gray">{{title}}</div>' +
  22654. '<ng-transclude></ng-transclude>' +
  22655. '</div>'
  22656. };
  22657. })
  22658. .controller('ExampleController', ['$scope', function($scope) {
  22659. $scope.title = 'Lorem Ipsum';
  22660. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  22661. }]);
  22662. </script>
  22663. <div ng-controller="ExampleController">
  22664. <input ng-model="title"><br>
  22665. <textarea ng-model="text"></textarea> <br/>
  22666. <pane title="{{title}}">{{text}}</pane>
  22667. </div>
  22668. </file>
  22669. <file name="protractor.js" type="protractor">
  22670. it('should have transcluded', function() {
  22671. var titleElement = element(by.model('title'));
  22672. titleElement.clear();
  22673. titleElement.sendKeys('TITLE');
  22674. var textElement = element(by.model('text'));
  22675. textElement.clear();
  22676. textElement.sendKeys('TEXT');
  22677. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  22678. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  22679. });
  22680. </file>
  22681. </example>
  22682. *
  22683. */
  22684. var ngTranscludeDirective = ngDirective({
  22685. restrict: 'EAC',
  22686. link: function($scope, $element, $attrs, controller, $transclude) {
  22687. if (!$transclude) {
  22688. throw minErr('ngTransclude')('orphan',
  22689. 'Illegal use of ngTransclude directive in the template! ' +
  22690. 'No parent directive that requires a transclusion found. ' +
  22691. 'Element: {0}',
  22692. startingTag($element));
  22693. }
  22694. $transclude(function(clone) {
  22695. $element.empty();
  22696. $element.append(clone);
  22697. });
  22698. }
  22699. });
  22700. /**
  22701. * @ngdoc directive
  22702. * @name script
  22703. * @restrict E
  22704. *
  22705. * @description
  22706. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  22707. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  22708. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  22709. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  22710. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  22711. *
  22712. * @param {string} type Must be set to `'text/ng-template'`.
  22713. * @param {string} id Cache name of the template.
  22714. *
  22715. * @example
  22716. <example>
  22717. <file name="index.html">
  22718. <script type="text/ng-template" id="/tpl.html">
  22719. Content of the template.
  22720. </script>
  22721. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  22722. <div id="tpl-content" ng-include src="currentTpl"></div>
  22723. </file>
  22724. <file name="protractor.js" type="protractor">
  22725. it('should load template defined inside script tag', function() {
  22726. element(by.css('#tpl-link')).click();
  22727. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  22728. });
  22729. </file>
  22730. </example>
  22731. */
  22732. var scriptDirective = ['$templateCache', function($templateCache) {
  22733. return {
  22734. restrict: 'E',
  22735. terminal: true,
  22736. compile: function(element, attr) {
  22737. if (attr.type == 'text/ng-template') {
  22738. var templateUrl = attr.id,
  22739. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  22740. text = element[0].text;
  22741. $templateCache.put(templateUrl, text);
  22742. }
  22743. }
  22744. };
  22745. }];
  22746. var ngOptionsMinErr = minErr('ngOptions');
  22747. /**
  22748. * @ngdoc directive
  22749. * @name select
  22750. * @restrict E
  22751. *
  22752. * @description
  22753. * HTML `SELECT` element with angular data-binding.
  22754. *
  22755. * # `ngOptions`
  22756. *
  22757. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  22758. * elements for the `<select>` element using the array or object obtained by evaluating the
  22759. * `ngOptions` comprehension_expression.
  22760. *
  22761. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  22762. * similar result. However, the `ngOptions` provides some benefits such as reducing memory and
  22763. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  22764. * more flexibility in how the `select`'s model is assigned via `select as`. `ngOptions should be
  22765. * used when the `select` model needs to be bound to a non-string value. This is because an option
  22766. * element can only be bound to string values at present.
  22767. *
  22768. * When an item in the `<select>` menu is selected, the array element or object property
  22769. * represented by the selected option will be bound to the model identified by the `ngModel`
  22770. * directive.
  22771. *
  22772. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  22773. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  22774. * option. See example below for demonstration.
  22775. *
  22776. * <div class="alert alert-warning">
  22777. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  22778. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  22779. * </div>
  22780. *
  22781. * ## `select as`
  22782. *
  22783. * Using `select as` will bind the result of the `select as` expression to the model, but
  22784. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  22785. * or property name (for object data sources) of the value within the collection. If a `track by` expression
  22786. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  22787. *
  22788. * ### `select as` with `trackexpr`
  22789. *
  22790. * Using `select as` together with `trackexpr` is not recommended. Reasoning:
  22791. *
  22792. * - Example: &lt;select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"&gt;
  22793. * values: [{id: 1, label: 'aLabel', subItem: {name: 'aSubItem'}}, {id: 2, label: 'bLabel', subItem: {name: 'bSubItem'}}],
  22794. * $scope.selected = {name: 'aSubItem'};
  22795. * - track by is always applied to `value`, with the purpose of preserving the selection,
  22796. * (to `item` in this case)
  22797. * - to calculate whether an item is selected we do the following:
  22798. * 1. apply `track by` to the values in the array, e.g.
  22799. * In the example: [1,2]
  22800. * 2. apply `track by` to the already selected value in `ngModel`:
  22801. * In the example: this is not possible, as `track by` refers to `item.id`, but the selected
  22802. * value from `ngModel` is `{name: aSubItem}`.
  22803. *
  22804. * @param {string} ngModel Assignable angular expression to data-bind to.
  22805. * @param {string=} name Property name of the form under which the control is published.
  22806. * @param {string=} required The control is considered valid only if value is entered.
  22807. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22808. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22809. * `required` when you want to data-bind to the `required` attribute.
  22810. * @param {comprehension_expression=} ngOptions in one of the following forms:
  22811. *
  22812. * * for array data sources:
  22813. * * `label` **`for`** `value` **`in`** `array`
  22814. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  22815. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  22816. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  22817. * * for object data sources:
  22818. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22819. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22820. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  22821. * * `select` **`as`** `label` **`group by`** `group`
  22822. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  22823. *
  22824. * Where:
  22825. *
  22826. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  22827. * * `value`: local variable which will refer to each item in the `array` or each property value
  22828. * of `object` during iteration.
  22829. * * `key`: local variable which will refer to a property name in `object` during iteration.
  22830. * * `label`: The result of this expression will be the label for `<option>` element. The
  22831. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  22832. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  22833. * element. If not specified, `select` expression will default to `value`.
  22834. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  22835. * DOM element.
  22836. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  22837. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  22838. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  22839. * even when the options are recreated (e.g. reloaded from the server).
  22840. *
  22841. * @example
  22842. <example module="selectExample">
  22843. <file name="index.html">
  22844. <script>
  22845. angular.module('selectExample', [])
  22846. .controller('ExampleController', ['$scope', function($scope) {
  22847. $scope.colors = [
  22848. {name:'black', shade:'dark'},
  22849. {name:'white', shade:'light'},
  22850. {name:'red', shade:'dark'},
  22851. {name:'blue', shade:'dark'},
  22852. {name:'yellow', shade:'light'}
  22853. ];
  22854. $scope.myColor = $scope.colors[2]; // red
  22855. }]);
  22856. </script>
  22857. <div ng-controller="ExampleController">
  22858. <ul>
  22859. <li ng-repeat="color in colors">
  22860. Name: <input ng-model="color.name">
  22861. [<a href ng-click="colors.splice($index, 1)">X</a>]
  22862. </li>
  22863. <li>
  22864. [<a href ng-click="colors.push({})">add</a>]
  22865. </li>
  22866. </ul>
  22867. <hr/>
  22868. Color (null not allowed):
  22869. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  22870. Color (null allowed):
  22871. <span class="nullable">
  22872. <select ng-model="myColor" ng-options="color.name for color in colors">
  22873. <option value="">-- choose color --</option>
  22874. </select>
  22875. </span><br/>
  22876. Color grouped by shade:
  22877. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  22878. </select><br/>
  22879. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  22880. <hr/>
  22881. Currently selected: {{ {selected_color:myColor} }}
  22882. <div style="border:solid 1px black; height:20px"
  22883. ng-style="{'background-color':myColor.name}">
  22884. </div>
  22885. </div>
  22886. </file>
  22887. <file name="protractor.js" type="protractor">
  22888. it('should check ng-options', function() {
  22889. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  22890. element.all(by.model('myColor')).first().click();
  22891. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  22892. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  22893. element(by.css('.nullable select[ng-model="myColor"]')).click();
  22894. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  22895. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  22896. });
  22897. </file>
  22898. </example>
  22899. */
  22900. var ngOptionsDirective = valueFn({
  22901. restrict: 'A',
  22902. terminal: true
  22903. });
  22904. // jshint maxlen: false
  22905. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  22906. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  22907. 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]+?))?$/,
  22908. nullModelCtrl = {$setViewValue: noop};
  22909. // jshint maxlen: 100
  22910. return {
  22911. restrict: 'E',
  22912. require: ['select', '?ngModel'],
  22913. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  22914. var self = this,
  22915. optionsMap = {},
  22916. ngModelCtrl = nullModelCtrl,
  22917. nullOption,
  22918. unknownOption;
  22919. self.databound = $attrs.ngModel;
  22920. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  22921. ngModelCtrl = ngModelCtrl_;
  22922. nullOption = nullOption_;
  22923. unknownOption = unknownOption_;
  22924. };
  22925. self.addOption = function(value, element) {
  22926. assertNotHasOwnProperty(value, '"option value"');
  22927. optionsMap[value] = true;
  22928. if (ngModelCtrl.$viewValue == value) {
  22929. $element.val(value);
  22930. if (unknownOption.parent()) unknownOption.remove();
  22931. }
  22932. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  22933. // Adding an <option selected="selected"> element to a <select required="required"> should
  22934. // automatically select the new element
  22935. if (element && element[0].hasAttribute('selected')) {
  22936. element[0].selected = true;
  22937. }
  22938. };
  22939. self.removeOption = function(value) {
  22940. if (this.hasOption(value)) {
  22941. delete optionsMap[value];
  22942. if (ngModelCtrl.$viewValue == value) {
  22943. this.renderUnknownOption(value);
  22944. }
  22945. }
  22946. };
  22947. self.renderUnknownOption = function(val) {
  22948. var unknownVal = '? ' + hashKey(val) + ' ?';
  22949. unknownOption.val(unknownVal);
  22950. $element.prepend(unknownOption);
  22951. $element.val(unknownVal);
  22952. unknownOption.prop('selected', true); // needed for IE
  22953. };
  22954. self.hasOption = function(value) {
  22955. return optionsMap.hasOwnProperty(value);
  22956. };
  22957. $scope.$on('$destroy', function() {
  22958. // disable unknown option so that we don't do work when the whole select is being destroyed
  22959. self.renderUnknownOption = noop;
  22960. });
  22961. }],
  22962. link: function(scope, element, attr, ctrls) {
  22963. // if ngModel is not defined, we don't need to do anything
  22964. if (!ctrls[1]) return;
  22965. var selectCtrl = ctrls[0],
  22966. ngModelCtrl = ctrls[1],
  22967. multiple = attr.multiple,
  22968. optionsExp = attr.ngOptions,
  22969. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  22970. emptyOption,
  22971. renderScheduled = false,
  22972. // we can't just jqLite('<option>') since jqLite is not smart enough
  22973. // to create it in <select> and IE barfs otherwise.
  22974. optionTemplate = jqLite(document.createElement('option')),
  22975. optGroupTemplate =jqLite(document.createElement('optgroup')),
  22976. unknownOption = optionTemplate.clone();
  22977. // find "null" option
  22978. for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  22979. if (children[i].value === '') {
  22980. emptyOption = nullOption = children.eq(i);
  22981. break;
  22982. }
  22983. }
  22984. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  22985. // required validator
  22986. if (multiple) {
  22987. ngModelCtrl.$isEmpty = function(value) {
  22988. return !value || value.length === 0;
  22989. };
  22990. }
  22991. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  22992. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  22993. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  22994. ////////////////////////////
  22995. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  22996. ngModelCtrl.$render = function() {
  22997. var viewValue = ngModelCtrl.$viewValue;
  22998. if (selectCtrl.hasOption(viewValue)) {
  22999. if (unknownOption.parent()) unknownOption.remove();
  23000. selectElement.val(viewValue);
  23001. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  23002. } else {
  23003. if (isUndefined(viewValue) && emptyOption) {
  23004. selectElement.val('');
  23005. } else {
  23006. selectCtrl.renderUnknownOption(viewValue);
  23007. }
  23008. }
  23009. };
  23010. selectElement.on('change', function() {
  23011. scope.$apply(function() {
  23012. if (unknownOption.parent()) unknownOption.remove();
  23013. ngModelCtrl.$setViewValue(selectElement.val());
  23014. });
  23015. });
  23016. }
  23017. function setupAsMultiple(scope, selectElement, ctrl) {
  23018. var lastView;
  23019. ctrl.$render = function() {
  23020. var items = new HashMap(ctrl.$viewValue);
  23021. forEach(selectElement.find('option'), function(option) {
  23022. option.selected = isDefined(items.get(option.value));
  23023. });
  23024. };
  23025. // we have to do it on each watch since ngModel watches reference, but
  23026. // we need to work of an array, so we need to see if anything was inserted/removed
  23027. scope.$watch(function selectMultipleWatch() {
  23028. if (!equals(lastView, ctrl.$viewValue)) {
  23029. lastView = shallowCopy(ctrl.$viewValue);
  23030. ctrl.$render();
  23031. }
  23032. });
  23033. selectElement.on('change', function() {
  23034. scope.$apply(function() {
  23035. var array = [];
  23036. forEach(selectElement.find('option'), function(option) {
  23037. if (option.selected) {
  23038. array.push(option.value);
  23039. }
  23040. });
  23041. ctrl.$setViewValue(array);
  23042. });
  23043. });
  23044. }
  23045. function setupAsOptions(scope, selectElement, ctrl) {
  23046. var match;
  23047. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  23048. throw ngOptionsMinErr('iexp',
  23049. "Expected expression in form of " +
  23050. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23051. " but got '{0}'. Element: {1}",
  23052. optionsExp, startingTag(selectElement));
  23053. }
  23054. var displayFn = $parse(match[2] || match[1]),
  23055. valueName = match[4] || match[6],
  23056. selectAs = / as /.test(match[0]) && match[1],
  23057. selectAsFn = selectAs ? $parse(selectAs) : null,
  23058. keyName = match[5],
  23059. groupByFn = $parse(match[3] || ''),
  23060. valueFn = $parse(match[2] ? match[1] : valueName),
  23061. valuesFn = $parse(match[7]),
  23062. track = match[8],
  23063. trackFn = track ? $parse(match[8]) : null,
  23064. trackKeysCache = {},
  23065. // This is an array of array of existing option groups in DOM.
  23066. // We try to reuse these if possible
  23067. // - optionGroupsCache[0] is the options with no option group
  23068. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  23069. optionGroupsCache = [[{element: selectElement, label:''}]],
  23070. //re-usable object to represent option's locals
  23071. locals = {};
  23072. if (nullOption) {
  23073. // compile the element since there might be bindings in it
  23074. $compile(nullOption)(scope);
  23075. // remove the class, which is added automatically because we recompile the element and it
  23076. // becomes the compilation root
  23077. nullOption.removeClass('ng-scope');
  23078. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23079. // remove the label from the element. wtf?
  23080. nullOption.remove();
  23081. }
  23082. // clear contents, we'll add what's needed based on the model
  23083. selectElement.empty();
  23084. selectElement.on('change', selectionChanged);
  23085. ctrl.$render = render;
  23086. scope.$watchCollection(valuesFn, scheduleRendering);
  23087. scope.$watchCollection(getLabels, scheduleRendering);
  23088. if (multiple) {
  23089. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  23090. }
  23091. // ------------------------------------------------------------------ //
  23092. function callExpression(exprFn, key, value) {
  23093. locals[valueName] = value;
  23094. if (keyName) locals[keyName] = key;
  23095. return exprFn(scope, locals);
  23096. }
  23097. function selectionChanged() {
  23098. scope.$apply(function() {
  23099. var collection = valuesFn(scope) || [];
  23100. var viewValue;
  23101. if (multiple) {
  23102. viewValue = [];
  23103. forEach(selectElement.val(), function(selectedKey) {
  23104. selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
  23105. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  23106. });
  23107. } else {
  23108. var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
  23109. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  23110. }
  23111. ctrl.$setViewValue(viewValue);
  23112. render();
  23113. });
  23114. }
  23115. function getViewValue(key, value) {
  23116. if (key === '?') {
  23117. return undefined;
  23118. } else if (key === '') {
  23119. return null;
  23120. } else {
  23121. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  23122. return callExpression(viewValueFn, key, value);
  23123. }
  23124. }
  23125. function getLabels() {
  23126. var values = valuesFn(scope);
  23127. var toDisplay;
  23128. if (values && isArray(values)) {
  23129. toDisplay = new Array(values.length);
  23130. for (var i = 0, ii = values.length; i < ii; i++) {
  23131. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23132. }
  23133. return toDisplay;
  23134. } else if (values) {
  23135. // TODO: Add a test for this case
  23136. toDisplay = {};
  23137. for (var prop in values) {
  23138. if (values.hasOwnProperty(prop)) {
  23139. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23140. }
  23141. }
  23142. }
  23143. return toDisplay;
  23144. }
  23145. function createIsSelectedFn(viewValue) {
  23146. var selectedSet;
  23147. if (multiple) {
  23148. if (trackFn && isArray(viewValue)) {
  23149. selectedSet = new HashMap([]);
  23150. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23151. // tracking by key
  23152. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23153. }
  23154. } else {
  23155. selectedSet = new HashMap(viewValue);
  23156. }
  23157. } else if (trackFn) {
  23158. viewValue = callExpression(trackFn, null, viewValue);
  23159. }
  23160. return function isSelected(key, value) {
  23161. var compareValueFn;
  23162. if (trackFn) {
  23163. compareValueFn = trackFn;
  23164. } else if (selectAsFn) {
  23165. compareValueFn = selectAsFn;
  23166. } else {
  23167. compareValueFn = valueFn;
  23168. }
  23169. if (multiple) {
  23170. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23171. } else {
  23172. return viewValue === callExpression(compareValueFn, key, value);
  23173. }
  23174. };
  23175. }
  23176. function scheduleRendering() {
  23177. if (!renderScheduled) {
  23178. scope.$$postDigest(render);
  23179. renderScheduled = true;
  23180. }
  23181. }
  23182. /**
  23183. * A new labelMap is created with each render.
  23184. * This function is called for each existing option with added=false,
  23185. * and each new option with added=true.
  23186. * - Labels that are passed to this method twice,
  23187. * (once with added=true and once with added=false) will end up with a value of 0, and
  23188. * will cause no change to happen to the corresponding option.
  23189. * - Labels that are passed to this method only once with added=false will end up with a
  23190. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23191. * - Labels that are passed to this method only once with added=true will end up with a
  23192. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23193. */
  23194. function updateLabelMap(labelMap, label, added) {
  23195. labelMap[label] = labelMap[label] || 0;
  23196. labelMap[label] += (added ? 1 : -1);
  23197. }
  23198. function render() {
  23199. renderScheduled = false;
  23200. // Temporary location for the option groups before we render them
  23201. var optionGroups = {'':[]},
  23202. optionGroupNames = [''],
  23203. optionGroupName,
  23204. optionGroup,
  23205. option,
  23206. existingParent, existingOptions, existingOption,
  23207. viewValue = ctrl.$viewValue,
  23208. values = valuesFn(scope) || [],
  23209. keys = keyName ? sortedKeys(values) : values,
  23210. key,
  23211. value,
  23212. groupLength, length,
  23213. groupIndex, index,
  23214. labelMap = {},
  23215. selected,
  23216. isSelected = createIsSelectedFn(viewValue),
  23217. anySelected = false,
  23218. lastElement,
  23219. element,
  23220. label,
  23221. optionId;
  23222. trackKeysCache = {};
  23223. // We now build up the list of options we need (we merge later)
  23224. for (index = 0; length = keys.length, index < length; index++) {
  23225. key = index;
  23226. if (keyName) {
  23227. key = keys[index];
  23228. if (key.charAt(0) === '$') continue;
  23229. }
  23230. value = values[key];
  23231. optionGroupName = callExpression(groupByFn, key, value) || '';
  23232. if (!(optionGroup = optionGroups[optionGroupName])) {
  23233. optionGroup = optionGroups[optionGroupName] = [];
  23234. optionGroupNames.push(optionGroupName);
  23235. }
  23236. selected = isSelected(key, value);
  23237. anySelected = anySelected || selected;
  23238. label = callExpression(displayFn, key, value); // what will be seen by the user
  23239. // doing displayFn(scope, locals) || '' overwrites zero values
  23240. label = isDefined(label) ? label : '';
  23241. optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
  23242. if (trackFn) {
  23243. trackKeysCache[optionId] = key;
  23244. }
  23245. optionGroup.push({
  23246. // either the index into array or key from object
  23247. id: optionId,
  23248. label: label,
  23249. selected: selected // determine if we should be selected
  23250. });
  23251. }
  23252. if (!multiple) {
  23253. if (nullOption || viewValue === null) {
  23254. // insert null option if we have a placeholder, or the model is null
  23255. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23256. } else if (!anySelected) {
  23257. // option could not be found, we have to insert the undefined item
  23258. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23259. }
  23260. }
  23261. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23262. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23263. groupIndex < groupLength;
  23264. groupIndex++) {
  23265. // current option group name or '' if no group
  23266. optionGroupName = optionGroupNames[groupIndex];
  23267. // list of options for that group. (first item has the parent)
  23268. optionGroup = optionGroups[optionGroupName];
  23269. if (optionGroupsCache.length <= groupIndex) {
  23270. // we need to grow the optionGroups
  23271. existingParent = {
  23272. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23273. label: optionGroup.label
  23274. };
  23275. existingOptions = [existingParent];
  23276. optionGroupsCache.push(existingOptions);
  23277. selectElement.append(existingParent.element);
  23278. } else {
  23279. existingOptions = optionGroupsCache[groupIndex];
  23280. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23281. // update the OPTGROUP label if not the same.
  23282. if (existingParent.label != optionGroupName) {
  23283. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23284. }
  23285. }
  23286. lastElement = null; // start at the beginning
  23287. for (index = 0, length = optionGroup.length; index < length; index++) {
  23288. option = optionGroup[index];
  23289. if ((existingOption = existingOptions[index+1])) {
  23290. // reuse elements
  23291. lastElement = existingOption.element;
  23292. if (existingOption.label !== option.label) {
  23293. updateLabelMap(labelMap, existingOption.label, false);
  23294. updateLabelMap(labelMap, option.label, true);
  23295. lastElement.text(existingOption.label = option.label);
  23296. }
  23297. if (existingOption.id !== option.id) {
  23298. lastElement.val(existingOption.id = option.id);
  23299. }
  23300. // lastElement.prop('selected') provided by jQuery has side-effects
  23301. if (lastElement[0].selected !== option.selected) {
  23302. lastElement.prop('selected', (existingOption.selected = option.selected));
  23303. if (msie) {
  23304. // See #7692
  23305. // The selected item wouldn't visually update on IE without this.
  23306. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23307. lastElement.prop('selected', existingOption.selected);
  23308. }
  23309. }
  23310. } else {
  23311. // grow elements
  23312. // if it's a null option
  23313. if (option.id === '' && nullOption) {
  23314. // put back the pre-compiled element
  23315. element = nullOption;
  23316. } else {
  23317. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23318. // in this version of jQuery on some browser the .text() returns a string
  23319. // rather then the element.
  23320. (element = optionTemplate.clone())
  23321. .val(option.id)
  23322. .prop('selected', option.selected)
  23323. .attr('selected', option.selected)
  23324. .text(option.label);
  23325. }
  23326. existingOptions.push(existingOption = {
  23327. element: element,
  23328. label: option.label,
  23329. id: option.id,
  23330. selected: option.selected
  23331. });
  23332. updateLabelMap(labelMap, option.label, true);
  23333. if (lastElement) {
  23334. lastElement.after(element);
  23335. } else {
  23336. existingParent.element.append(element);
  23337. }
  23338. lastElement = element;
  23339. }
  23340. }
  23341. // remove any excessive OPTIONs in a group
  23342. index++; // increment since the existingOptions[0] is parent element not OPTION
  23343. while (existingOptions.length > index) {
  23344. option = existingOptions.pop();
  23345. updateLabelMap(labelMap, option.label, false);
  23346. option.element.remove();
  23347. }
  23348. forEach(labelMap, function(count, label) {
  23349. if (count > 0) {
  23350. selectCtrl.addOption(label);
  23351. } else if (count < 0) {
  23352. selectCtrl.removeOption(label);
  23353. }
  23354. });
  23355. }
  23356. // remove any excessive OPTGROUPs from select
  23357. while (optionGroupsCache.length > groupIndex) {
  23358. optionGroupsCache.pop()[0].element.remove();
  23359. }
  23360. }
  23361. }
  23362. }
  23363. };
  23364. }];
  23365. var optionDirective = ['$interpolate', function($interpolate) {
  23366. var nullSelectCtrl = {
  23367. addOption: noop,
  23368. removeOption: noop
  23369. };
  23370. return {
  23371. restrict: 'E',
  23372. priority: 100,
  23373. compile: function(element, attr) {
  23374. if (isUndefined(attr.value)) {
  23375. var interpolateFn = $interpolate(element.text(), true);
  23376. if (!interpolateFn) {
  23377. attr.$set('value', element.text());
  23378. }
  23379. }
  23380. return function(scope, element, attr) {
  23381. var selectCtrlName = '$selectController',
  23382. parent = element.parent(),
  23383. selectCtrl = parent.data(selectCtrlName) ||
  23384. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23385. if (!selectCtrl || !selectCtrl.databound) {
  23386. selectCtrl = nullSelectCtrl;
  23387. }
  23388. if (interpolateFn) {
  23389. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23390. attr.$set('value', newVal);
  23391. if (oldVal !== newVal) {
  23392. selectCtrl.removeOption(oldVal);
  23393. }
  23394. selectCtrl.addOption(newVal, element);
  23395. });
  23396. } else {
  23397. selectCtrl.addOption(attr.value, element);
  23398. }
  23399. element.on('$destroy', function() {
  23400. selectCtrl.removeOption(attr.value);
  23401. });
  23402. };
  23403. }
  23404. };
  23405. }];
  23406. var styleDirective = valueFn({
  23407. restrict: 'E',
  23408. terminal: false
  23409. });
  23410. if (window.angular.bootstrap) {
  23411. //AngularJS is already loaded, so we can return here...
  23412. console.log('WARNING: Tried to load angular more than once.');
  23413. return;
  23414. }
  23415. //try to bind to jquery now so that one can write jqLite(document).ready()
  23416. //but we will rebind on bootstrap again.
  23417. bindJQuery();
  23418. publishExternalAPI(angular);
  23419. jqLite(document).ready(function() {
  23420. angularInit(document, bootstrap);
  23421. });
  23422. })(window, document);
  23423. !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>');