angular.js 773 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187
  1. /**
  2. * @license AngularJS v1.2.30
  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. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  33. */
  34. function minErr(module) {
  35. return function () {
  36. var code = arguments[0],
  37. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  38. template = arguments[1],
  39. templateArgs = arguments,
  40. stringify = function (obj) {
  41. if (typeof obj === 'function') {
  42. return obj.toString().replace(/ \{[\s\S]*$/, '');
  43. } else if (typeof obj === 'undefined') {
  44. return 'undefined';
  45. } else if (typeof obj !== 'string') {
  46. return JSON.stringify(obj);
  47. }
  48. return obj;
  49. },
  50. message, i;
  51. message = prefix + template.replace(/\{\d+\}/g, function (match) {
  52. var index = +match.slice(1, -1), arg;
  53. if (index + 2 < templateArgs.length) {
  54. arg = templateArgs[index + 2];
  55. if (typeof arg === 'function') {
  56. return arg.toString().replace(/ ?\{[\s\S]*$/, '');
  57. } else if (typeof arg === 'undefined') {
  58. return 'undefined';
  59. } else if (typeof arg !== 'string') {
  60. return toJson(arg);
  61. }
  62. return arg;
  63. }
  64. return match;
  65. });
  66. message = message + '\nhttp://errors.angularjs.org/1.2.30/' +
  67. (module ? module + '/' : '') + code;
  68. for (i = 2; i < arguments.length; i++) {
  69. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  70. encodeURIComponent(stringify(arguments[i]));
  71. }
  72. return new Error(message);
  73. };
  74. }
  75. /* We need to tell jshint what variables are being exported */
  76. /* global angular: true,
  77. msie: true,
  78. jqLite: true,
  79. jQuery: true,
  80. slice: true,
  81. push: true,
  82. toString: true,
  83. ngMinErr: true,
  84. angularModule: true,
  85. nodeName_: true,
  86. uid: true,
  87. VALIDITY_STATE_PROPERTY: true,
  88. lowercase: true,
  89. uppercase: true,
  90. manualLowercase: true,
  91. manualUppercase: true,
  92. nodeName_: true,
  93. isArrayLike: true,
  94. forEach: true,
  95. sortedKeys: true,
  96. forEachSorted: true,
  97. reverseParams: true,
  98. nextUid: true,
  99. setHashKey: true,
  100. extend: true,
  101. int: true,
  102. inherit: true,
  103. noop: true,
  104. identity: true,
  105. valueFn: true,
  106. isUndefined: true,
  107. isDefined: true,
  108. isObject: true,
  109. isString: true,
  110. isNumber: true,
  111. isDate: true,
  112. isArray: true,
  113. isFunction: true,
  114. isRegExp: true,
  115. isWindow: true,
  116. isScope: true,
  117. isFile: true,
  118. isBlob: true,
  119. isBoolean: true,
  120. isPromiseLike: true,
  121. trim: true,
  122. isElement: true,
  123. makeMap: true,
  124. map: true,
  125. size: true,
  126. includes: true,
  127. indexOf: true,
  128. arrayRemove: true,
  129. isLeafNode: true,
  130. copy: true,
  131. shallowCopy: true,
  132. equals: true,
  133. csp: true,
  134. concat: true,
  135. sliceArgs: true,
  136. bind: true,
  137. toJsonReplacer: true,
  138. toJson: true,
  139. fromJson: true,
  140. toBoolean: 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. snake_case: true,
  150. bindJQuery: true,
  151. assertArg: true,
  152. assertArgFn: true,
  153. assertNotHasOwnProperty: true,
  154. getter: true,
  155. getBlockElements: true,
  156. hasOwnProperty: true,
  157. */
  158. ////////////////////////////////////
  159. /**
  160. * @ngdoc module
  161. * @name ng
  162. * @module ng
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. // The name of a form control's ValidityState property.
  174. // This is used so that it's possible for internal tests to create mock ValidityStates.
  175. var VALIDITY_STATE_PROPERTY = 'validity';
  176. /**
  177. * @ngdoc function
  178. * @name angular.lowercase
  179. * @module ng
  180. * @kind function
  181. *
  182. * @description Converts the specified string to lowercase.
  183. * @param {string} string String to be converted to lowercase.
  184. * @returns {string} Lowercased string.
  185. */
  186. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  187. var hasOwnProperty = Object.prototype.hasOwnProperty;
  188. /**
  189. * @ngdoc function
  190. * @name angular.uppercase
  191. * @module ng
  192. * @kind function
  193. *
  194. * @description Converts the specified string to uppercase.
  195. * @param {string} string String to be converted to uppercase.
  196. * @returns {string} Uppercased string.
  197. */
  198. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  199. var manualLowercase = function(s) {
  200. /* jshint bitwise: false */
  201. return isString(s)
  202. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  203. : s;
  204. };
  205. var manualUppercase = function(s) {
  206. /* jshint bitwise: false */
  207. return isString(s)
  208. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  209. : s;
  210. };
  211. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  212. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  213. // with correct but slower alternatives.
  214. if ('i' !== 'I'.toLowerCase()) {
  215. lowercase = manualLowercase;
  216. uppercase = manualUppercase;
  217. }
  218. var
  219. msie, // holds major version number for IE, or NaN if UA is not IE.
  220. jqLite, // delay binding since jQuery could be loaded after us.
  221. jQuery, // delay binding
  222. slice = [].slice,
  223. push = [].push,
  224. toString = Object.prototype.toString,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. nodeName_,
  230. uid = ['0', '0', '0'];
  231. /**
  232. * IE 11 changed the format of the UserAgent string.
  233. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  234. */
  235. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  236. if (isNaN(msie)) {
  237. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  238. }
  239. /**
  240. * @private
  241. * @param {*} obj
  242. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  243. * String ...)
  244. */
  245. function isArrayLike(obj) {
  246. if (obj == null || isWindow(obj)) {
  247. return false;
  248. }
  249. var length = obj.length;
  250. if (obj.nodeType === 1 && length) {
  251. return true;
  252. }
  253. return isString(obj) || isArray(obj) || length === 0 ||
  254. typeof length === 'number' && length > 0 && (length - 1) in obj;
  255. }
  256. /**
  257. * @ngdoc function
  258. * @name angular.forEach
  259. * @module ng
  260. * @kind function
  261. *
  262. * @description
  263. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  264. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  265. * is the value of an object property or an array element and `key` is the object property key or
  266. * array element index. Specifying a `context` for the function is optional.
  267. *
  268. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  269. * using the `hasOwnProperty` method.
  270. *
  271. ```js
  272. var values = {name: 'misko', gender: 'male'};
  273. var log = [];
  274. angular.forEach(values, function(value, key) {
  275. this.push(key + ': ' + value);
  276. }, log);
  277. expect(log).toEqual(['name: misko', 'gender: male']);
  278. ```
  279. *
  280. * @param {Object|Array} obj Object to iterate over.
  281. * @param {Function} iterator Iterator function.
  282. * @param {Object=} context Object to become context (`this`) for the iterator function.
  283. * @returns {Object|Array} Reference to `obj`.
  284. */
  285. function forEach(obj, iterator, context) {
  286. var key;
  287. if (obj) {
  288. if (isFunction(obj)) {
  289. for (key in obj) {
  290. // Need to check if hasOwnProperty exists,
  291. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  292. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  293. iterator.call(context, obj[key], key);
  294. }
  295. }
  296. } else if (isArray(obj) || isArrayLike(obj)) {
  297. for (key = 0; key < obj.length; key++) {
  298. iterator.call(context, obj[key], key);
  299. }
  300. } else if (obj.forEach && obj.forEach !== forEach) {
  301. obj.forEach(iterator, context);
  302. } else {
  303. for (key in obj) {
  304. if (obj.hasOwnProperty(key)) {
  305. iterator.call(context, obj[key], key);
  306. }
  307. }
  308. }
  309. }
  310. return obj;
  311. }
  312. function sortedKeys(obj) {
  313. var keys = [];
  314. for (var key in obj) {
  315. if (obj.hasOwnProperty(key)) {
  316. keys.push(key);
  317. }
  318. }
  319. return keys.sort();
  320. }
  321. function forEachSorted(obj, iterator, context) {
  322. var keys = sortedKeys(obj);
  323. for ( var i = 0; i < keys.length; i++) {
  324. iterator.call(context, obj[keys[i]], keys[i]);
  325. }
  326. return keys;
  327. }
  328. /**
  329. * when using forEach the params are value, key, but it is often useful to have key, value.
  330. * @param {function(string, *)} iteratorFn
  331. * @returns {function(*, string)}
  332. */
  333. function reverseParams(iteratorFn) {
  334. return function(value, key) { iteratorFn(key, value); };
  335. }
  336. /**
  337. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  338. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  339. * the number string gets longer over time, and it can also overflow, where as the nextId
  340. * will grow much slower, it is a string, and it will never overflow.
  341. *
  342. * @returns {string} an unique alpha-numeric string
  343. */
  344. function nextUid() {
  345. var index = uid.length;
  346. var digit;
  347. while(index) {
  348. index--;
  349. digit = uid[index].charCodeAt(0);
  350. if (digit == 57 /*'9'*/) {
  351. uid[index] = 'A';
  352. return uid.join('');
  353. }
  354. if (digit == 90 /*'Z'*/) {
  355. uid[index] = '0';
  356. } else {
  357. uid[index] = String.fromCharCode(digit + 1);
  358. return uid.join('');
  359. }
  360. }
  361. uid.unshift('0');
  362. return uid.join('');
  363. }
  364. /**
  365. * Set or clear the hashkey for an object.
  366. * @param obj object
  367. * @param h the hashkey (!truthy to delete the hashkey)
  368. */
  369. function setHashKey(obj, h) {
  370. if (h) {
  371. obj.$$hashKey = h;
  372. }
  373. else {
  374. delete obj.$$hashKey;
  375. }
  376. }
  377. /**
  378. * @ngdoc function
  379. * @name angular.extend
  380. * @module ng
  381. * @kind function
  382. *
  383. * @description
  384. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  385. * to `dst`. You can specify multiple `src` objects.
  386. *
  387. * @param {Object} dst Destination object.
  388. * @param {...Object} src Source object(s).
  389. * @returns {Object} Reference to `dst`.
  390. */
  391. function extend(dst) {
  392. var h = dst.$$hashKey;
  393. forEach(arguments, function(obj) {
  394. if (obj !== dst) {
  395. forEach(obj, function(value, key) {
  396. dst[key] = value;
  397. });
  398. }
  399. });
  400. setHashKey(dst,h);
  401. return dst;
  402. }
  403. function int(str) {
  404. return parseInt(str, 10);
  405. }
  406. function inherit(parent, extra) {
  407. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  408. }
  409. /**
  410. * @ngdoc function
  411. * @name angular.noop
  412. * @module ng
  413. * @kind function
  414. *
  415. * @description
  416. * A function that performs no operations. This function can be useful when writing code in the
  417. * functional style.
  418. ```js
  419. function foo(callback) {
  420. var result = calculateResult();
  421. (callback || angular.noop)(result);
  422. }
  423. ```
  424. */
  425. function noop() {}
  426. noop.$inject = [];
  427. /**
  428. * @ngdoc function
  429. * @name angular.identity
  430. * @module ng
  431. * @kind function
  432. *
  433. * @description
  434. * A function that returns its first argument. This function is useful when writing code in the
  435. * functional style.
  436. *
  437. ```js
  438. function transformer(transformationFn, value) {
  439. return (transformationFn || angular.identity)(value);
  440. };
  441. ```
  442. * @param {*} value to be returned.
  443. * @returns {*} the value passed in.
  444. */
  445. function identity($) {return $;}
  446. identity.$inject = [];
  447. function valueFn(value) {return function() {return value;};}
  448. /**
  449. * @ngdoc function
  450. * @name angular.isUndefined
  451. * @module ng
  452. * @kind function
  453. *
  454. * @description
  455. * Determines if a reference is undefined.
  456. *
  457. * @param {*} value Reference to check.
  458. * @returns {boolean} True if `value` is undefined.
  459. */
  460. function isUndefined(value){return typeof value === 'undefined';}
  461. /**
  462. * @ngdoc function
  463. * @name angular.isDefined
  464. * @module ng
  465. * @kind function
  466. *
  467. * @description
  468. * Determines if a reference is defined.
  469. *
  470. * @param {*} value Reference to check.
  471. * @returns {boolean} True if `value` is defined.
  472. */
  473. function isDefined(value){return typeof value !== 'undefined';}
  474. /**
  475. * @ngdoc function
  476. * @name angular.isObject
  477. * @module ng
  478. * @kind function
  479. *
  480. * @description
  481. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  482. * considered to be objects. Note that JavaScript arrays are objects.
  483. *
  484. * @param {*} value Reference to check.
  485. * @returns {boolean} True if `value` is an `Object` but not `null`.
  486. */
  487. function isObject(value){return value != null && typeof value === 'object';}
  488. /**
  489. * @ngdoc function
  490. * @name angular.isString
  491. * @module ng
  492. * @kind function
  493. *
  494. * @description
  495. * Determines if a reference is a `String`.
  496. *
  497. * @param {*} value Reference to check.
  498. * @returns {boolean} True if `value` is a `String`.
  499. */
  500. function isString(value){return typeof value === 'string';}
  501. /**
  502. * @ngdoc function
  503. * @name angular.isNumber
  504. * @module ng
  505. * @kind function
  506. *
  507. * @description
  508. * Determines if a reference is a `Number`.
  509. *
  510. * @param {*} value Reference to check.
  511. * @returns {boolean} True if `value` is a `Number`.
  512. */
  513. function isNumber(value){return typeof value === 'number';}
  514. /**
  515. * @ngdoc function
  516. * @name angular.isDate
  517. * @module ng
  518. * @kind function
  519. *
  520. * @description
  521. * Determines if a value is a date.
  522. *
  523. * @param {*} value Reference to check.
  524. * @returns {boolean} True if `value` is a `Date`.
  525. */
  526. function isDate(value) {
  527. return toString.call(value) === '[object Date]';
  528. }
  529. /**
  530. * @ngdoc function
  531. * @name angular.isArray
  532. * @module ng
  533. * @kind function
  534. *
  535. * @description
  536. * Determines if a reference is an `Array`.
  537. *
  538. * @param {*} value Reference to check.
  539. * @returns {boolean} True if `value` is an `Array`.
  540. */
  541. var isArray = (function() {
  542. if (!isFunction(Array.isArray)) {
  543. return function(value) {
  544. return toString.call(value) === '[object Array]';
  545. };
  546. }
  547. return Array.isArray;
  548. })();
  549. /**
  550. * @ngdoc function
  551. * @name angular.isFunction
  552. * @module ng
  553. * @kind function
  554. *
  555. * @description
  556. * Determines if a reference is a `Function`.
  557. *
  558. * @param {*} value Reference to check.
  559. * @returns {boolean} True if `value` is a `Function`.
  560. */
  561. function isFunction(value){return typeof value === 'function';}
  562. /**
  563. * Determines if a value is a regular expression object.
  564. *
  565. * @private
  566. * @param {*} value Reference to check.
  567. * @returns {boolean} True if `value` is a `RegExp`.
  568. */
  569. function isRegExp(value) {
  570. return toString.call(value) === '[object RegExp]';
  571. }
  572. /**
  573. * Checks if `obj` is a window object.
  574. *
  575. * @private
  576. * @param {*} obj Object to check
  577. * @returns {boolean} True if `obj` is a window obj.
  578. */
  579. function isWindow(obj) {
  580. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  581. }
  582. function isScope(obj) {
  583. return obj && obj.$evalAsync && obj.$watch;
  584. }
  585. function isFile(obj) {
  586. return toString.call(obj) === '[object File]';
  587. }
  588. function isBlob(obj) {
  589. return toString.call(obj) === '[object Blob]';
  590. }
  591. function isBoolean(value) {
  592. return typeof value === 'boolean';
  593. }
  594. function isPromiseLike(obj) {
  595. return obj && isFunction(obj.then);
  596. }
  597. var trim = (function() {
  598. // native trim is way faster: http://jsperf.com/angular-trim-test
  599. // but IE doesn't have it... :-(
  600. // TODO: we should move this into IE/ES5 polyfill
  601. if (!String.prototype.trim) {
  602. return function(value) {
  603. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  604. };
  605. }
  606. return function(value) {
  607. return isString(value) ? value.trim() : value;
  608. };
  609. })();
  610. /**
  611. * @ngdoc function
  612. * @name angular.isElement
  613. * @module ng
  614. * @kind function
  615. *
  616. * @description
  617. * Determines if a reference is a DOM element (or wrapped jQuery element).
  618. *
  619. * @param {*} value Reference to check.
  620. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  621. */
  622. function isElement(node) {
  623. return !!(node &&
  624. (node.nodeName // we are a direct element
  625. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  626. }
  627. /**
  628. * @param str 'key1,key2,...'
  629. * @returns {object} in the form of {key1:true, key2:true, ...}
  630. */
  631. function makeMap(str) {
  632. var obj = {}, items = str.split(","), i;
  633. for ( i = 0; i < items.length; i++ )
  634. obj[ items[i] ] = true;
  635. return obj;
  636. }
  637. if (msie < 9) {
  638. nodeName_ = function(element) {
  639. element = element.nodeName ? element : element[0];
  640. return (element.scopeName && element.scopeName != 'HTML')
  641. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  642. };
  643. } else {
  644. nodeName_ = function(element) {
  645. return element.nodeName ? element.nodeName : element[0].nodeName;
  646. };
  647. }
  648. function map(obj, iterator, context) {
  649. var results = [];
  650. forEach(obj, function(value, index, list) {
  651. results.push(iterator.call(context, value, index, list));
  652. });
  653. return results;
  654. }
  655. /**
  656. * @description
  657. * Determines the number of elements in an array, the number of properties an object has, or
  658. * the length of a string.
  659. *
  660. * Note: This function is used to augment the Object type in Angular expressions. See
  661. * {@link angular.Object} for more information about Angular arrays.
  662. *
  663. * @param {Object|Array|string} obj Object, array, or string to inspect.
  664. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  665. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  666. */
  667. function size(obj, ownPropsOnly) {
  668. var count = 0, key;
  669. if (isArray(obj) || isString(obj)) {
  670. return obj.length;
  671. } else if (isObject(obj)) {
  672. for (key in obj)
  673. if (!ownPropsOnly || obj.hasOwnProperty(key))
  674. count++;
  675. }
  676. return count;
  677. }
  678. function includes(array, obj) {
  679. return indexOf(array, obj) != -1;
  680. }
  681. function indexOf(array, obj) {
  682. if (array.indexOf) return array.indexOf(obj);
  683. for (var i = 0; i < array.length; i++) {
  684. if (obj === array[i]) return i;
  685. }
  686. return -1;
  687. }
  688. function arrayRemove(array, value) {
  689. var index = indexOf(array, value);
  690. if (index >=0)
  691. array.splice(index, 1);
  692. return value;
  693. }
  694. function isLeafNode (node) {
  695. if (node) {
  696. switch (node.nodeName) {
  697. case "OPTION":
  698. case "PRE":
  699. case "TITLE":
  700. return true;
  701. }
  702. }
  703. return false;
  704. }
  705. /**
  706. * @ngdoc function
  707. * @name angular.copy
  708. * @module ng
  709. * @kind function
  710. *
  711. * @description
  712. * Creates a deep copy of `source`, which should be an object or an array.
  713. *
  714. * * If no destination is supplied, a copy of the object or array is created.
  715. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  716. * are deleted and then all elements/properties from the source are copied to it.
  717. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  718. * * If `source` is identical to 'destination' an exception will be thrown.
  719. *
  720. * @param {*} source The source that will be used to make a copy.
  721. * Can be any type, including primitives, `null`, and `undefined`.
  722. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  723. * provided, must be of the same type as `source`.
  724. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  725. *
  726. * @example
  727. <example module="copyExample">
  728. <file name="index.html">
  729. <div ng-controller="ExampleController">
  730. <form novalidate class="simple-form">
  731. Name: <input type="text" ng-model="user.name" /><br />
  732. E-mail: <input type="email" ng-model="user.email" /><br />
  733. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  734. <input type="radio" ng-model="user.gender" value="female" />female<br />
  735. <button ng-click="reset()">RESET</button>
  736. <button ng-click="update(user)">SAVE</button>
  737. </form>
  738. <pre>form = {{user | json}}</pre>
  739. <pre>master = {{master | json}}</pre>
  740. </div>
  741. <script>
  742. angular.module('copyExample', [])
  743. .controller('ExampleController', ['$scope', function($scope) {
  744. $scope.master= {};
  745. $scope.update = function(user) {
  746. // Example with 1 argument
  747. $scope.master= angular.copy(user);
  748. };
  749. $scope.reset = function() {
  750. // Example with 2 arguments
  751. angular.copy($scope.master, $scope.user);
  752. };
  753. $scope.reset();
  754. }]);
  755. </script>
  756. </file>
  757. </example>
  758. */
  759. function copy(source, destination, stackSource, stackDest) {
  760. if (isWindow(source) || isScope(source)) {
  761. throw ngMinErr('cpws',
  762. "Can't copy! Making copies of Window or Scope instances is not supported.");
  763. }
  764. if (!destination) {
  765. destination = source;
  766. if (source) {
  767. if (isArray(source)) {
  768. destination = copy(source, [], stackSource, stackDest);
  769. } else if (isDate(source)) {
  770. destination = new Date(source.getTime());
  771. } else if (isRegExp(source)) {
  772. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  773. destination.lastIndex = source.lastIndex;
  774. } else if (isObject(source)) {
  775. destination = copy(source, {}, stackSource, stackDest);
  776. }
  777. }
  778. } else {
  779. if (source === destination) throw ngMinErr('cpi',
  780. "Can't copy! Source and destination are identical.");
  781. stackSource = stackSource || [];
  782. stackDest = stackDest || [];
  783. if (isObject(source)) {
  784. var index = indexOf(stackSource, source);
  785. if (index !== -1) return stackDest[index];
  786. stackSource.push(source);
  787. stackDest.push(destination);
  788. }
  789. var result;
  790. if (isArray(source)) {
  791. destination.length = 0;
  792. for ( var i = 0; i < source.length; i++) {
  793. result = copy(source[i], null, stackSource, stackDest);
  794. if (isObject(source[i])) {
  795. stackSource.push(source[i]);
  796. stackDest.push(result);
  797. }
  798. destination.push(result);
  799. }
  800. } else {
  801. var h = destination.$$hashKey;
  802. if (isArray(destination)) {
  803. destination.length = 0;
  804. } else {
  805. forEach(destination, function(value, key) {
  806. delete destination[key];
  807. });
  808. }
  809. for ( var key in source) {
  810. result = copy(source[key], null, stackSource, stackDest);
  811. if (isObject(source[key])) {
  812. stackSource.push(source[key]);
  813. stackDest.push(result);
  814. }
  815. destination[key] = result;
  816. }
  817. setHashKey(destination,h);
  818. }
  819. }
  820. return destination;
  821. }
  822. /**
  823. * Creates a shallow copy of an object, an array or a primitive
  824. */
  825. function shallowCopy(src, dst) {
  826. if (isArray(src)) {
  827. dst = dst || [];
  828. for ( var i = 0; i < src.length; i++) {
  829. dst[i] = src[i];
  830. }
  831. } else if (isObject(src)) {
  832. dst = dst || {};
  833. for (var key in src) {
  834. if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  835. dst[key] = src[key];
  836. }
  837. }
  838. }
  839. return dst || src;
  840. }
  841. /**
  842. * @ngdoc function
  843. * @name angular.equals
  844. * @module ng
  845. * @kind function
  846. *
  847. * @description
  848. * Determines if two objects or two values are equivalent. Supports value types, regular
  849. * expressions, arrays and objects.
  850. *
  851. * Two objects or values are considered equivalent if at least one of the following is true:
  852. *
  853. * * Both objects or values pass `===` comparison.
  854. * * Both objects or values are of the same type and all of their properties are equal by
  855. * comparing them with `angular.equals`.
  856. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  857. * * Both values represent the same regular expression (In JavaScript,
  858. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  859. * representation matches).
  860. *
  861. * During a property comparison, properties of `function` type and properties with names
  862. * that begin with `$` are ignored.
  863. *
  864. * Scope and DOMWindow objects are being compared only by identify (`===`).
  865. *
  866. * @param {*} o1 Object or value to compare.
  867. * @param {*} o2 Object or value to compare.
  868. * @returns {boolean} True if arguments are equal.
  869. */
  870. function equals(o1, o2) {
  871. if (o1 === o2) return true;
  872. if (o1 === null || o2 === null) return false;
  873. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  874. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  875. if (t1 == t2) {
  876. if (t1 == 'object') {
  877. if (isArray(o1)) {
  878. if (!isArray(o2)) return false;
  879. if ((length = o1.length) == o2.length) {
  880. for(key=0; key<length; key++) {
  881. if (!equals(o1[key], o2[key])) return false;
  882. }
  883. return true;
  884. }
  885. } else if (isDate(o1)) {
  886. if (!isDate(o2)) return false;
  887. return (isNaN(o1.getTime()) && isNaN(o2.getTime())) || (o1.getTime() === o2.getTime());
  888. } else if (isRegExp(o1) && isRegExp(o2)) {
  889. return o1.toString() == o2.toString();
  890. } else {
  891. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  892. keySet = {};
  893. for(key in o1) {
  894. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  895. if (!equals(o1[key], o2[key])) return false;
  896. keySet[key] = true;
  897. }
  898. for(key in o2) {
  899. if (!keySet.hasOwnProperty(key) &&
  900. key.charAt(0) !== '$' &&
  901. o2[key] !== undefined &&
  902. !isFunction(o2[key])) return false;
  903. }
  904. return true;
  905. }
  906. }
  907. }
  908. return false;
  909. }
  910. var csp = function() {
  911. if (isDefined(csp.isActive_)) return csp.isActive_;
  912. var active = !!(document.querySelector('[ng-csp]') ||
  913. document.querySelector('[data-ng-csp]'));
  914. if (!active) {
  915. try {
  916. /* jshint -W031, -W054 */
  917. new Function('');
  918. /* jshint +W031, +W054 */
  919. } catch (e) {
  920. active = true;
  921. }
  922. }
  923. return (csp.isActive_ = active);
  924. };
  925. function concat(array1, array2, index) {
  926. return array1.concat(slice.call(array2, index));
  927. }
  928. function sliceArgs(args, startIndex) {
  929. return slice.call(args, startIndex || 0);
  930. }
  931. /* jshint -W101 */
  932. /**
  933. * @ngdoc function
  934. * @name angular.bind
  935. * @module ng
  936. * @kind function
  937. *
  938. * @description
  939. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  940. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  941. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  942. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  943. *
  944. * @param {Object} self Context which `fn` should be evaluated in.
  945. * @param {function()} fn Function to be bound.
  946. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  947. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  948. */
  949. /* jshint +W101 */
  950. function bind(self, fn) {
  951. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  952. if (isFunction(fn) && !(fn instanceof RegExp)) {
  953. return curryArgs.length
  954. ? function() {
  955. return arguments.length
  956. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  957. : fn.apply(self, curryArgs);
  958. }
  959. : function() {
  960. return arguments.length
  961. ? fn.apply(self, arguments)
  962. : fn.call(self);
  963. };
  964. } else {
  965. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  966. return fn;
  967. }
  968. }
  969. function toJsonReplacer(key, value) {
  970. var val = value;
  971. if (typeof key === 'string' && key.charAt(0) === '$') {
  972. val = undefined;
  973. } else if (isWindow(value)) {
  974. val = '$WINDOW';
  975. } else if (value && document === value) {
  976. val = '$DOCUMENT';
  977. } else if (isScope(value)) {
  978. val = '$SCOPE';
  979. }
  980. return val;
  981. }
  982. /**
  983. * @ngdoc function
  984. * @name angular.toJson
  985. * @module ng
  986. * @kind function
  987. *
  988. * @description
  989. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  990. * stripped since angular uses this notation internally.
  991. *
  992. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  993. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  994. * @returns {string|undefined} JSON-ified string representing `obj`.
  995. */
  996. function toJson(obj, pretty) {
  997. if (typeof obj === 'undefined') return undefined;
  998. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  999. }
  1000. /**
  1001. * @ngdoc function
  1002. * @name angular.fromJson
  1003. * @module ng
  1004. * @kind function
  1005. *
  1006. * @description
  1007. * Deserializes a JSON string.
  1008. *
  1009. * @param {string} json JSON string to deserialize.
  1010. * @returns {Object|Array|string|number} Deserialized thingy.
  1011. */
  1012. function fromJson(json) {
  1013. return isString(json)
  1014. ? JSON.parse(json)
  1015. : json;
  1016. }
  1017. function toBoolean(value) {
  1018. if (typeof value === 'function') {
  1019. value = true;
  1020. } else if (value && value.length !== 0) {
  1021. var v = lowercase("" + value);
  1022. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  1023. } else {
  1024. value = false;
  1025. }
  1026. return value;
  1027. }
  1028. /**
  1029. * @returns {string} Returns the string representation of the element.
  1030. */
  1031. function startingTag(element) {
  1032. element = jqLite(element).clone();
  1033. try {
  1034. // turns out IE does not let you set .html() on elements which
  1035. // are not allowed to have children. So we just ignore it.
  1036. element.empty();
  1037. } catch(e) {}
  1038. // As Per DOM Standards
  1039. var TEXT_NODE = 3;
  1040. var elemHtml = jqLite('<div>').append(element).html();
  1041. try {
  1042. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  1043. elemHtml.
  1044. match(/^(<[^>]+>)/)[1].
  1045. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1046. } catch(e) {
  1047. return lowercase(elemHtml);
  1048. }
  1049. }
  1050. /////////////////////////////////////////////////
  1051. /**
  1052. * Tries to decode the URI component without throwing an exception.
  1053. *
  1054. * @private
  1055. * @param str value potential URI component to check.
  1056. * @returns {boolean} True if `value` can be decoded
  1057. * with the decodeURIComponent function.
  1058. */
  1059. function tryDecodeURIComponent(value) {
  1060. try {
  1061. return decodeURIComponent(value);
  1062. } catch(e) {
  1063. // Ignore any invalid uri component
  1064. }
  1065. }
  1066. /**
  1067. * Parses an escaped url query string into key-value pairs.
  1068. * @returns {Object.<string,boolean|Array>}
  1069. */
  1070. function parseKeyValue(/**string*/keyValue) {
  1071. var obj = {}, key_value, key;
  1072. forEach((keyValue || "").split('&'), function(keyValue) {
  1073. if ( keyValue ) {
  1074. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1075. key = tryDecodeURIComponent(key_value[0]);
  1076. if ( isDefined(key) ) {
  1077. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1078. if (!hasOwnProperty.call(obj, key)) {
  1079. obj[key] = val;
  1080. } else if(isArray(obj[key])) {
  1081. obj[key].push(val);
  1082. } else {
  1083. obj[key] = [obj[key],val];
  1084. }
  1085. }
  1086. }
  1087. });
  1088. return obj;
  1089. }
  1090. function toKeyValue(obj) {
  1091. var parts = [];
  1092. forEach(obj, function(value, key) {
  1093. if (isArray(value)) {
  1094. forEach(value, function(arrayValue) {
  1095. parts.push(encodeUriQuery(key, true) +
  1096. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1097. });
  1098. } else {
  1099. parts.push(encodeUriQuery(key, true) +
  1100. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1101. }
  1102. });
  1103. return parts.length ? parts.join('&') : '';
  1104. }
  1105. /**
  1106. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1107. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1108. * segments:
  1109. * segment = *pchar
  1110. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1111. * pct-encoded = "%" HEXDIG HEXDIG
  1112. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1113. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1114. * / "*" / "+" / "," / ";" / "="
  1115. */
  1116. function encodeUriSegment(val) {
  1117. return encodeUriQuery(val, true).
  1118. replace(/%26/gi, '&').
  1119. replace(/%3D/gi, '=').
  1120. replace(/%2B/gi, '+');
  1121. }
  1122. /**
  1123. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1124. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1125. * encoded per http://tools.ietf.org/html/rfc3986:
  1126. * query = *( pchar / "/" / "?" )
  1127. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1128. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1129. * pct-encoded = "%" HEXDIG HEXDIG
  1130. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1131. * / "*" / "+" / "," / ";" / "="
  1132. */
  1133. function encodeUriQuery(val, pctEncodeSpaces) {
  1134. return encodeURIComponent(val).
  1135. replace(/%40/gi, '@').
  1136. replace(/%3A/gi, ':').
  1137. replace(/%24/g, '$').
  1138. replace(/%2C/gi, ',').
  1139. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1140. }
  1141. /**
  1142. * @ngdoc directive
  1143. * @name ngApp
  1144. * @module ng
  1145. *
  1146. * @element ANY
  1147. * @param {angular.Module} ngApp an optional application
  1148. * {@link angular.module module} name to load.
  1149. *
  1150. * @description
  1151. *
  1152. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1153. * designates the **root element** of the application and is typically placed near the root element
  1154. * of the page - e.g. on the `<body>` or `<html>` tags.
  1155. *
  1156. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1157. * found in the document will be used to define the root element to auto-bootstrap as an
  1158. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1159. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1160. *
  1161. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1162. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1163. * should contain the application code needed or have dependencies on other modules that will
  1164. * contain the code. See {@link angular.module} for more information.
  1165. *
  1166. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1167. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1168. * would not be resolved to `3`.
  1169. *
  1170. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1171. *
  1172. <example module="ngAppDemo">
  1173. <file name="index.html">
  1174. <div ng-controller="ngAppDemoController">
  1175. I can add: {{a}} + {{b}} = {{ a+b }}
  1176. </div>
  1177. </file>
  1178. <file name="script.js">
  1179. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1180. $scope.a = 1;
  1181. $scope.b = 2;
  1182. });
  1183. </file>
  1184. </example>
  1185. *
  1186. */
  1187. function angularInit(element, bootstrap) {
  1188. var elements = [element],
  1189. appElement,
  1190. module,
  1191. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1192. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1193. function append(element) {
  1194. element && elements.push(element);
  1195. }
  1196. forEach(names, function(name) {
  1197. names[name] = true;
  1198. append(document.getElementById(name));
  1199. name = name.replace(':', '\\:');
  1200. if (element.querySelectorAll) {
  1201. forEach(element.querySelectorAll('.' + name), append);
  1202. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1203. forEach(element.querySelectorAll('[' + name + ']'), append);
  1204. }
  1205. });
  1206. forEach(elements, function(element) {
  1207. if (!appElement) {
  1208. var className = ' ' + element.className + ' ';
  1209. var match = NG_APP_CLASS_REGEXP.exec(className);
  1210. if (match) {
  1211. appElement = element;
  1212. module = (match[2] || '').replace(/\s+/g, ',');
  1213. } else {
  1214. forEach(element.attributes, function(attr) {
  1215. if (!appElement && names[attr.name]) {
  1216. appElement = element;
  1217. module = attr.value;
  1218. }
  1219. });
  1220. }
  1221. }
  1222. });
  1223. if (appElement) {
  1224. bootstrap(appElement, module ? [module] : []);
  1225. }
  1226. }
  1227. /**
  1228. * @ngdoc function
  1229. * @name angular.bootstrap
  1230. * @module ng
  1231. * @description
  1232. * Use this function to manually start up angular application.
  1233. *
  1234. * See: {@link guide/bootstrap Bootstrap}
  1235. *
  1236. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1237. * They must use {@link ng.directive:ngApp ngApp}.
  1238. *
  1239. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1240. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1241. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1242. * multiple instances of Angular try to work on the DOM.
  1243. *
  1244. * <example name="multi-bootstrap" module="multi-bootstrap">
  1245. * <file name="index.html">
  1246. * <script src="../../../angular.js"></script>
  1247. * <div ng-controller="BrokenTable">
  1248. * <table>
  1249. * <tr>
  1250. * <th ng-repeat="heading in headings">{{heading}}</th>
  1251. * </tr>
  1252. * <tr ng-repeat="filling in fillings">
  1253. * <td ng-repeat="fill in filling">{{fill}}</td>
  1254. * </tr>
  1255. * </table>
  1256. * </div>
  1257. * </file>
  1258. * <file name="controller.js">
  1259. * var app = angular.module('multi-bootstrap', [])
  1260. *
  1261. * .controller('BrokenTable', function($scope) {
  1262. * $scope.headings = ['One', 'Two', 'Three'];
  1263. * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
  1264. * });
  1265. * </file>
  1266. * <file name="protractor.js" type="protractor">
  1267. * it('should only insert one table cell for each item in $scope.fillings', function() {
  1268. * expect(element.all(by.css('td')).count())
  1269. * .toBe(9);
  1270. * });
  1271. * </file>
  1272. * </example>
  1273. *
  1274. * @param {DOMElement} element DOM element which is the root of angular application.
  1275. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1276. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1277. * function that will be invoked by the injector as a run block.
  1278. * See: {@link angular.module modules}
  1279. * @returns {auto.$injector} Returns the newly created injector for this app.
  1280. */
  1281. function bootstrap(element, modules) {
  1282. var doBootstrap = function() {
  1283. element = jqLite(element);
  1284. if (element.injector()) {
  1285. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1286. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1287. throw ngMinErr(
  1288. 'btstrpd',
  1289. "App Already Bootstrapped with this Element '{0}'",
  1290. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1291. }
  1292. modules = modules || [];
  1293. modules.unshift(['$provide', function($provide) {
  1294. $provide.value('$rootElement', element);
  1295. }]);
  1296. modules.unshift('ng');
  1297. var injector = createInjector(modules);
  1298. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1299. function(scope, element, compile, injector, animate) {
  1300. scope.$apply(function() {
  1301. element.data('$injector', injector);
  1302. compile(element)(scope);
  1303. });
  1304. }]
  1305. );
  1306. return injector;
  1307. };
  1308. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1309. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1310. return doBootstrap();
  1311. }
  1312. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1313. angular.resumeBootstrap = function(extraModules) {
  1314. forEach(extraModules, function(module) {
  1315. modules.push(module);
  1316. });
  1317. doBootstrap();
  1318. };
  1319. }
  1320. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1321. function snake_case(name, separator) {
  1322. separator = separator || '_';
  1323. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1324. return (pos ? separator : '') + letter.toLowerCase();
  1325. });
  1326. }
  1327. function bindJQuery() {
  1328. // bind to jQuery if present;
  1329. jQuery = window.jQuery;
  1330. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1331. // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support.
  1332. if (jQuery && jQuery.fn.on) {
  1333. jqLite = jQuery;
  1334. extend(jQuery.fn, {
  1335. scope: JQLitePrototype.scope,
  1336. isolateScope: JQLitePrototype.isolateScope,
  1337. controller: JQLitePrototype.controller,
  1338. injector: JQLitePrototype.injector,
  1339. inheritedData: JQLitePrototype.inheritedData
  1340. });
  1341. // Method signature:
  1342. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1343. jqLitePatchJQueryRemove('remove', true, true, false);
  1344. jqLitePatchJQueryRemove('empty', false, false, false);
  1345. jqLitePatchJQueryRemove('html', false, false, true);
  1346. } else {
  1347. jqLite = JQLite;
  1348. }
  1349. angular.element = jqLite;
  1350. }
  1351. /**
  1352. * throw error if the argument is falsy.
  1353. */
  1354. function assertArg(arg, name, reason) {
  1355. if (!arg) {
  1356. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1357. }
  1358. return arg;
  1359. }
  1360. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1361. if (acceptArrayAnnotation && isArray(arg)) {
  1362. arg = arg[arg.length - 1];
  1363. }
  1364. assertArg(isFunction(arg), name, 'not a function, got ' +
  1365. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1366. return arg;
  1367. }
  1368. /**
  1369. * throw error if the name given is hasOwnProperty
  1370. * @param {String} name the name to test
  1371. * @param {String} context the context in which the name is used, such as module or directive
  1372. */
  1373. function assertNotHasOwnProperty(name, context) {
  1374. if (name === 'hasOwnProperty') {
  1375. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1376. }
  1377. }
  1378. /**
  1379. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1380. * @param {Object} obj starting object
  1381. * @param {String} path path to traverse
  1382. * @param {boolean} [bindFnToScope=true]
  1383. * @returns {Object} value as accessible by path
  1384. */
  1385. //TODO(misko): this function needs to be removed
  1386. function getter(obj, path, bindFnToScope) {
  1387. if (!path) return obj;
  1388. var keys = path.split('.');
  1389. var key;
  1390. var lastInstance = obj;
  1391. var len = keys.length;
  1392. for (var i = 0; i < len; i++) {
  1393. key = keys[i];
  1394. if (obj) {
  1395. obj = (lastInstance = obj)[key];
  1396. }
  1397. }
  1398. if (!bindFnToScope && isFunction(obj)) {
  1399. return bind(lastInstance, obj);
  1400. }
  1401. return obj;
  1402. }
  1403. /**
  1404. * Return the DOM siblings between the first and last node in the given array.
  1405. * @param {Array} array like object
  1406. * @returns {DOMElement} object containing the elements
  1407. */
  1408. function getBlockElements(nodes) {
  1409. var startNode = nodes[0],
  1410. endNode = nodes[nodes.length - 1];
  1411. if (startNode === endNode) {
  1412. return jqLite(startNode);
  1413. }
  1414. var element = startNode;
  1415. var elements = [element];
  1416. do {
  1417. element = element.nextSibling;
  1418. if (!element) break;
  1419. elements.push(element);
  1420. } while (element !== endNode);
  1421. return jqLite(elements);
  1422. }
  1423. /**
  1424. * @ngdoc type
  1425. * @name angular.Module
  1426. * @module ng
  1427. * @description
  1428. *
  1429. * Interface for configuring angular {@link angular.module modules}.
  1430. */
  1431. function setupModuleLoader(window) {
  1432. var $injectorMinErr = minErr('$injector');
  1433. var ngMinErr = minErr('ng');
  1434. function ensure(obj, name, factory) {
  1435. return obj[name] || (obj[name] = factory());
  1436. }
  1437. var angular = ensure(window, 'angular', Object);
  1438. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1439. angular.$$minErr = angular.$$minErr || minErr;
  1440. return ensure(angular, 'module', function() {
  1441. /** @type {Object.<string, angular.Module>} */
  1442. var modules = {};
  1443. /**
  1444. * @ngdoc function
  1445. * @name angular.module
  1446. * @module ng
  1447. * @description
  1448. *
  1449. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1450. * modules.
  1451. * All modules (angular core or 3rd party) that should be available to an application must be
  1452. * registered using this mechanism.
  1453. *
  1454. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1455. * existing module (the name passed as the first argument to `module`) is retrieved.
  1456. *
  1457. *
  1458. * # Module
  1459. *
  1460. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1461. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1462. *
  1463. * ```js
  1464. * // Create a new module
  1465. * var myModule = angular.module('myModule', []);
  1466. *
  1467. * // register a new service
  1468. * myModule.value('appName', 'MyCoolApp');
  1469. *
  1470. * // configure existing services inside initialization blocks.
  1471. * myModule.config(['$locationProvider', function($locationProvider) {
  1472. * // Configure existing providers
  1473. * $locationProvider.hashPrefix('!');
  1474. * }]);
  1475. * ```
  1476. *
  1477. * Then you can create an injector and load your modules like this:
  1478. *
  1479. * ```js
  1480. * var injector = angular.injector(['ng', 'myModule'])
  1481. * ```
  1482. *
  1483. * However it's more likely that you'll just use
  1484. * {@link ng.directive:ngApp ngApp} or
  1485. * {@link angular.bootstrap} to simplify this process for you.
  1486. *
  1487. * @param {!string} name The name of the module to create or retrieve.
  1488. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1489. * unspecified then the module is being retrieved for further configuration.
  1490. * @param {Function=} configFn Optional configuration function for the module. Same as
  1491. * {@link angular.Module#config Module#config()}.
  1492. * @returns {module} new module with the {@link angular.Module} api.
  1493. */
  1494. return function module(name, requires, configFn) {
  1495. var assertNotHasOwnProperty = function(name, context) {
  1496. if (name === 'hasOwnProperty') {
  1497. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1498. }
  1499. };
  1500. assertNotHasOwnProperty(name, 'module');
  1501. if (requires && modules.hasOwnProperty(name)) {
  1502. modules[name] = null;
  1503. }
  1504. return ensure(modules, name, function() {
  1505. if (!requires) {
  1506. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1507. "the module name or forgot to load it. If registering a module ensure that you " +
  1508. "specify the dependencies as the second argument.", name);
  1509. }
  1510. /** @type {!Array.<Array.<*>>} */
  1511. var invokeQueue = [];
  1512. /** @type {!Array.<Function>} */
  1513. var runBlocks = [];
  1514. var config = invokeLater('$injector', 'invoke');
  1515. /** @type {angular.Module} */
  1516. var moduleInstance = {
  1517. // Private state
  1518. _invokeQueue: invokeQueue,
  1519. _runBlocks: runBlocks,
  1520. /**
  1521. * @ngdoc property
  1522. * @name angular.Module#requires
  1523. * @module ng
  1524. *
  1525. * @description
  1526. * Holds the list of modules which the injector will load before the current module is
  1527. * loaded.
  1528. */
  1529. requires: requires,
  1530. /**
  1531. * @ngdoc property
  1532. * @name angular.Module#name
  1533. * @module ng
  1534. *
  1535. * @description
  1536. * Name of the module.
  1537. */
  1538. name: name,
  1539. /**
  1540. * @ngdoc method
  1541. * @name angular.Module#provider
  1542. * @module ng
  1543. * @param {string} name service name
  1544. * @param {Function} providerType Construction function for creating new instance of the
  1545. * service.
  1546. * @description
  1547. * See {@link auto.$provide#provider $provide.provider()}.
  1548. */
  1549. provider: invokeLater('$provide', 'provider'),
  1550. /**
  1551. * @ngdoc method
  1552. * @name angular.Module#factory
  1553. * @module ng
  1554. * @param {string} name service name
  1555. * @param {Function} providerFunction Function for creating new instance of the service.
  1556. * @description
  1557. * See {@link auto.$provide#factory $provide.factory()}.
  1558. */
  1559. factory: invokeLater('$provide', 'factory'),
  1560. /**
  1561. * @ngdoc method
  1562. * @name angular.Module#service
  1563. * @module ng
  1564. * @param {string} name service name
  1565. * @param {Function} constructor A constructor function that will be instantiated.
  1566. * @description
  1567. * See {@link auto.$provide#service $provide.service()}.
  1568. */
  1569. service: invokeLater('$provide', 'service'),
  1570. /**
  1571. * @ngdoc method
  1572. * @name angular.Module#value
  1573. * @module ng
  1574. * @param {string} name service name
  1575. * @param {*} object Service instance object.
  1576. * @description
  1577. * See {@link auto.$provide#value $provide.value()}.
  1578. */
  1579. value: invokeLater('$provide', 'value'),
  1580. /**
  1581. * @ngdoc method
  1582. * @name angular.Module#constant
  1583. * @module ng
  1584. * @param {string} name constant name
  1585. * @param {*} object Constant value.
  1586. * @description
  1587. * Because the constant are fixed, they get applied before other provide methods.
  1588. * See {@link auto.$provide#constant $provide.constant()}.
  1589. */
  1590. constant: invokeLater('$provide', 'constant', 'unshift'),
  1591. /**
  1592. * @ngdoc method
  1593. * @name angular.Module#animation
  1594. * @module ng
  1595. * @param {string} name animation name
  1596. * @param {Function} animationFactory Factory function for creating new instance of an
  1597. * animation.
  1598. * @description
  1599. *
  1600. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1601. *
  1602. *
  1603. * Defines an animation hook that can be later used with
  1604. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1605. *
  1606. * ```js
  1607. * module.animation('.animation-name', function($inject1, $inject2) {
  1608. * return {
  1609. * eventName : function(element, done) {
  1610. * //code to run the animation
  1611. * //once complete, then run done()
  1612. * return function cancellationFunction(element) {
  1613. * //code to cancel the animation
  1614. * }
  1615. * }
  1616. * }
  1617. * })
  1618. * ```
  1619. *
  1620. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1621. * {@link ngAnimate ngAnimate module} for more information.
  1622. */
  1623. animation: invokeLater('$animateProvider', 'register'),
  1624. /**
  1625. * @ngdoc method
  1626. * @name angular.Module#filter
  1627. * @module ng
  1628. * @param {string} name Filter name.
  1629. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1630. * @description
  1631. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1632. */
  1633. filter: invokeLater('$filterProvider', 'register'),
  1634. /**
  1635. * @ngdoc method
  1636. * @name angular.Module#controller
  1637. * @module ng
  1638. * @param {string|Object} name Controller name, or an object map of controllers where the
  1639. * keys are the names and the values are the constructors.
  1640. * @param {Function} constructor Controller constructor function.
  1641. * @description
  1642. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1643. */
  1644. controller: invokeLater('$controllerProvider', 'register'),
  1645. /**
  1646. * @ngdoc method
  1647. * @name angular.Module#directive
  1648. * @module ng
  1649. * @param {string|Object} name Directive name, or an object map of directives where the
  1650. * keys are the names and the values are the factories.
  1651. * @param {Function} directiveFactory Factory function for creating new instance of
  1652. * directives.
  1653. * @description
  1654. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1655. */
  1656. directive: invokeLater('$compileProvider', 'directive'),
  1657. /**
  1658. * @ngdoc method
  1659. * @name angular.Module#config
  1660. * @module ng
  1661. * @param {Function} configFn Execute this function on module load. Useful for service
  1662. * configuration.
  1663. * @description
  1664. * Use this method to register work which needs to be performed on module loading.
  1665. * For more about how to configure services, see
  1666. * {@link providers#providers_provider-recipe Provider Recipe}.
  1667. */
  1668. config: config,
  1669. /**
  1670. * @ngdoc method
  1671. * @name angular.Module#run
  1672. * @module ng
  1673. * @param {Function} initializationFn Execute this function after injector creation.
  1674. * Useful for application initialization.
  1675. * @description
  1676. * Use this method to register work which should be performed when the injector is done
  1677. * loading all modules.
  1678. */
  1679. run: function(block) {
  1680. runBlocks.push(block);
  1681. return this;
  1682. }
  1683. };
  1684. if (configFn) {
  1685. config(configFn);
  1686. }
  1687. return moduleInstance;
  1688. /**
  1689. * @param {string} provider
  1690. * @param {string} method
  1691. * @param {String=} insertMethod
  1692. * @returns {angular.Module}
  1693. */
  1694. function invokeLater(provider, method, insertMethod) {
  1695. return function() {
  1696. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1697. return moduleInstance;
  1698. };
  1699. }
  1700. });
  1701. };
  1702. });
  1703. }
  1704. /* global angularModule: true,
  1705. version: true,
  1706. $LocaleProvider,
  1707. $CompileProvider,
  1708. htmlAnchorDirective,
  1709. inputDirective,
  1710. inputDirective,
  1711. formDirective,
  1712. scriptDirective,
  1713. selectDirective,
  1714. styleDirective,
  1715. optionDirective,
  1716. ngBindDirective,
  1717. ngBindHtmlDirective,
  1718. ngBindTemplateDirective,
  1719. ngClassDirective,
  1720. ngClassEvenDirective,
  1721. ngClassOddDirective,
  1722. ngCspDirective,
  1723. ngCloakDirective,
  1724. ngControllerDirective,
  1725. ngFormDirective,
  1726. ngHideDirective,
  1727. ngIfDirective,
  1728. ngIncludeDirective,
  1729. ngIncludeFillContentDirective,
  1730. ngInitDirective,
  1731. ngNonBindableDirective,
  1732. ngPluralizeDirective,
  1733. ngRepeatDirective,
  1734. ngShowDirective,
  1735. ngStyleDirective,
  1736. ngSwitchDirective,
  1737. ngSwitchWhenDirective,
  1738. ngSwitchDefaultDirective,
  1739. ngOptionsDirective,
  1740. ngTranscludeDirective,
  1741. ngModelDirective,
  1742. ngListDirective,
  1743. ngChangeDirective,
  1744. requiredDirective,
  1745. requiredDirective,
  1746. ngValueDirective,
  1747. ngAttributeAliasDirectives,
  1748. ngEventDirectives,
  1749. $AnchorScrollProvider,
  1750. $AnimateProvider,
  1751. $BrowserProvider,
  1752. $CacheFactoryProvider,
  1753. $ControllerProvider,
  1754. $DocumentProvider,
  1755. $ExceptionHandlerProvider,
  1756. $FilterProvider,
  1757. $InterpolateProvider,
  1758. $IntervalProvider,
  1759. $HttpProvider,
  1760. $HttpBackendProvider,
  1761. $LocationProvider,
  1762. $LogProvider,
  1763. $ParseProvider,
  1764. $RootScopeProvider,
  1765. $QProvider,
  1766. $$SanitizeUriProvider,
  1767. $SceProvider,
  1768. $SceDelegateProvider,
  1769. $SnifferProvider,
  1770. $TemplateCacheProvider,
  1771. $TimeoutProvider,
  1772. $$RAFProvider,
  1773. $$AsyncCallbackProvider,
  1774. $WindowProvider
  1775. */
  1776. /**
  1777. * @ngdoc object
  1778. * @name angular.version
  1779. * @module ng
  1780. * @description
  1781. * An object that contains information about the current AngularJS version. This object has the
  1782. * following properties:
  1783. *
  1784. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1785. * - `major` – `{number}` – Major version number, such as "0".
  1786. * - `minor` – `{number}` – Minor version number, such as "9".
  1787. * - `dot` – `{number}` – Dot version number, such as "18".
  1788. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1789. */
  1790. var version = {
  1791. full: '1.2.30', // all of these placeholder strings will be replaced by grunt's
  1792. major: 1, // package task
  1793. minor: 2,
  1794. dot: 30,
  1795. codeName: 'patronal-resurrection'
  1796. };
  1797. function publishExternalAPI(angular){
  1798. extend(angular, {
  1799. 'bootstrap': bootstrap,
  1800. 'copy': copy,
  1801. 'extend': extend,
  1802. 'equals': equals,
  1803. 'element': jqLite,
  1804. 'forEach': forEach,
  1805. 'injector': createInjector,
  1806. 'noop': noop,
  1807. 'bind': bind,
  1808. 'toJson': toJson,
  1809. 'fromJson': fromJson,
  1810. 'identity': identity,
  1811. 'isUndefined': isUndefined,
  1812. 'isDefined': isDefined,
  1813. 'isString': isString,
  1814. 'isFunction': isFunction,
  1815. 'isObject': isObject,
  1816. 'isNumber': isNumber,
  1817. 'isElement': isElement,
  1818. 'isArray': isArray,
  1819. 'version': version,
  1820. 'isDate': isDate,
  1821. 'lowercase': lowercase,
  1822. 'uppercase': uppercase,
  1823. 'callbacks': {counter: 0},
  1824. '$$minErr': minErr,
  1825. '$$csp': csp
  1826. });
  1827. angularModule = setupModuleLoader(window);
  1828. try {
  1829. angularModule('ngLocale');
  1830. } catch (e) {
  1831. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1832. }
  1833. angularModule('ng', ['ngLocale'], ['$provide',
  1834. function ngModule($provide) {
  1835. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1836. $provide.provider({
  1837. $$sanitizeUri: $$SanitizeUriProvider
  1838. });
  1839. $provide.provider('$compile', $CompileProvider).
  1840. directive({
  1841. a: htmlAnchorDirective,
  1842. input: inputDirective,
  1843. textarea: inputDirective,
  1844. form: formDirective,
  1845. script: scriptDirective,
  1846. select: selectDirective,
  1847. style: styleDirective,
  1848. option: optionDirective,
  1849. ngBind: ngBindDirective,
  1850. ngBindHtml: ngBindHtmlDirective,
  1851. ngBindTemplate: ngBindTemplateDirective,
  1852. ngClass: ngClassDirective,
  1853. ngClassEven: ngClassEvenDirective,
  1854. ngClassOdd: ngClassOddDirective,
  1855. ngCloak: ngCloakDirective,
  1856. ngController: ngControllerDirective,
  1857. ngForm: ngFormDirective,
  1858. ngHide: ngHideDirective,
  1859. ngIf: ngIfDirective,
  1860. ngInclude: ngIncludeDirective,
  1861. ngInit: ngInitDirective,
  1862. ngNonBindable: ngNonBindableDirective,
  1863. ngPluralize: ngPluralizeDirective,
  1864. ngRepeat: ngRepeatDirective,
  1865. ngShow: ngShowDirective,
  1866. ngStyle: ngStyleDirective,
  1867. ngSwitch: ngSwitchDirective,
  1868. ngSwitchWhen: ngSwitchWhenDirective,
  1869. ngSwitchDefault: ngSwitchDefaultDirective,
  1870. ngOptions: ngOptionsDirective,
  1871. ngTransclude: ngTranscludeDirective,
  1872. ngModel: ngModelDirective,
  1873. ngList: ngListDirective,
  1874. ngChange: ngChangeDirective,
  1875. required: requiredDirective,
  1876. ngRequired: requiredDirective,
  1877. ngValue: ngValueDirective
  1878. }).
  1879. directive({
  1880. ngInclude: ngIncludeFillContentDirective
  1881. }).
  1882. directive(ngAttributeAliasDirectives).
  1883. directive(ngEventDirectives);
  1884. $provide.provider({
  1885. $anchorScroll: $AnchorScrollProvider,
  1886. $animate: $AnimateProvider,
  1887. $browser: $BrowserProvider,
  1888. $cacheFactory: $CacheFactoryProvider,
  1889. $controller: $ControllerProvider,
  1890. $document: $DocumentProvider,
  1891. $exceptionHandler: $ExceptionHandlerProvider,
  1892. $filter: $FilterProvider,
  1893. $interpolate: $InterpolateProvider,
  1894. $interval: $IntervalProvider,
  1895. $http: $HttpProvider,
  1896. $httpBackend: $HttpBackendProvider,
  1897. $location: $LocationProvider,
  1898. $log: $LogProvider,
  1899. $parse: $ParseProvider,
  1900. $rootScope: $RootScopeProvider,
  1901. $q: $QProvider,
  1902. $sce: $SceProvider,
  1903. $sceDelegate: $SceDelegateProvider,
  1904. $sniffer: $SnifferProvider,
  1905. $templateCache: $TemplateCacheProvider,
  1906. $timeout: $TimeoutProvider,
  1907. $window: $WindowProvider,
  1908. $$rAF: $$RAFProvider,
  1909. $$asyncCallback : $$AsyncCallbackProvider
  1910. });
  1911. }
  1912. ]);
  1913. }
  1914. /* global JQLitePrototype: true,
  1915. addEventListenerFn: true,
  1916. removeEventListenerFn: true,
  1917. BOOLEAN_ATTR: true
  1918. */
  1919. //////////////////////////////////
  1920. //JQLite
  1921. //////////////////////////////////
  1922. /**
  1923. * @ngdoc function
  1924. * @name angular.element
  1925. * @module ng
  1926. * @kind function
  1927. *
  1928. * @description
  1929. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1930. *
  1931. * If jQuery is available, `angular.element` is an alias for the
  1932. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1933. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1934. *
  1935. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1936. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1937. * commonly needed functionality with the goal of having a very small footprint.</div>
  1938. *
  1939. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1940. *
  1941. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1942. * jqLite; they are never raw DOM references.</div>
  1943. *
  1944. * ## Angular's jqLite
  1945. * jqLite provides only the following jQuery methods:
  1946. *
  1947. * - [`addClass()`](http://api.jquery.com/addClass/)
  1948. * - [`after()`](http://api.jquery.com/after/)
  1949. * - [`append()`](http://api.jquery.com/append/)
  1950. * - [`attr()`](http://api.jquery.com/attr/)
  1951. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  1952. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1953. * - [`clone()`](http://api.jquery.com/clone/)
  1954. * - [`contents()`](http://api.jquery.com/contents/)
  1955. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()`
  1956. * - [`data()`](http://api.jquery.com/data/)
  1957. * - [`empty()`](http://api.jquery.com/empty/)
  1958. * - [`eq()`](http://api.jquery.com/eq/)
  1959. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1960. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1961. * - [`html()`](http://api.jquery.com/html/)
  1962. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1963. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1964. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1965. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1966. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1967. * - [`prepend()`](http://api.jquery.com/prepend/)
  1968. * - [`prop()`](http://api.jquery.com/prop/)
  1969. * - [`ready()`](http://api.jquery.com/ready/)
  1970. * - [`remove()`](http://api.jquery.com/remove/)
  1971. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1972. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1973. * - [`removeData()`](http://api.jquery.com/removeData/)
  1974. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1975. * - [`text()`](http://api.jquery.com/text/)
  1976. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1977. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1978. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  1979. * - [`val()`](http://api.jquery.com/val/)
  1980. * - [`wrap()`](http://api.jquery.com/wrap/)
  1981. *
  1982. * ## jQuery/jqLite Extras
  1983. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1984. *
  1985. * ### Events
  1986. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1987. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1988. * element before it is removed.
  1989. *
  1990. * ### Methods
  1991. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1992. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1993. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1994. * `'ngModel'`).
  1995. * - `injector()` - retrieves the injector of the current element or its parent.
  1996. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  1997. * element or its parent.
  1998. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  1999. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2000. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2001. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2002. * parent element is reached.
  2003. *
  2004. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2005. * @returns {Object} jQuery object.
  2006. */
  2007. JQLite.expando = 'ng339';
  2008. var jqCache = JQLite.cache = {},
  2009. jqId = 1,
  2010. addEventListenerFn = (window.document.addEventListener
  2011. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  2012. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  2013. removeEventListenerFn = (window.document.removeEventListener
  2014. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  2015. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  2016. /*
  2017. * !!! This is an undocumented "private" function !!!
  2018. */
  2019. var jqData = JQLite._data = function(node) {
  2020. //jQuery always returns an object on cache miss
  2021. return this.cache[node[this.expando]] || {};
  2022. };
  2023. function jqNextId() { return ++jqId; }
  2024. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2025. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2026. var jqLiteMinErr = minErr('jqLite');
  2027. /**
  2028. * Converts snake_case to camelCase.
  2029. * Also there is special case for Moz prefix starting with upper case letter.
  2030. * @param name Name to normalize
  2031. */
  2032. function camelCase(name) {
  2033. return name.
  2034. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2035. return offset ? letter.toUpperCase() : letter;
  2036. }).
  2037. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2038. }
  2039. /////////////////////////////////////////////
  2040. // jQuery mutation patch
  2041. //
  2042. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  2043. // $destroy event on all DOM nodes being removed.
  2044. //
  2045. /////////////////////////////////////////////
  2046. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  2047. var originalJqFn = jQuery.fn[name];
  2048. originalJqFn = originalJqFn.$original || originalJqFn;
  2049. removePatch.$original = originalJqFn;
  2050. jQuery.fn[name] = removePatch;
  2051. function removePatch(param) {
  2052. // jshint -W040
  2053. var list = filterElems && param ? [this.filter(param)] : [this],
  2054. fireEvent = dispatchThis,
  2055. set, setIndex, setLength,
  2056. element, childIndex, childLength, children;
  2057. if (!getterIfNoArguments || param != null) {
  2058. while(list.length) {
  2059. set = list.shift();
  2060. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  2061. element = jqLite(set[setIndex]);
  2062. if (fireEvent) {
  2063. element.triggerHandler('$destroy');
  2064. } else {
  2065. fireEvent = !fireEvent;
  2066. }
  2067. for(childIndex = 0, childLength = (children = element.children()).length;
  2068. childIndex < childLength;
  2069. childIndex++) {
  2070. list.push(jQuery(children[childIndex]));
  2071. }
  2072. }
  2073. }
  2074. }
  2075. return originalJqFn.apply(this, arguments);
  2076. }
  2077. }
  2078. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2079. var HTML_REGEXP = /<|&#?\w+;/;
  2080. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2081. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2082. var wrapMap = {
  2083. 'option': [1, '<select multiple="multiple">', '</select>'],
  2084. 'thead': [1, '<table>', '</table>'],
  2085. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2086. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2087. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2088. '_default': [0, "", ""]
  2089. };
  2090. wrapMap.optgroup = wrapMap.option;
  2091. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2092. wrapMap.th = wrapMap.td;
  2093. function jqLiteIsTextNode(html) {
  2094. return !HTML_REGEXP.test(html);
  2095. }
  2096. function jqLiteBuildFragment(html, context) {
  2097. var elem, tmp, tag, wrap,
  2098. fragment = context.createDocumentFragment(),
  2099. nodes = [], i, j, jj;
  2100. if (jqLiteIsTextNode(html)) {
  2101. // Convert non-html into a text node
  2102. nodes.push(context.createTextNode(html));
  2103. } else {
  2104. tmp = fragment.appendChild(context.createElement('div'));
  2105. // Convert html into DOM nodes
  2106. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2107. wrap = wrapMap[tag] || wrapMap._default;
  2108. tmp.innerHTML = '<div>&#160;</div>' +
  2109. wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2110. tmp.removeChild(tmp.firstChild);
  2111. // Descend through wrappers to the right content
  2112. i = wrap[0];
  2113. while (i--) {
  2114. tmp = tmp.lastChild;
  2115. }
  2116. for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);
  2117. tmp = fragment.firstChild;
  2118. tmp.textContent = "";
  2119. }
  2120. // Remove wrapper from fragment
  2121. fragment.textContent = "";
  2122. fragment.innerHTML = ""; // Clear inner HTML
  2123. return nodes;
  2124. }
  2125. function jqLiteParseHTML(html, context) {
  2126. context = context || document;
  2127. var parsed;
  2128. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2129. return [context.createElement(parsed[1])];
  2130. }
  2131. return jqLiteBuildFragment(html, context);
  2132. }
  2133. /////////////////////////////////////////////
  2134. function JQLite(element) {
  2135. if (element instanceof JQLite) {
  2136. return element;
  2137. }
  2138. if (isString(element)) {
  2139. element = trim(element);
  2140. }
  2141. if (!(this instanceof JQLite)) {
  2142. if (isString(element) && element.charAt(0) != '<') {
  2143. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2144. }
  2145. return new JQLite(element);
  2146. }
  2147. if (isString(element)) {
  2148. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2149. var fragment = jqLite(document.createDocumentFragment());
  2150. fragment.append(this);
  2151. } else {
  2152. jqLiteAddNodes(this, element);
  2153. }
  2154. }
  2155. function jqLiteClone(element) {
  2156. return element.cloneNode(true);
  2157. }
  2158. function jqLiteDealoc(element){
  2159. jqLiteRemoveData(element);
  2160. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  2161. jqLiteDealoc(children[i]);
  2162. }
  2163. }
  2164. function jqLiteOff(element, type, fn, unsupported) {
  2165. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2166. var events = jqLiteExpandoStore(element, 'events'),
  2167. handle = jqLiteExpandoStore(element, 'handle');
  2168. if (!handle) return; //no listeners registered
  2169. if (isUndefined(type)) {
  2170. forEach(events, function(eventHandler, type) {
  2171. removeEventListenerFn(element, type, eventHandler);
  2172. delete events[type];
  2173. });
  2174. } else {
  2175. forEach(type.split(' '), function(type) {
  2176. if (isUndefined(fn)) {
  2177. removeEventListenerFn(element, type, events[type]);
  2178. delete events[type];
  2179. } else {
  2180. arrayRemove(events[type] || [], fn);
  2181. }
  2182. });
  2183. }
  2184. }
  2185. function jqLiteRemoveData(element, name) {
  2186. var expandoId = element.ng339,
  2187. expandoStore = jqCache[expandoId];
  2188. if (expandoStore) {
  2189. if (name) {
  2190. delete jqCache[expandoId].data[name];
  2191. return;
  2192. }
  2193. if (expandoStore.handle) {
  2194. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  2195. jqLiteOff(element);
  2196. }
  2197. delete jqCache[expandoId];
  2198. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2199. }
  2200. }
  2201. function jqLiteExpandoStore(element, key, value) {
  2202. var expandoId = element.ng339,
  2203. expandoStore = jqCache[expandoId || -1];
  2204. if (isDefined(value)) {
  2205. if (!expandoStore) {
  2206. element.ng339 = expandoId = jqNextId();
  2207. expandoStore = jqCache[expandoId] = {};
  2208. }
  2209. expandoStore[key] = value;
  2210. } else {
  2211. return expandoStore && expandoStore[key];
  2212. }
  2213. }
  2214. function jqLiteData(element, key, value) {
  2215. var data = jqLiteExpandoStore(element, 'data'),
  2216. isSetter = isDefined(value),
  2217. keyDefined = !isSetter && isDefined(key),
  2218. isSimpleGetter = keyDefined && !isObject(key);
  2219. if (!data && !isSimpleGetter) {
  2220. jqLiteExpandoStore(element, 'data', data = {});
  2221. }
  2222. if (isSetter) {
  2223. data[key] = value;
  2224. } else {
  2225. if (keyDefined) {
  2226. if (isSimpleGetter) {
  2227. // don't create data in this case.
  2228. return data && data[key];
  2229. } else {
  2230. extend(data, key);
  2231. }
  2232. } else {
  2233. return data;
  2234. }
  2235. }
  2236. }
  2237. function jqLiteHasClass(element, selector) {
  2238. if (!element.getAttribute) return false;
  2239. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2240. indexOf( " " + selector + " " ) > -1);
  2241. }
  2242. function jqLiteRemoveClass(element, cssClasses) {
  2243. if (cssClasses && element.setAttribute) {
  2244. forEach(cssClasses.split(' '), function(cssClass) {
  2245. element.setAttribute('class', trim(
  2246. (" " + (element.getAttribute('class') || '') + " ")
  2247. .replace(/[\n\t]/g, " ")
  2248. .replace(" " + trim(cssClass) + " ", " "))
  2249. );
  2250. });
  2251. }
  2252. }
  2253. function jqLiteAddClass(element, cssClasses) {
  2254. if (cssClasses && element.setAttribute) {
  2255. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2256. .replace(/[\n\t]/g, " ");
  2257. forEach(cssClasses.split(' '), function(cssClass) {
  2258. cssClass = trim(cssClass);
  2259. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2260. existingClasses += cssClass + ' ';
  2261. }
  2262. });
  2263. element.setAttribute('class', trim(existingClasses));
  2264. }
  2265. }
  2266. function jqLiteAddNodes(root, elements) {
  2267. if (elements) {
  2268. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2269. ? elements
  2270. : [ elements ];
  2271. for(var i=0; i < elements.length; i++) {
  2272. root.push(elements[i]);
  2273. }
  2274. }
  2275. }
  2276. function jqLiteController(element, name) {
  2277. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2278. }
  2279. function jqLiteInheritedData(element, name, value) {
  2280. // if element is the document object work with the html element instead
  2281. // this makes $(document).scope() possible
  2282. if(element.nodeType == 9) {
  2283. element = element.documentElement;
  2284. }
  2285. var names = isArray(name) ? name : [name];
  2286. while (element) {
  2287. for (var i = 0, ii = names.length; i < ii; i++) {
  2288. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2289. }
  2290. // If dealing with a document fragment node with a host element, and no parent, use the host
  2291. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2292. // to lookup parent controllers.
  2293. element = element.parentNode || (element.nodeType === 11 && element.host);
  2294. }
  2295. }
  2296. function jqLiteEmpty(element) {
  2297. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2298. jqLiteDealoc(childNodes[i]);
  2299. }
  2300. while (element.firstChild) {
  2301. element.removeChild(element.firstChild);
  2302. }
  2303. }
  2304. //////////////////////////////////////////
  2305. // Functions which are declared directly.
  2306. //////////////////////////////////////////
  2307. var JQLitePrototype = JQLite.prototype = {
  2308. ready: function(fn) {
  2309. var fired = false;
  2310. function trigger() {
  2311. if (fired) return;
  2312. fired = true;
  2313. fn();
  2314. }
  2315. // check if document already is loaded
  2316. if (document.readyState === 'complete'){
  2317. setTimeout(trigger);
  2318. } else {
  2319. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2320. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2321. // jshint -W064
  2322. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2323. // jshint +W064
  2324. }
  2325. },
  2326. toString: function() {
  2327. var value = [];
  2328. forEach(this, function(e){ value.push('' + e);});
  2329. return '[' + value.join(', ') + ']';
  2330. },
  2331. eq: function(index) {
  2332. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2333. },
  2334. length: 0,
  2335. push: push,
  2336. sort: [].sort,
  2337. splice: [].splice
  2338. };
  2339. //////////////////////////////////////////
  2340. // Functions iterating getter/setters.
  2341. // these functions return self on setter and
  2342. // value on get.
  2343. //////////////////////////////////////////
  2344. var BOOLEAN_ATTR = {};
  2345. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2346. BOOLEAN_ATTR[lowercase(value)] = value;
  2347. });
  2348. var BOOLEAN_ELEMENTS = {};
  2349. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2350. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2351. });
  2352. function getBooleanAttrName(element, name) {
  2353. // check dom last since we will most likely fail on name
  2354. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2355. // booleanAttr is here twice to minimize DOM access
  2356. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2357. }
  2358. forEach({
  2359. data: jqLiteData,
  2360. removeData: jqLiteRemoveData
  2361. }, function(fn, name) {
  2362. JQLite[name] = fn;
  2363. });
  2364. forEach({
  2365. data: jqLiteData,
  2366. inheritedData: jqLiteInheritedData,
  2367. scope: function(element) {
  2368. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2369. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2370. },
  2371. isolateScope: function(element) {
  2372. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2373. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2374. },
  2375. controller: jqLiteController,
  2376. injector: function(element) {
  2377. return jqLiteInheritedData(element, '$injector');
  2378. },
  2379. removeAttr: function(element,name) {
  2380. element.removeAttribute(name);
  2381. },
  2382. hasClass: jqLiteHasClass,
  2383. css: function(element, name, value) {
  2384. name = camelCase(name);
  2385. if (isDefined(value)) {
  2386. element.style[name] = value;
  2387. } else {
  2388. var val;
  2389. if (msie <= 8) {
  2390. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2391. val = element.currentStyle && element.currentStyle[name];
  2392. if (val === '') val = 'auto';
  2393. }
  2394. val = val || element.style[name];
  2395. if (msie <= 8) {
  2396. // jquery weirdness :-/
  2397. val = (val === '') ? undefined : val;
  2398. }
  2399. return val;
  2400. }
  2401. },
  2402. attr: function(element, name, value){
  2403. var lowercasedName = lowercase(name);
  2404. if (BOOLEAN_ATTR[lowercasedName]) {
  2405. if (isDefined(value)) {
  2406. if (!!value) {
  2407. element[name] = true;
  2408. element.setAttribute(name, lowercasedName);
  2409. } else {
  2410. element[name] = false;
  2411. element.removeAttribute(lowercasedName);
  2412. }
  2413. } else {
  2414. return (element[name] ||
  2415. (element.attributes.getNamedItem(name)|| noop).specified)
  2416. ? lowercasedName
  2417. : undefined;
  2418. }
  2419. } else if (isDefined(value)) {
  2420. element.setAttribute(name, value);
  2421. } else if (element.getAttribute) {
  2422. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2423. // some elements (e.g. Document) don't have get attribute, so return undefined
  2424. var ret = element.getAttribute(name, 2);
  2425. // normalize non-existing attributes to undefined (as jQuery)
  2426. return ret === null ? undefined : ret;
  2427. }
  2428. },
  2429. prop: function(element, name, value) {
  2430. if (isDefined(value)) {
  2431. element[name] = value;
  2432. } else {
  2433. return element[name];
  2434. }
  2435. },
  2436. text: (function() {
  2437. var NODE_TYPE_TEXT_PROPERTY = [];
  2438. if (msie < 9) {
  2439. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2440. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2441. } else {
  2442. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2443. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2444. }
  2445. getText.$dv = '';
  2446. return getText;
  2447. function getText(element, value) {
  2448. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2449. if (isUndefined(value)) {
  2450. return textProp ? element[textProp] : '';
  2451. }
  2452. element[textProp] = value;
  2453. }
  2454. })(),
  2455. val: function(element, value) {
  2456. if (isUndefined(value)) {
  2457. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2458. var result = [];
  2459. forEach(element.options, function (option) {
  2460. if (option.selected) {
  2461. result.push(option.value || option.text);
  2462. }
  2463. });
  2464. return result.length === 0 ? null : result;
  2465. }
  2466. return element.value;
  2467. }
  2468. element.value = value;
  2469. },
  2470. html: function(element, value) {
  2471. if (isUndefined(value)) {
  2472. return element.innerHTML;
  2473. }
  2474. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2475. jqLiteDealoc(childNodes[i]);
  2476. }
  2477. element.innerHTML = value;
  2478. },
  2479. empty: jqLiteEmpty
  2480. }, function(fn, name){
  2481. /**
  2482. * Properties: writes return selection, reads return first value
  2483. */
  2484. JQLite.prototype[name] = function(arg1, arg2) {
  2485. var i, key;
  2486. var nodeCount = this.length;
  2487. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2488. // in a way that survives minification.
  2489. // jqLiteEmpty takes no arguments but is a setter.
  2490. if (fn !== jqLiteEmpty &&
  2491. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2492. if (isObject(arg1)) {
  2493. // we are a write, but the object properties are the key/values
  2494. for (i = 0; i < nodeCount; i++) {
  2495. if (fn === jqLiteData) {
  2496. // data() takes the whole object in jQuery
  2497. fn(this[i], arg1);
  2498. } else {
  2499. for (key in arg1) {
  2500. fn(this[i], key, arg1[key]);
  2501. }
  2502. }
  2503. }
  2504. // return self for chaining
  2505. return this;
  2506. } else {
  2507. // we are a read, so read the first child.
  2508. // TODO: do we still need this?
  2509. var value = fn.$dv;
  2510. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2511. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2512. for (var j = 0; j < jj; j++) {
  2513. var nodeValue = fn(this[j], arg1, arg2);
  2514. value = value ? value + nodeValue : nodeValue;
  2515. }
  2516. return value;
  2517. }
  2518. } else {
  2519. // we are a write, so apply to all children
  2520. for (i = 0; i < nodeCount; i++) {
  2521. fn(this[i], arg1, arg2);
  2522. }
  2523. // return self for chaining
  2524. return this;
  2525. }
  2526. };
  2527. });
  2528. function createEventHandler(element, events) {
  2529. var eventHandler = function (event, type) {
  2530. if (!event.preventDefault) {
  2531. event.preventDefault = function() {
  2532. event.returnValue = false; //ie
  2533. };
  2534. }
  2535. if (!event.stopPropagation) {
  2536. event.stopPropagation = function() {
  2537. event.cancelBubble = true; //ie
  2538. };
  2539. }
  2540. if (!event.target) {
  2541. event.target = event.srcElement || document;
  2542. }
  2543. if (isUndefined(event.defaultPrevented)) {
  2544. var prevent = event.preventDefault;
  2545. event.preventDefault = function() {
  2546. event.defaultPrevented = true;
  2547. prevent.call(event);
  2548. };
  2549. event.defaultPrevented = false;
  2550. }
  2551. event.isDefaultPrevented = function() {
  2552. return event.defaultPrevented || event.returnValue === false;
  2553. };
  2554. // Copy event handlers in case event handlers array is modified during execution.
  2555. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2556. forEach(eventHandlersCopy, function(fn) {
  2557. fn.call(element, event);
  2558. });
  2559. // Remove monkey-patched methods (IE),
  2560. // as they would cause memory leaks in IE8.
  2561. if (msie <= 8) {
  2562. // IE7/8 does not allow to delete property on native object
  2563. event.preventDefault = null;
  2564. event.stopPropagation = null;
  2565. event.isDefaultPrevented = null;
  2566. } else {
  2567. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2568. delete event.preventDefault;
  2569. delete event.stopPropagation;
  2570. delete event.isDefaultPrevented;
  2571. }
  2572. };
  2573. eventHandler.elem = element;
  2574. return eventHandler;
  2575. }
  2576. //////////////////////////////////////////
  2577. // Functions iterating traversal.
  2578. // These functions chain results into a single
  2579. // selector.
  2580. //////////////////////////////////////////
  2581. forEach({
  2582. removeData: jqLiteRemoveData,
  2583. dealoc: jqLiteDealoc,
  2584. on: function onFn(element, type, fn, unsupported){
  2585. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2586. var events = jqLiteExpandoStore(element, 'events'),
  2587. handle = jqLiteExpandoStore(element, 'handle');
  2588. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2589. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2590. forEach(type.split(' '), function(type){
  2591. var eventFns = events[type];
  2592. if (!eventFns) {
  2593. if (type == 'mouseenter' || type == 'mouseleave') {
  2594. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2595. function( a, b ) {
  2596. // jshint bitwise: false
  2597. var adown = a.nodeType === 9 ? a.documentElement : a,
  2598. bup = b && b.parentNode;
  2599. return a === bup || !!( bup && bup.nodeType === 1 && (
  2600. adown.contains ?
  2601. adown.contains( bup ) :
  2602. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2603. ));
  2604. } :
  2605. function( a, b ) {
  2606. if ( b ) {
  2607. while ( (b = b.parentNode) ) {
  2608. if ( b === a ) {
  2609. return true;
  2610. }
  2611. }
  2612. }
  2613. return false;
  2614. };
  2615. events[type] = [];
  2616. // Refer to jQuery's implementation of mouseenter & mouseleave
  2617. // Read about mouseenter and mouseleave:
  2618. // http://www.quirksmode.org/js/events_mouse.html#link8
  2619. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2620. onFn(element, eventmap[type], function(event) {
  2621. var target = this, related = event.relatedTarget;
  2622. // For mousenter/leave call the handler if related is outside the target.
  2623. // NB: No relatedTarget if the mouse left/entered the browser window
  2624. if ( !related || (related !== target && !contains(target, related)) ){
  2625. handle(event, type);
  2626. }
  2627. });
  2628. } else {
  2629. addEventListenerFn(element, type, handle);
  2630. events[type] = [];
  2631. }
  2632. eventFns = events[type];
  2633. }
  2634. eventFns.push(fn);
  2635. });
  2636. },
  2637. off: jqLiteOff,
  2638. one: function(element, type, fn) {
  2639. element = jqLite(element);
  2640. //add the listener twice so that when it is called
  2641. //you can remove the original function and still be
  2642. //able to call element.off(ev, fn) normally
  2643. element.on(type, function onFn() {
  2644. element.off(type, fn);
  2645. element.off(type, onFn);
  2646. });
  2647. element.on(type, fn);
  2648. },
  2649. replaceWith: function(element, replaceNode) {
  2650. var index, parent = element.parentNode;
  2651. jqLiteDealoc(element);
  2652. forEach(new JQLite(replaceNode), function(node){
  2653. if (index) {
  2654. parent.insertBefore(node, index.nextSibling);
  2655. } else {
  2656. parent.replaceChild(node, element);
  2657. }
  2658. index = node;
  2659. });
  2660. },
  2661. children: function(element) {
  2662. var children = [];
  2663. forEach(element.childNodes, function(element){
  2664. if (element.nodeType === 1)
  2665. children.push(element);
  2666. });
  2667. return children;
  2668. },
  2669. contents: function(element) {
  2670. return element.contentDocument || element.childNodes || [];
  2671. },
  2672. append: function(element, node) {
  2673. forEach(new JQLite(node), function(child){
  2674. if (element.nodeType === 1 || element.nodeType === 11) {
  2675. element.appendChild(child);
  2676. }
  2677. });
  2678. },
  2679. prepend: function(element, node) {
  2680. if (element.nodeType === 1) {
  2681. var index = element.firstChild;
  2682. forEach(new JQLite(node), function(child){
  2683. element.insertBefore(child, index);
  2684. });
  2685. }
  2686. },
  2687. wrap: function(element, wrapNode) {
  2688. wrapNode = jqLite(wrapNode)[0];
  2689. var parent = element.parentNode;
  2690. if (parent) {
  2691. parent.replaceChild(wrapNode, element);
  2692. }
  2693. wrapNode.appendChild(element);
  2694. },
  2695. remove: function(element) {
  2696. jqLiteDealoc(element);
  2697. var parent = element.parentNode;
  2698. if (parent) parent.removeChild(element);
  2699. },
  2700. after: function(element, newElement) {
  2701. var index = element, parent = element.parentNode;
  2702. forEach(new JQLite(newElement), function(node){
  2703. parent.insertBefore(node, index.nextSibling);
  2704. index = node;
  2705. });
  2706. },
  2707. addClass: jqLiteAddClass,
  2708. removeClass: jqLiteRemoveClass,
  2709. toggleClass: function(element, selector, condition) {
  2710. if (selector) {
  2711. forEach(selector.split(' '), function(className){
  2712. var classCondition = condition;
  2713. if (isUndefined(classCondition)) {
  2714. classCondition = !jqLiteHasClass(element, className);
  2715. }
  2716. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2717. });
  2718. }
  2719. },
  2720. parent: function(element) {
  2721. var parent = element.parentNode;
  2722. return parent && parent.nodeType !== 11 ? parent : null;
  2723. },
  2724. next: function(element) {
  2725. if (element.nextElementSibling) {
  2726. return element.nextElementSibling;
  2727. }
  2728. // IE8 doesn't have nextElementSibling
  2729. var elm = element.nextSibling;
  2730. while (elm != null && elm.nodeType !== 1) {
  2731. elm = elm.nextSibling;
  2732. }
  2733. return elm;
  2734. },
  2735. find: function(element, selector) {
  2736. if (element.getElementsByTagName) {
  2737. return element.getElementsByTagName(selector);
  2738. } else {
  2739. return [];
  2740. }
  2741. },
  2742. clone: jqLiteClone,
  2743. triggerHandler: function(element, event, extraParameters) {
  2744. var dummyEvent, eventFnsCopy, handlerArgs;
  2745. var eventName = event.type || event;
  2746. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2747. if (eventFns) {
  2748. // Create a dummy event to pass to the handlers
  2749. dummyEvent = {
  2750. preventDefault: function() { this.defaultPrevented = true; },
  2751. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2752. stopPropagation: noop,
  2753. type: eventName,
  2754. target: element
  2755. };
  2756. // If a custom event was provided then extend our dummy event with it
  2757. if (event.type) {
  2758. dummyEvent = extend(dummyEvent, event);
  2759. }
  2760. // Copy event handlers in case event handlers array is modified during execution.
  2761. eventFnsCopy = shallowCopy(eventFns);
  2762. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2763. forEach(eventFnsCopy, function(fn) {
  2764. fn.apply(element, handlerArgs);
  2765. });
  2766. }
  2767. }
  2768. }, function(fn, name){
  2769. /**
  2770. * chaining functions
  2771. */
  2772. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2773. var value;
  2774. for(var i=0; i < this.length; i++) {
  2775. if (isUndefined(value)) {
  2776. value = fn(this[i], arg1, arg2, arg3);
  2777. if (isDefined(value)) {
  2778. // any function which returns a value needs to be wrapped
  2779. value = jqLite(value);
  2780. }
  2781. } else {
  2782. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2783. }
  2784. }
  2785. return isDefined(value) ? value : this;
  2786. };
  2787. // bind legacy bind/unbind to on/off
  2788. JQLite.prototype.bind = JQLite.prototype.on;
  2789. JQLite.prototype.unbind = JQLite.prototype.off;
  2790. });
  2791. /**
  2792. * Computes a hash of an 'obj'.
  2793. * Hash of a:
  2794. * string is string
  2795. * number is number as string
  2796. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2797. * that is also assigned to the $$hashKey property of the object.
  2798. *
  2799. * @param obj
  2800. * @returns {string} hash string such that the same input will have the same hash string.
  2801. * The resulting string key is in 'type:hashKey' format.
  2802. */
  2803. function hashKey(obj, nextUidFn) {
  2804. var objType = typeof obj,
  2805. key;
  2806. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2807. if (typeof (key = obj.$$hashKey) == 'function') {
  2808. // must invoke on object to keep the right this
  2809. key = obj.$$hashKey();
  2810. } else if (key === undefined) {
  2811. key = obj.$$hashKey = (nextUidFn || nextUid)();
  2812. }
  2813. } else {
  2814. key = obj;
  2815. }
  2816. return objType + ':' + key;
  2817. }
  2818. /**
  2819. * HashMap which can use objects as keys
  2820. */
  2821. function HashMap(array, isolatedUid) {
  2822. if (isolatedUid) {
  2823. var uid = 0;
  2824. this.nextUid = function() {
  2825. return ++uid;
  2826. };
  2827. }
  2828. forEach(array, this.put, this);
  2829. }
  2830. HashMap.prototype = {
  2831. /**
  2832. * Store key value pair
  2833. * @param key key to store can be any type
  2834. * @param value value to store can be any type
  2835. */
  2836. put: function(key, value) {
  2837. this[hashKey(key, this.nextUid)] = value;
  2838. },
  2839. /**
  2840. * @param key
  2841. * @returns {Object} the value for the key
  2842. */
  2843. get: function(key) {
  2844. return this[hashKey(key, this.nextUid)];
  2845. },
  2846. /**
  2847. * Remove the key/value pair
  2848. * @param key
  2849. */
  2850. remove: function(key) {
  2851. var value = this[key = hashKey(key, this.nextUid)];
  2852. delete this[key];
  2853. return value;
  2854. }
  2855. };
  2856. /**
  2857. * @ngdoc function
  2858. * @module ng
  2859. * @name angular.injector
  2860. * @kind function
  2861. *
  2862. * @description
  2863. * Creates an injector object that can be used for retrieving services as well as for
  2864. * dependency injection (see {@link guide/di dependency injection}).
  2865. *
  2866. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2867. * {@link angular.module}. The `ng` module must be explicitly added.
  2868. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2869. *
  2870. * @example
  2871. * Typical usage
  2872. * ```js
  2873. * // create an injector
  2874. * var $injector = angular.injector(['ng']);
  2875. *
  2876. * // use the injector to kick off your application
  2877. * // use the type inference to auto inject arguments, or use implicit injection
  2878. * $injector.invoke(function($rootScope, $compile, $document){
  2879. * $compile($document)($rootScope);
  2880. * $rootScope.$digest();
  2881. * });
  2882. * ```
  2883. *
  2884. * Sometimes you want to get access to the injector of a currently running Angular app
  2885. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2886. * application has been bootstrapped. You can do this using the extra `injector()` added
  2887. * to JQuery/jqLite elements. See {@link angular.element}.
  2888. *
  2889. * *This is fairly rare but could be the case if a third party library is injecting the
  2890. * markup.*
  2891. *
  2892. * In the following example a new block of HTML containing a `ng-controller`
  2893. * directive is added to the end of the document body by JQuery. We then compile and link
  2894. * it into the current AngularJS scope.
  2895. *
  2896. * ```js
  2897. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2898. * $(document.body).append($div);
  2899. *
  2900. * angular.element(document).injector().invoke(function($compile) {
  2901. * var scope = angular.element($div).scope();
  2902. * $compile($div)(scope);
  2903. * });
  2904. * ```
  2905. */
  2906. /**
  2907. * @ngdoc module
  2908. * @name auto
  2909. * @description
  2910. *
  2911. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2912. */
  2913. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2914. var FN_ARG_SPLIT = /,/;
  2915. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2916. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2917. var $injectorMinErr = minErr('$injector');
  2918. function annotate(fn) {
  2919. var $inject,
  2920. fnText,
  2921. argDecl,
  2922. last;
  2923. if (typeof fn === 'function') {
  2924. if (!($inject = fn.$inject)) {
  2925. $inject = [];
  2926. if (fn.length) {
  2927. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2928. argDecl = fnText.match(FN_ARGS);
  2929. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2930. arg.replace(FN_ARG, function(all, underscore, name){
  2931. $inject.push(name);
  2932. });
  2933. });
  2934. }
  2935. fn.$inject = $inject;
  2936. }
  2937. } else if (isArray(fn)) {
  2938. last = fn.length - 1;
  2939. assertArgFn(fn[last], 'fn');
  2940. $inject = fn.slice(0, last);
  2941. } else {
  2942. assertArgFn(fn, 'fn', true);
  2943. }
  2944. return $inject;
  2945. }
  2946. ///////////////////////////////////////
  2947. /**
  2948. * @ngdoc service
  2949. * @name $injector
  2950. *
  2951. * @description
  2952. *
  2953. * `$injector` is used to retrieve object instances as defined by
  2954. * {@link auto.$provide provider}, instantiate types, invoke methods,
  2955. * and load modules.
  2956. *
  2957. * The following always holds true:
  2958. *
  2959. * ```js
  2960. * var $injector = angular.injector();
  2961. * expect($injector.get('$injector')).toBe($injector);
  2962. * expect($injector.invoke(function($injector){
  2963. * return $injector;
  2964. * })).toBe($injector);
  2965. * ```
  2966. *
  2967. * # Injection Function Annotation
  2968. *
  2969. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2970. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2971. *
  2972. * ```js
  2973. * // inferred (only works if code not minified/obfuscated)
  2974. * $injector.invoke(function(serviceA){});
  2975. *
  2976. * // annotated
  2977. * function explicit(serviceA) {};
  2978. * explicit.$inject = ['serviceA'];
  2979. * $injector.invoke(explicit);
  2980. *
  2981. * // inline
  2982. * $injector.invoke(['serviceA', function(serviceA){}]);
  2983. * ```
  2984. *
  2985. * ## Inference
  2986. *
  2987. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2988. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2989. * minification, and obfuscation tools since these tools change the argument names.
  2990. *
  2991. * ## `$inject` Annotation
  2992. * By adding an `$inject` property onto a function the injection parameters can be specified.
  2993. *
  2994. * ## Inline
  2995. * As an array of injection names, where the last item in the array is the function to call.
  2996. */
  2997. /**
  2998. * @ngdoc method
  2999. * @name $injector#get
  3000. *
  3001. * @description
  3002. * Return an instance of the service.
  3003. *
  3004. * @param {string} name The name of the instance to retrieve.
  3005. * @return {*} The instance.
  3006. */
  3007. /**
  3008. * @ngdoc method
  3009. * @name $injector#invoke
  3010. *
  3011. * @description
  3012. * Invoke the method and supply the method arguments from the `$injector`.
  3013. *
  3014. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3015. * {@link guide/di $inject Annotation} rules.
  3016. * @param {Object=} self The `this` for the invoked method.
  3017. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3018. * object first, before the `$injector` is consulted.
  3019. * @returns {*} the value returned by the invoked `fn` function.
  3020. */
  3021. /**
  3022. * @ngdoc method
  3023. * @name $injector#has
  3024. *
  3025. * @description
  3026. * Allows the user to query if the particular service exists.
  3027. *
  3028. * @param {string} name Name of the service to query.
  3029. * @returns {boolean} `true` if injector has given service.
  3030. */
  3031. /**
  3032. * @ngdoc method
  3033. * @name $injector#instantiate
  3034. * @description
  3035. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3036. * operator, and supplies all of the arguments to the constructor function as specified by the
  3037. * constructor annotation.
  3038. *
  3039. * @param {Function} Type Annotated constructor function.
  3040. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3041. * object first, before the `$injector` is consulted.
  3042. * @returns {Object} new instance of `Type`.
  3043. */
  3044. /**
  3045. * @ngdoc method
  3046. * @name $injector#annotate
  3047. *
  3048. * @description
  3049. * Returns an array of service names which the function is requesting for injection. This API is
  3050. * used by the injector to determine which services need to be injected into the function when the
  3051. * function is invoked. There are three ways in which the function can be annotated with the needed
  3052. * dependencies.
  3053. *
  3054. * # Argument names
  3055. *
  3056. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3057. * by converting the function into a string using `toString()` method and extracting the argument
  3058. * names.
  3059. * ```js
  3060. * // Given
  3061. * function MyController($scope, $route) {
  3062. * // ...
  3063. * }
  3064. *
  3065. * // Then
  3066. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3067. * ```
  3068. *
  3069. * This method does not work with code minification / obfuscation. For this reason the following
  3070. * annotation strategies are supported.
  3071. *
  3072. * # The `$inject` property
  3073. *
  3074. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3075. * represent names of services to be injected into the function.
  3076. * ```js
  3077. * // Given
  3078. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3079. * // ...
  3080. * }
  3081. * // Define function dependencies
  3082. * MyController['$inject'] = ['$scope', '$route'];
  3083. *
  3084. * // Then
  3085. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3086. * ```
  3087. *
  3088. * # The array notation
  3089. *
  3090. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3091. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3092. * a way that survives minification is a better choice:
  3093. *
  3094. * ```js
  3095. * // We wish to write this (not minification / obfuscation safe)
  3096. * injector.invoke(function($compile, $rootScope) {
  3097. * // ...
  3098. * });
  3099. *
  3100. * // We are forced to write break inlining
  3101. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3102. * // ...
  3103. * };
  3104. * tmpFn.$inject = ['$compile', '$rootScope'];
  3105. * injector.invoke(tmpFn);
  3106. *
  3107. * // To better support inline function the inline annotation is supported
  3108. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3109. * // ...
  3110. * }]);
  3111. *
  3112. * // Therefore
  3113. * expect(injector.annotate(
  3114. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3115. * ).toEqual(['$compile', '$rootScope']);
  3116. * ```
  3117. *
  3118. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3119. * be retrieved as described above.
  3120. *
  3121. * @returns {Array.<string>} The names of the services which the function requires.
  3122. */
  3123. /**
  3124. * @ngdoc service
  3125. * @name $provide
  3126. *
  3127. * @description
  3128. *
  3129. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3130. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3131. * {@link angular.Module}.
  3132. *
  3133. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3134. * factories** are functions which, in turn, are created by a **service provider**.
  3135. * The **service providers** are constructor functions. When instantiated they must contain a
  3136. * property called `$get`, which holds the **service factory** function.
  3137. *
  3138. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3139. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3140. * function to get the instance of the **service**.
  3141. *
  3142. * Often services have no configuration options and there is no need to add methods to the service
  3143. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3144. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3145. * services without specifying a provider.
  3146. *
  3147. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3148. * {@link auto.$injector $injector}
  3149. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3150. * providers and services.
  3151. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3152. * services, not providers.
  3153. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3154. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3155. * given factory function.
  3156. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3157. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3158. * a new object using the given constructor function.
  3159. *
  3160. * See the individual methods for more information and examples.
  3161. */
  3162. /**
  3163. * @ngdoc method
  3164. * @name $provide#provider
  3165. * @description
  3166. *
  3167. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3168. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3169. * service.
  3170. *
  3171. * Service provider names start with the name of the service they provide followed by `Provider`.
  3172. * For example, the {@link ng.$log $log} service has a provider called
  3173. * {@link ng.$logProvider $logProvider}.
  3174. *
  3175. * Service provider objects can have additional methods which allow configuration of the provider
  3176. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3177. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3178. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3179. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3180. * console or not.
  3181. *
  3182. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3183. 'Provider'` key.
  3184. * @param {(Object|function())} provider If the provider is:
  3185. *
  3186. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3187. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3188. * - `Constructor`: a new instance of the provider will be created using
  3189. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3190. *
  3191. * @returns {Object} registered provider instance
  3192. * @example
  3193. *
  3194. * The following example shows how to create a simple event tracking service and register it using
  3195. * {@link auto.$provide#provider $provide.provider()}.
  3196. *
  3197. * ```js
  3198. * // Define the eventTracker provider
  3199. * function EventTrackerProvider() {
  3200. * var trackingUrl = '/track';
  3201. *
  3202. * // A provider method for configuring where the tracked events should been saved
  3203. * this.setTrackingUrl = function(url) {
  3204. * trackingUrl = url;
  3205. * };
  3206. *
  3207. * // The service factory function
  3208. * this.$get = ['$http', function($http) {
  3209. * var trackedEvents = {};
  3210. * return {
  3211. * // Call this to track an event
  3212. * event: function(event) {
  3213. * var count = trackedEvents[event] || 0;
  3214. * count += 1;
  3215. * trackedEvents[event] = count;
  3216. * return count;
  3217. * },
  3218. * // Call this to save the tracked events to the trackingUrl
  3219. * save: function() {
  3220. * $http.post(trackingUrl, trackedEvents);
  3221. * }
  3222. * };
  3223. * }];
  3224. * }
  3225. *
  3226. * describe('eventTracker', function() {
  3227. * var postSpy;
  3228. *
  3229. * beforeEach(module(function($provide) {
  3230. * // Register the eventTracker provider
  3231. * $provide.provider('eventTracker', EventTrackerProvider);
  3232. * }));
  3233. *
  3234. * beforeEach(module(function(eventTrackerProvider) {
  3235. * // Configure eventTracker provider
  3236. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3237. * }));
  3238. *
  3239. * it('tracks events', inject(function(eventTracker) {
  3240. * expect(eventTracker.event('login')).toEqual(1);
  3241. * expect(eventTracker.event('login')).toEqual(2);
  3242. * }));
  3243. *
  3244. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3245. * postSpy = spyOn($http, 'post');
  3246. * eventTracker.event('login');
  3247. * eventTracker.save();
  3248. * expect(postSpy).toHaveBeenCalled();
  3249. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3250. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3251. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3252. * }));
  3253. * });
  3254. * ```
  3255. */
  3256. /**
  3257. * @ngdoc method
  3258. * @name $provide#factory
  3259. * @description
  3260. *
  3261. * Register a **service factory**, which will be called to return the service instance.
  3262. * This is short for registering a service where its provider consists of only a `$get` property,
  3263. * which is the given service factory function.
  3264. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3265. * configure your service in a provider.
  3266. *
  3267. * @param {string} name The name of the instance.
  3268. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3269. * for `$provide.provider(name, {$get: $getFn})`.
  3270. * @returns {Object} registered provider instance
  3271. *
  3272. * @example
  3273. * Here is an example of registering a service
  3274. * ```js
  3275. * $provide.factory('ping', ['$http', function($http) {
  3276. * return function ping() {
  3277. * return $http.send('/ping');
  3278. * };
  3279. * }]);
  3280. * ```
  3281. * You would then inject and use this service like this:
  3282. * ```js
  3283. * someModule.controller('Ctrl', ['ping', function(ping) {
  3284. * ping();
  3285. * }]);
  3286. * ```
  3287. */
  3288. /**
  3289. * @ngdoc method
  3290. * @name $provide#service
  3291. * @description
  3292. *
  3293. * Register a **service constructor**, which will be invoked with `new` to create the service
  3294. * instance.
  3295. * This is short for registering a service where its provider's `$get` property is the service
  3296. * constructor function that will be used to instantiate the service instance.
  3297. *
  3298. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3299. * as a type/class.
  3300. *
  3301. * @param {string} name The name of the instance.
  3302. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3303. * @returns {Object} registered provider instance
  3304. *
  3305. * @example
  3306. * Here is an example of registering a service using
  3307. * {@link auto.$provide#service $provide.service(class)}.
  3308. * ```js
  3309. * var Ping = function($http) {
  3310. * this.$http = $http;
  3311. * };
  3312. *
  3313. * Ping.$inject = ['$http'];
  3314. *
  3315. * Ping.prototype.send = function() {
  3316. * return this.$http.get('/ping');
  3317. * };
  3318. * $provide.service('ping', Ping);
  3319. * ```
  3320. * You would then inject and use this service like this:
  3321. * ```js
  3322. * someModule.controller('Ctrl', ['ping', function(ping) {
  3323. * ping.send();
  3324. * }]);
  3325. * ```
  3326. */
  3327. /**
  3328. * @ngdoc method
  3329. * @name $provide#value
  3330. * @description
  3331. *
  3332. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3333. * number, an array, an object or a function. This is short for registering a service where its
  3334. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3335. * service**.
  3336. *
  3337. * Value services are similar to constant services, except that they cannot be injected into a
  3338. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3339. * an Angular
  3340. * {@link auto.$provide#decorator decorator}.
  3341. *
  3342. * @param {string} name The name of the instance.
  3343. * @param {*} value The value.
  3344. * @returns {Object} registered provider instance
  3345. *
  3346. * @example
  3347. * Here are some examples of creating value services.
  3348. * ```js
  3349. * $provide.value('ADMIN_USER', 'admin');
  3350. *
  3351. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3352. *
  3353. * $provide.value('halfOf', function(value) {
  3354. * return value / 2;
  3355. * });
  3356. * ```
  3357. */
  3358. /**
  3359. * @ngdoc method
  3360. * @name $provide#constant
  3361. * @description
  3362. *
  3363. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3364. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3365. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3366. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3367. *
  3368. * @param {string} name The name of the constant.
  3369. * @param {*} value The constant value.
  3370. * @returns {Object} registered instance
  3371. *
  3372. * @example
  3373. * Here a some examples of creating constants:
  3374. * ```js
  3375. * $provide.constant('SHARD_HEIGHT', 306);
  3376. *
  3377. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3378. *
  3379. * $provide.constant('double', function(value) {
  3380. * return value * 2;
  3381. * });
  3382. * ```
  3383. */
  3384. /**
  3385. * @ngdoc method
  3386. * @name $provide#decorator
  3387. * @description
  3388. *
  3389. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3390. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3391. * service. The object returned by the decorator may be the original service, or a new service
  3392. * object which replaces or wraps and delegates to the original service.
  3393. *
  3394. * @param {string} name The name of the service to decorate.
  3395. * @param {function()} decorator This function will be invoked when the service needs to be
  3396. * instantiated and should return the decorated service instance. The function is called using
  3397. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3398. * Local injection arguments:
  3399. *
  3400. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3401. * decorated or delegated to.
  3402. *
  3403. * @example
  3404. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3405. * calls to {@link ng.$log#error $log.warn()}.
  3406. * ```js
  3407. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3408. * $delegate.warn = $delegate.error;
  3409. * return $delegate;
  3410. * }]);
  3411. * ```
  3412. */
  3413. function createInjector(modulesToLoad) {
  3414. var INSTANTIATING = {},
  3415. providerSuffix = 'Provider',
  3416. path = [],
  3417. loadedModules = new HashMap([], true),
  3418. providerCache = {
  3419. $provide: {
  3420. provider: supportObject(provider),
  3421. factory: supportObject(factory),
  3422. service: supportObject(service),
  3423. value: supportObject(value),
  3424. constant: supportObject(constant),
  3425. decorator: decorator
  3426. }
  3427. },
  3428. providerInjector = (providerCache.$injector =
  3429. createInternalInjector(providerCache, function() {
  3430. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3431. })),
  3432. instanceCache = {},
  3433. instanceInjector = (instanceCache.$injector =
  3434. createInternalInjector(instanceCache, function(servicename) {
  3435. var provider = providerInjector.get(servicename + providerSuffix);
  3436. return instanceInjector.invoke(provider.$get, provider);
  3437. }));
  3438. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3439. return instanceInjector;
  3440. ////////////////////////////////////
  3441. // $provider
  3442. ////////////////////////////////////
  3443. function supportObject(delegate) {
  3444. return function(key, value) {
  3445. if (isObject(key)) {
  3446. forEach(key, reverseParams(delegate));
  3447. } else {
  3448. return delegate(key, value);
  3449. }
  3450. };
  3451. }
  3452. function provider(name, provider_) {
  3453. assertNotHasOwnProperty(name, 'service');
  3454. if (isFunction(provider_) || isArray(provider_)) {
  3455. provider_ = providerInjector.instantiate(provider_);
  3456. }
  3457. if (!provider_.$get) {
  3458. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3459. }
  3460. return providerCache[name + providerSuffix] = provider_;
  3461. }
  3462. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3463. function service(name, constructor) {
  3464. return factory(name, ['$injector', function($injector) {
  3465. return $injector.instantiate(constructor);
  3466. }]);
  3467. }
  3468. function value(name, val) { return factory(name, valueFn(val)); }
  3469. function constant(name, value) {
  3470. assertNotHasOwnProperty(name, 'constant');
  3471. providerCache[name] = value;
  3472. instanceCache[name] = value;
  3473. }
  3474. function decorator(serviceName, decorFn) {
  3475. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3476. orig$get = origProvider.$get;
  3477. origProvider.$get = function() {
  3478. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3479. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3480. };
  3481. }
  3482. ////////////////////////////////////
  3483. // Module Loading
  3484. ////////////////////////////////////
  3485. function loadModules(modulesToLoad){
  3486. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3487. forEach(modulesToLoad, function(module) {
  3488. if (loadedModules.get(module)) return;
  3489. loadedModules.put(module, true);
  3490. try {
  3491. if (isString(module)) {
  3492. moduleFn = angularModule(module);
  3493. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3494. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3495. var invokeArgs = invokeQueue[i],
  3496. provider = providerInjector.get(invokeArgs[0]);
  3497. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3498. }
  3499. } else if (isFunction(module)) {
  3500. runBlocks.push(providerInjector.invoke(module));
  3501. } else if (isArray(module)) {
  3502. runBlocks.push(providerInjector.invoke(module));
  3503. } else {
  3504. assertArgFn(module, 'module');
  3505. }
  3506. } catch (e) {
  3507. if (isArray(module)) {
  3508. module = module[module.length - 1];
  3509. }
  3510. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3511. // Safari & FF's stack traces don't contain error.message content
  3512. // unlike those of Chrome and IE
  3513. // So if stack doesn't contain message, we create a new string that contains both.
  3514. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3515. /* jshint -W022 */
  3516. e = e.message + '\n' + e.stack;
  3517. }
  3518. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3519. module, e.stack || e.message || e);
  3520. }
  3521. });
  3522. return runBlocks;
  3523. }
  3524. ////////////////////////////////////
  3525. // internal Injector
  3526. ////////////////////////////////////
  3527. function createInternalInjector(cache, factory) {
  3528. function getService(serviceName) {
  3529. if (cache.hasOwnProperty(serviceName)) {
  3530. if (cache[serviceName] === INSTANTIATING) {
  3531. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3532. serviceName + ' <- ' + path.join(' <- '));
  3533. }
  3534. return cache[serviceName];
  3535. } else {
  3536. try {
  3537. path.unshift(serviceName);
  3538. cache[serviceName] = INSTANTIATING;
  3539. return cache[serviceName] = factory(serviceName);
  3540. } catch (err) {
  3541. if (cache[serviceName] === INSTANTIATING) {
  3542. delete cache[serviceName];
  3543. }
  3544. throw err;
  3545. } finally {
  3546. path.shift();
  3547. }
  3548. }
  3549. }
  3550. function invoke(fn, self, locals){
  3551. var args = [],
  3552. $inject = annotate(fn),
  3553. length, i,
  3554. key;
  3555. for(i = 0, length = $inject.length; i < length; i++) {
  3556. key = $inject[i];
  3557. if (typeof key !== 'string') {
  3558. throw $injectorMinErr('itkn',
  3559. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3560. }
  3561. args.push(
  3562. locals && locals.hasOwnProperty(key)
  3563. ? locals[key]
  3564. : getService(key)
  3565. );
  3566. }
  3567. if (isArray(fn)) {
  3568. fn = fn[length];
  3569. }
  3570. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3571. // #5388
  3572. return fn.apply(self, args);
  3573. }
  3574. function instantiate(Type, locals) {
  3575. var Constructor = function() {},
  3576. instance, returnedValue;
  3577. // Check if Type is annotated and use just the given function at n-1 as parameter
  3578. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3579. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3580. instance = new Constructor();
  3581. returnedValue = invoke(Type, instance, locals);
  3582. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3583. }
  3584. return {
  3585. invoke: invoke,
  3586. instantiate: instantiate,
  3587. get: getService,
  3588. annotate: annotate,
  3589. has: function(name) {
  3590. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3591. }
  3592. };
  3593. }
  3594. }
  3595. /**
  3596. * @ngdoc service
  3597. * @name $anchorScroll
  3598. * @kind function
  3599. * @requires $window
  3600. * @requires $location
  3601. * @requires $rootScope
  3602. *
  3603. * @description
  3604. * When called, it checks current value of `$location.hash()` and scrolls to the related element,
  3605. * according to rules specified in
  3606. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3607. *
  3608. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3609. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3610. *
  3611. * @example
  3612. <example>
  3613. <file name="index.html">
  3614. <div id="scrollArea" ng-controller="ScrollCtrl">
  3615. <a ng-click="gotoBottom()">Go to bottom</a>
  3616. <a id="bottom"></a> You're at the bottom!
  3617. </div>
  3618. </file>
  3619. <file name="script.js">
  3620. function ScrollCtrl($scope, $location, $anchorScroll) {
  3621. $scope.gotoBottom = function (){
  3622. // set the location.hash to the id of
  3623. // the element you wish to scroll to.
  3624. $location.hash('bottom');
  3625. // call $anchorScroll()
  3626. $anchorScroll();
  3627. };
  3628. }
  3629. </file>
  3630. <file name="style.css">
  3631. #scrollArea {
  3632. height: 350px;
  3633. overflow: auto;
  3634. }
  3635. #bottom {
  3636. display: block;
  3637. margin-top: 2000px;
  3638. }
  3639. </file>
  3640. </example>
  3641. */
  3642. function $AnchorScrollProvider() {
  3643. var autoScrollingEnabled = true;
  3644. /**
  3645. * @ngdoc method
  3646. * @name $anchorScrollProvider#disableAutoScrolling
  3647. *
  3648. * @description
  3649. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3650. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3651. * Use this method to disable automatic scrolling.
  3652. *
  3653. * If automatic scrolling is disabled, one must explicitly call
  3654. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3655. * current hash.
  3656. */
  3657. this.disableAutoScrolling = function() {
  3658. autoScrollingEnabled = false;
  3659. };
  3660. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3661. var document = $window.document;
  3662. // helper function to get first anchor from a NodeList
  3663. // can't use filter.filter, as it accepts only instances of Array
  3664. // and IE can't convert NodeList to an array using [].slice
  3665. // TODO(vojta): use filter if we change it to accept lists as well
  3666. function getFirstAnchor(list) {
  3667. var result = null;
  3668. forEach(list, function(element) {
  3669. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3670. });
  3671. return result;
  3672. }
  3673. function scroll() {
  3674. var hash = $location.hash(), elm;
  3675. // empty hash, scroll to the top of the page
  3676. if (!hash) $window.scrollTo(0, 0);
  3677. // element with given id
  3678. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3679. // first anchor with given name :-D
  3680. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3681. // no element and hash == 'top', scroll to the top of the page
  3682. else if (hash === 'top') $window.scrollTo(0, 0);
  3683. }
  3684. // does not scroll when user clicks on anchor link that is currently on
  3685. // (no url change, no $location.hash() change), browser native does scroll
  3686. if (autoScrollingEnabled) {
  3687. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3688. function autoScrollWatchAction() {
  3689. $rootScope.$evalAsync(scroll);
  3690. });
  3691. }
  3692. return scroll;
  3693. }];
  3694. }
  3695. var $animateMinErr = minErr('$animate');
  3696. /**
  3697. * @ngdoc provider
  3698. * @name $animateProvider
  3699. *
  3700. * @description
  3701. * Default implementation of $animate that doesn't perform any animations, instead just
  3702. * synchronously performs DOM
  3703. * updates and calls done() callbacks.
  3704. *
  3705. * In order to enable animations the ngAnimate module has to be loaded.
  3706. *
  3707. * To see the functional implementation check out src/ngAnimate/animate.js
  3708. */
  3709. var $AnimateProvider = ['$provide', function($provide) {
  3710. this.$$selectors = {};
  3711. /**
  3712. * @ngdoc method
  3713. * @name $animateProvider#register
  3714. *
  3715. * @description
  3716. * Registers a new injectable animation factory function. The factory function produces the
  3717. * animation object which contains callback functions for each event that is expected to be
  3718. * animated.
  3719. *
  3720. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3721. * must be called once the element animation is complete. If a function is returned then the
  3722. * animation service will use this function to cancel the animation whenever a cancel event is
  3723. * triggered.
  3724. *
  3725. *
  3726. * ```js
  3727. * return {
  3728. * eventFn : function(element, done) {
  3729. * //code to run the animation
  3730. * //once complete, then run done()
  3731. * return function cancellationFunction() {
  3732. * //code to cancel the animation
  3733. * }
  3734. * }
  3735. * }
  3736. * ```
  3737. *
  3738. * @param {string} name The name of the animation.
  3739. * @param {Function} factory The factory function that will be executed to return the animation
  3740. * object.
  3741. */
  3742. this.register = function(name, factory) {
  3743. var key = name + '-animation';
  3744. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3745. "Expecting class selector starting with '.' got '{0}'.", name);
  3746. this.$$selectors[name.substr(1)] = key;
  3747. $provide.factory(key, factory);
  3748. };
  3749. /**
  3750. * @ngdoc method
  3751. * @name $animateProvider#classNameFilter
  3752. *
  3753. * @description
  3754. * Sets and/or returns the CSS class regular expression that is checked when performing
  3755. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3756. * therefore enable $animate to attempt to perform an animation on any element.
  3757. * When setting the classNameFilter value, animations will only be performed on elements
  3758. * that successfully match the filter expression. This in turn can boost performance
  3759. * for low-powered devices as well as applications containing a lot of structural operations.
  3760. * @param {RegExp=} expression The className expression which will be checked against all animations
  3761. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3762. */
  3763. this.classNameFilter = function(expression) {
  3764. if(arguments.length === 1) {
  3765. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3766. }
  3767. return this.$$classNameFilter;
  3768. };
  3769. this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
  3770. function async(fn) {
  3771. fn && $$asyncCallback(fn);
  3772. }
  3773. /**
  3774. *
  3775. * @ngdoc service
  3776. * @name $animate
  3777. * @description The $animate service provides rudimentary DOM manipulation functions to
  3778. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3779. * This service is the core service used by the ngAnimate $animator service which provides
  3780. * high-level animation hooks for CSS and JavaScript.
  3781. *
  3782. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3783. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3784. * manipulation operations.
  3785. *
  3786. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3787. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3788. * page}.
  3789. */
  3790. return {
  3791. /**
  3792. *
  3793. * @ngdoc method
  3794. * @name $animate#enter
  3795. * @kind function
  3796. * @description Inserts the element into the DOM either after the `after` element or within
  3797. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3798. * @param {DOMElement} element the element which will be inserted into the DOM
  3799. * @param {DOMElement} parent the parent element which will append the element as
  3800. * a child (if the after element is not present)
  3801. * @param {DOMElement} after the sibling element which will append the element
  3802. * after itself
  3803. * @param {Function=} done callback function that will be called after the element has been
  3804. * inserted into the DOM
  3805. */
  3806. enter : function(element, parent, after, done) {
  3807. if (after) {
  3808. after.after(element);
  3809. } else {
  3810. if (!parent || !parent[0]) {
  3811. parent = after.parent();
  3812. }
  3813. parent.append(element);
  3814. }
  3815. async(done);
  3816. },
  3817. /**
  3818. *
  3819. * @ngdoc method
  3820. * @name $animate#leave
  3821. * @kind function
  3822. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3823. * fired (if provided).
  3824. * @param {DOMElement} element the element which will be removed from the DOM
  3825. * @param {Function=} done callback function that will be called after the element has been
  3826. * removed from the DOM
  3827. */
  3828. leave : function(element, done) {
  3829. element.remove();
  3830. async(done);
  3831. },
  3832. /**
  3833. *
  3834. * @ngdoc method
  3835. * @name $animate#move
  3836. * @kind function
  3837. * @description Moves the position of the provided element within the DOM to be placed
  3838. * either after the `after` element or inside of the `parent` element. Once complete, the
  3839. * done() callback will be fired (if provided).
  3840. *
  3841. * @param {DOMElement} element the element which will be moved around within the
  3842. * DOM
  3843. * @param {DOMElement} parent the parent element where the element will be
  3844. * inserted into (if the after element is not present)
  3845. * @param {DOMElement} after the sibling element where the element will be
  3846. * positioned next to
  3847. * @param {Function=} done the callback function (if provided) that will be fired after the
  3848. * element has been moved to its new position
  3849. */
  3850. move : function(element, parent, after, done) {
  3851. // Do not remove element before insert. Removing will cause data associated with the
  3852. // element to be dropped. Insert will implicitly do the remove.
  3853. this.enter(element, parent, after, done);
  3854. },
  3855. /**
  3856. *
  3857. * @ngdoc method
  3858. * @name $animate#addClass
  3859. * @kind function
  3860. * @description Adds the provided className CSS class value to the provided element. Once
  3861. * complete, the done() callback will be fired (if provided).
  3862. * @param {DOMElement} element the element which will have the className value
  3863. * added to it
  3864. * @param {string} className the CSS class which will be added to the element
  3865. * @param {Function=} done the callback function (if provided) that will be fired after the
  3866. * className value has been added to the element
  3867. */
  3868. addClass : function(element, className, done) {
  3869. className = isString(className) ?
  3870. className :
  3871. isArray(className) ? className.join(' ') : '';
  3872. forEach(element, function (element) {
  3873. jqLiteAddClass(element, className);
  3874. });
  3875. async(done);
  3876. },
  3877. /**
  3878. *
  3879. * @ngdoc method
  3880. * @name $animate#removeClass
  3881. * @kind function
  3882. * @description Removes the provided className CSS class value from the provided element.
  3883. * Once complete, the done() callback will be fired (if provided).
  3884. * @param {DOMElement} element the element which will have the className value
  3885. * removed from it
  3886. * @param {string} className the CSS class which will be removed from the element
  3887. * @param {Function=} done the callback function (if provided) that will be fired after the
  3888. * className value has been removed from the element
  3889. */
  3890. removeClass : function(element, className, done) {
  3891. className = isString(className) ?
  3892. className :
  3893. isArray(className) ? className.join(' ') : '';
  3894. forEach(element, function (element) {
  3895. jqLiteRemoveClass(element, className);
  3896. });
  3897. async(done);
  3898. },
  3899. /**
  3900. *
  3901. * @ngdoc method
  3902. * @name $animate#setClass
  3903. * @kind function
  3904. * @description Adds and/or removes the given CSS classes to and from the element.
  3905. * Once complete, the done() callback will be fired (if provided).
  3906. * @param {DOMElement} element the element which will have its CSS classes changed
  3907. * removed from it
  3908. * @param {string} add the CSS classes which will be added to the element
  3909. * @param {string} remove the CSS class which will be removed from the element
  3910. * @param {Function=} done the callback function (if provided) that will be fired after the
  3911. * CSS classes have been set on the element
  3912. */
  3913. setClass : function(element, add, remove, done) {
  3914. forEach(element, function (element) {
  3915. jqLiteAddClass(element, add);
  3916. jqLiteRemoveClass(element, remove);
  3917. });
  3918. async(done);
  3919. },
  3920. enabled : noop
  3921. };
  3922. }];
  3923. }];
  3924. function $$AsyncCallbackProvider(){
  3925. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  3926. return $$rAF.supported
  3927. ? function(fn) { return $$rAF(fn); }
  3928. : function(fn) {
  3929. return $timeout(fn, 0, false);
  3930. };
  3931. }];
  3932. }
  3933. /* global stripHash: true */
  3934. /**
  3935. * ! This is a private undocumented service !
  3936. *
  3937. * @name $browser
  3938. * @requires $log
  3939. * @description
  3940. * This object has two goals:
  3941. *
  3942. * - hide all the global state in the browser caused by the window object
  3943. * - abstract away all the browser specific features and inconsistencies
  3944. *
  3945. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3946. * service, which can be used for convenient testing of the application without the interaction with
  3947. * the real browser apis.
  3948. */
  3949. /**
  3950. * @param {object} window The global window object.
  3951. * @param {object} document jQuery wrapped document.
  3952. * @param {function()} XHR XMLHttpRequest constructor.
  3953. * @param {object} $log console.log or an object with the same interface.
  3954. * @param {object} $sniffer $sniffer service
  3955. */
  3956. function Browser(window, document, $log, $sniffer) {
  3957. var self = this,
  3958. rawDocument = document[0],
  3959. location = window.location,
  3960. history = window.history,
  3961. setTimeout = window.setTimeout,
  3962. clearTimeout = window.clearTimeout,
  3963. pendingDeferIds = {};
  3964. self.isMock = false;
  3965. var outstandingRequestCount = 0;
  3966. var outstandingRequestCallbacks = [];
  3967. // TODO(vojta): remove this temporary api
  3968. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3969. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3970. /**
  3971. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3972. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3973. */
  3974. function completeOutstandingRequest(fn) {
  3975. try {
  3976. fn.apply(null, sliceArgs(arguments, 1));
  3977. } finally {
  3978. outstandingRequestCount--;
  3979. if (outstandingRequestCount === 0) {
  3980. while(outstandingRequestCallbacks.length) {
  3981. try {
  3982. outstandingRequestCallbacks.pop()();
  3983. } catch (e) {
  3984. $log.error(e);
  3985. }
  3986. }
  3987. }
  3988. }
  3989. }
  3990. function getHash(url) {
  3991. var index = url.indexOf('#');
  3992. return index === -1 ? '' : url.substr(index + 1);
  3993. }
  3994. /**
  3995. * @private
  3996. * Note: this method is used only by scenario runner
  3997. * TODO(vojta): prefix this method with $$ ?
  3998. * @param {function()} callback Function that will be called when no outstanding request
  3999. */
  4000. self.notifyWhenNoOutstandingRequests = function(callback) {
  4001. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4002. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4003. // regular poller would result in flaky tests.
  4004. forEach(pollFns, function(pollFn){ pollFn(); });
  4005. if (outstandingRequestCount === 0) {
  4006. callback();
  4007. } else {
  4008. outstandingRequestCallbacks.push(callback);
  4009. }
  4010. };
  4011. //////////////////////////////////////////////////////////////
  4012. // Poll Watcher API
  4013. //////////////////////////////////////////////////////////////
  4014. var pollFns = [],
  4015. pollTimeout;
  4016. /**
  4017. * @name $browser#addPollFn
  4018. *
  4019. * @param {function()} fn Poll function to add
  4020. *
  4021. * @description
  4022. * Adds a function to the list of functions that poller periodically executes,
  4023. * and starts polling if not started yet.
  4024. *
  4025. * @returns {function()} the added function
  4026. */
  4027. self.addPollFn = function(fn) {
  4028. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4029. pollFns.push(fn);
  4030. return fn;
  4031. };
  4032. /**
  4033. * @param {number} interval How often should browser call poll functions (ms)
  4034. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4035. *
  4036. * @description
  4037. * Configures the poller to run in the specified intervals, using the specified
  4038. * setTimeout fn and kicks it off.
  4039. */
  4040. function startPoller(interval, setTimeout) {
  4041. (function check() {
  4042. forEach(pollFns, function(pollFn){ pollFn(); });
  4043. pollTimeout = setTimeout(check, interval);
  4044. })();
  4045. }
  4046. //////////////////////////////////////////////////////////////
  4047. // URL API
  4048. //////////////////////////////////////////////////////////////
  4049. var lastBrowserUrl = location.href,
  4050. baseElement = document.find('base'),
  4051. reloadLocation = null;
  4052. /**
  4053. * @name $browser#url
  4054. *
  4055. * @description
  4056. * GETTER:
  4057. * Without any argument, this method just returns current value of location.href.
  4058. *
  4059. * SETTER:
  4060. * With at least one argument, this method sets url to new value.
  4061. * If html5 history api supported, pushState/replaceState is used, otherwise
  4062. * location.href/location.replace is used.
  4063. * Returns its own instance to allow chaining
  4064. *
  4065. * NOTE: this api is intended for use only by the $location service. Please use the
  4066. * {@link ng.$location $location service} to change url.
  4067. *
  4068. * @param {string} url New url (when used as setter)
  4069. * @param {boolean=} replace Should new url replace current history record ?
  4070. */
  4071. self.url = function(url, replace) {
  4072. // Android Browser BFCache causes location, history reference to become stale.
  4073. if (location !== window.location) location = window.location;
  4074. if (history !== window.history) history = window.history;
  4075. // setter
  4076. if (url) {
  4077. if (lastBrowserUrl == url) return;
  4078. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4079. lastBrowserUrl = url;
  4080. // Don't use history API if only the hash changed
  4081. // due to a bug in IE10/IE11 which leads
  4082. // to not firing a `hashchange` nor `popstate` event
  4083. // in some cases (see #9143).
  4084. if (!sameBase && $sniffer.history) {
  4085. if (replace) history.replaceState(null, '', url);
  4086. else {
  4087. history.pushState(null, '', url);
  4088. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  4089. baseElement.attr('href', baseElement.attr('href'));
  4090. }
  4091. } else {
  4092. if (!sameBase) {
  4093. reloadLocation = url;
  4094. }
  4095. if (replace) {
  4096. location.replace(url);
  4097. } else if (!sameBase) {
  4098. location.href = url;
  4099. } else {
  4100. location.hash = getHash(url);
  4101. }
  4102. }
  4103. return self;
  4104. // getter
  4105. } else {
  4106. // - reloadLocation is needed as browsers don't allow to read out
  4107. // the new location.href if a reload happened.
  4108. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4109. return reloadLocation || location.href.replace(/%27/g,"'");
  4110. }
  4111. };
  4112. var urlChangeListeners = [],
  4113. urlChangeInit = false;
  4114. function fireUrlChange() {
  4115. if (lastBrowserUrl == self.url()) return;
  4116. lastBrowserUrl = self.url();
  4117. forEach(urlChangeListeners, function(listener) {
  4118. listener(self.url());
  4119. });
  4120. }
  4121. /**
  4122. * @name $browser#onUrlChange
  4123. *
  4124. * @description
  4125. * Register callback function that will be called, when url changes.
  4126. *
  4127. * It's only called when the url is changed from outside of angular:
  4128. * - user types different url into address bar
  4129. * - user clicks on history (forward/back) button
  4130. * - user clicks on a link
  4131. *
  4132. * It's not called when url is changed by $browser.url() method
  4133. *
  4134. * The listener gets called with new url as parameter.
  4135. *
  4136. * NOTE: this api is intended for use only by the $location service. Please use the
  4137. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4138. *
  4139. * @param {function(string)} listener Listener function to be called when url changes.
  4140. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4141. */
  4142. self.onUrlChange = function(callback) {
  4143. // TODO(vojta): refactor to use node's syntax for events
  4144. if (!urlChangeInit) {
  4145. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4146. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4147. // changed by push/replaceState
  4148. // html5 history api - popstate event
  4149. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  4150. // hashchange event
  4151. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  4152. // polling
  4153. else self.addPollFn(fireUrlChange);
  4154. urlChangeInit = true;
  4155. }
  4156. urlChangeListeners.push(callback);
  4157. return callback;
  4158. };
  4159. /**
  4160. * Checks whether the url has changed outside of Angular.
  4161. * Needs to be exported to be able to check for changes that have been done in sync,
  4162. * as hashchange/popstate events fire in async.
  4163. */
  4164. self.$$checkUrlChange = fireUrlChange;
  4165. //////////////////////////////////////////////////////////////
  4166. // Misc API
  4167. //////////////////////////////////////////////////////////////
  4168. /**
  4169. * @name $browser#baseHref
  4170. *
  4171. * @description
  4172. * Returns current <base href>
  4173. * (always relative - without domain)
  4174. *
  4175. * @returns {string} The current base href
  4176. */
  4177. self.baseHref = function() {
  4178. var href = baseElement.attr('href');
  4179. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4180. };
  4181. //////////////////////////////////////////////////////////////
  4182. // Cookies API
  4183. //////////////////////////////////////////////////////////////
  4184. var lastCookies = {};
  4185. var lastCookieString = '';
  4186. var cookiePath = self.baseHref();
  4187. /**
  4188. * @name $browser#cookies
  4189. *
  4190. * @param {string=} name Cookie name
  4191. * @param {string=} value Cookie value
  4192. *
  4193. * @description
  4194. * The cookies method provides a 'private' low level access to browser cookies.
  4195. * It is not meant to be used directly, use the $cookie service instead.
  4196. *
  4197. * The return values vary depending on the arguments that the method was called with as follows:
  4198. *
  4199. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4200. * it
  4201. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4202. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4203. * way)
  4204. *
  4205. * @returns {Object} Hash of all cookies (if called without any parameter)
  4206. */
  4207. self.cookies = function(name, value) {
  4208. /* global escape: false, unescape: false */
  4209. var cookieLength, cookieArray, cookie, i, index;
  4210. if (name) {
  4211. if (value === undefined) {
  4212. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  4213. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4214. } else {
  4215. if (isString(value)) {
  4216. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  4217. ';path=' + cookiePath).length + 1;
  4218. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4219. // - 300 cookies
  4220. // - 20 cookies per unique domain
  4221. // - 4096 bytes per cookie
  4222. if (cookieLength > 4096) {
  4223. $log.warn("Cookie '"+ name +
  4224. "' possibly not set or overflowed because it was too large ("+
  4225. cookieLength + " > 4096 bytes)!");
  4226. }
  4227. }
  4228. }
  4229. } else {
  4230. if (rawDocument.cookie !== lastCookieString) {
  4231. lastCookieString = rawDocument.cookie;
  4232. cookieArray = lastCookieString.split("; ");
  4233. lastCookies = {};
  4234. for (i = 0; i < cookieArray.length; i++) {
  4235. cookie = cookieArray[i];
  4236. index = cookie.indexOf('=');
  4237. if (index > 0) { //ignore nameless cookies
  4238. name = unescape(cookie.substring(0, index));
  4239. // the first value that is seen for a cookie is the most
  4240. // specific one. values for the same cookie name that
  4241. // follow are for less specific paths.
  4242. if (lastCookies[name] === undefined) {
  4243. lastCookies[name] = unescape(cookie.substring(index + 1));
  4244. }
  4245. }
  4246. }
  4247. }
  4248. return lastCookies;
  4249. }
  4250. };
  4251. /**
  4252. * @name $browser#defer
  4253. * @param {function()} fn A function, who's execution should be deferred.
  4254. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4255. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4256. *
  4257. * @description
  4258. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4259. *
  4260. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4261. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4262. * via `$browser.defer.flush()`.
  4263. *
  4264. */
  4265. self.defer = function(fn, delay) {
  4266. var timeoutId;
  4267. outstandingRequestCount++;
  4268. timeoutId = setTimeout(function() {
  4269. delete pendingDeferIds[timeoutId];
  4270. completeOutstandingRequest(fn);
  4271. }, delay || 0);
  4272. pendingDeferIds[timeoutId] = true;
  4273. return timeoutId;
  4274. };
  4275. /**
  4276. * @name $browser#defer.cancel
  4277. *
  4278. * @description
  4279. * Cancels a deferred task identified with `deferId`.
  4280. *
  4281. * @param {*} deferId Token returned by the `$browser.defer` function.
  4282. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4283. * canceled.
  4284. */
  4285. self.defer.cancel = function(deferId) {
  4286. if (pendingDeferIds[deferId]) {
  4287. delete pendingDeferIds[deferId];
  4288. clearTimeout(deferId);
  4289. completeOutstandingRequest(noop);
  4290. return true;
  4291. }
  4292. return false;
  4293. };
  4294. }
  4295. function $BrowserProvider(){
  4296. this.$get = ['$window', '$log', '$sniffer', '$document',
  4297. function( $window, $log, $sniffer, $document){
  4298. return new Browser($window, $document, $log, $sniffer);
  4299. }];
  4300. }
  4301. /**
  4302. * @ngdoc service
  4303. * @name $cacheFactory
  4304. *
  4305. * @description
  4306. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4307. * them.
  4308. *
  4309. * ```js
  4310. *
  4311. * var cache = $cacheFactory('cacheId');
  4312. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4313. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4314. *
  4315. * cache.put("key", "value");
  4316. * cache.put("another key", "another value");
  4317. *
  4318. * // We've specified no options on creation
  4319. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4320. *
  4321. * ```
  4322. *
  4323. *
  4324. * @param {string} cacheId Name or id of the newly created cache.
  4325. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4326. *
  4327. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4328. *
  4329. * @returns {object} Newly created cache object with the following set of methods:
  4330. *
  4331. * - `{object}` `info()` — Returns id, size, and options of cache.
  4332. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4333. * it.
  4334. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4335. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4336. * - `{void}` `removeAll()` — Removes all cached values.
  4337. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4338. *
  4339. * @example
  4340. <example module="cacheExampleApp">
  4341. <file name="index.html">
  4342. <div ng-controller="CacheController">
  4343. <input ng-model="newCacheKey" placeholder="Key">
  4344. <input ng-model="newCacheValue" placeholder="Value">
  4345. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4346. <p ng-if="keys.length">Cached Values</p>
  4347. <div ng-repeat="key in keys">
  4348. <span ng-bind="key"></span>
  4349. <span>: </span>
  4350. <b ng-bind="cache.get(key)"></b>
  4351. </div>
  4352. <p>Cache Info</p>
  4353. <div ng-repeat="(key, value) in cache.info()">
  4354. <span ng-bind="key"></span>
  4355. <span>: </span>
  4356. <b ng-bind="value"></b>
  4357. </div>
  4358. </div>
  4359. </file>
  4360. <file name="script.js">
  4361. angular.module('cacheExampleApp', []).
  4362. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4363. $scope.keys = [];
  4364. $scope.cache = $cacheFactory('cacheId');
  4365. $scope.put = function(key, value) {
  4366. if ($scope.cache.get(key) === undefined) {
  4367. $scope.keys.push(key);
  4368. }
  4369. $scope.cache.put(key, value === undefined ? null : value);
  4370. };
  4371. }]);
  4372. </file>
  4373. <file name="style.css">
  4374. p {
  4375. margin: 10px 0 3px;
  4376. }
  4377. </file>
  4378. </example>
  4379. */
  4380. function $CacheFactoryProvider() {
  4381. this.$get = function() {
  4382. var caches = {};
  4383. function cacheFactory(cacheId, options) {
  4384. if (cacheId in caches) {
  4385. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4386. }
  4387. var size = 0,
  4388. stats = extend({}, options, {id: cacheId}),
  4389. data = {},
  4390. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4391. lruHash = {},
  4392. freshEnd = null,
  4393. staleEnd = null;
  4394. /**
  4395. * @ngdoc type
  4396. * @name $cacheFactory.Cache
  4397. *
  4398. * @description
  4399. * A cache object used to store and retrieve data, primarily used by
  4400. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4401. * templates and other data.
  4402. *
  4403. * ```js
  4404. * angular.module('superCache')
  4405. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4406. * return $cacheFactory('super-cache');
  4407. * }]);
  4408. * ```
  4409. *
  4410. * Example test:
  4411. *
  4412. * ```js
  4413. * it('should behave like a cache', inject(function(superCache) {
  4414. * superCache.put('key', 'value');
  4415. * superCache.put('another key', 'another value');
  4416. *
  4417. * expect(superCache.info()).toEqual({
  4418. * id: 'super-cache',
  4419. * size: 2
  4420. * });
  4421. *
  4422. * superCache.remove('another key');
  4423. * expect(superCache.get('another key')).toBeUndefined();
  4424. *
  4425. * superCache.removeAll();
  4426. * expect(superCache.info()).toEqual({
  4427. * id: 'super-cache',
  4428. * size: 0
  4429. * });
  4430. * }));
  4431. * ```
  4432. */
  4433. return caches[cacheId] = {
  4434. /**
  4435. * @ngdoc method
  4436. * @name $cacheFactory.Cache#put
  4437. * @kind function
  4438. *
  4439. * @description
  4440. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4441. * retrieved later, and incrementing the size of the cache if the key was not already
  4442. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4443. * entries from the set.
  4444. *
  4445. * It will not insert undefined values into the cache.
  4446. *
  4447. * @param {string} key the key under which the cached data is stored.
  4448. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4449. * will not be stored.
  4450. * @returns {*} the value stored.
  4451. */
  4452. put: function(key, value) {
  4453. if (capacity < Number.MAX_VALUE) {
  4454. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4455. refresh(lruEntry);
  4456. }
  4457. if (isUndefined(value)) return;
  4458. if (!(key in data)) size++;
  4459. data[key] = value;
  4460. if (size > capacity) {
  4461. this.remove(staleEnd.key);
  4462. }
  4463. return value;
  4464. },
  4465. /**
  4466. * @ngdoc method
  4467. * @name $cacheFactory.Cache#get
  4468. * @kind function
  4469. *
  4470. * @description
  4471. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4472. *
  4473. * @param {string} key the key of the data to be retrieved
  4474. * @returns {*} the value stored.
  4475. */
  4476. get: function(key) {
  4477. if (capacity < Number.MAX_VALUE) {
  4478. var lruEntry = lruHash[key];
  4479. if (!lruEntry) return;
  4480. refresh(lruEntry);
  4481. }
  4482. return data[key];
  4483. },
  4484. /**
  4485. * @ngdoc method
  4486. * @name $cacheFactory.Cache#remove
  4487. * @kind function
  4488. *
  4489. * @description
  4490. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4491. *
  4492. * @param {string} key the key of the entry to be removed
  4493. */
  4494. remove: function(key) {
  4495. if (capacity < Number.MAX_VALUE) {
  4496. var lruEntry = lruHash[key];
  4497. if (!lruEntry) return;
  4498. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4499. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4500. link(lruEntry.n,lruEntry.p);
  4501. delete lruHash[key];
  4502. }
  4503. delete data[key];
  4504. size--;
  4505. },
  4506. /**
  4507. * @ngdoc method
  4508. * @name $cacheFactory.Cache#removeAll
  4509. * @kind function
  4510. *
  4511. * @description
  4512. * Clears the cache object of any entries.
  4513. */
  4514. removeAll: function() {
  4515. data = {};
  4516. size = 0;
  4517. lruHash = {};
  4518. freshEnd = staleEnd = null;
  4519. },
  4520. /**
  4521. * @ngdoc method
  4522. * @name $cacheFactory.Cache#destroy
  4523. * @kind function
  4524. *
  4525. * @description
  4526. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4527. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4528. */
  4529. destroy: function() {
  4530. data = null;
  4531. stats = null;
  4532. lruHash = null;
  4533. delete caches[cacheId];
  4534. },
  4535. /**
  4536. * @ngdoc method
  4537. * @name $cacheFactory.Cache#info
  4538. * @kind function
  4539. *
  4540. * @description
  4541. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4542. *
  4543. * @returns {object} an object with the following properties:
  4544. * <ul>
  4545. * <li>**id**: the id of the cache instance</li>
  4546. * <li>**size**: the number of entries kept in the cache instance</li>
  4547. * <li>**...**: any additional properties from the options object when creating the
  4548. * cache.</li>
  4549. * </ul>
  4550. */
  4551. info: function() {
  4552. return extend({}, stats, {size: size});
  4553. }
  4554. };
  4555. /**
  4556. * makes the `entry` the freshEnd of the LRU linked list
  4557. */
  4558. function refresh(entry) {
  4559. if (entry != freshEnd) {
  4560. if (!staleEnd) {
  4561. staleEnd = entry;
  4562. } else if (staleEnd == entry) {
  4563. staleEnd = entry.n;
  4564. }
  4565. link(entry.n, entry.p);
  4566. link(entry, freshEnd);
  4567. freshEnd = entry;
  4568. freshEnd.n = null;
  4569. }
  4570. }
  4571. /**
  4572. * bidirectionally links two entries of the LRU linked list
  4573. */
  4574. function link(nextEntry, prevEntry) {
  4575. if (nextEntry != prevEntry) {
  4576. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4577. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4578. }
  4579. }
  4580. }
  4581. /**
  4582. * @ngdoc method
  4583. * @name $cacheFactory#info
  4584. *
  4585. * @description
  4586. * Get information about all the caches that have been created
  4587. *
  4588. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4589. */
  4590. cacheFactory.info = function() {
  4591. var info = {};
  4592. forEach(caches, function(cache, cacheId) {
  4593. info[cacheId] = cache.info();
  4594. });
  4595. return info;
  4596. };
  4597. /**
  4598. * @ngdoc method
  4599. * @name $cacheFactory#get
  4600. *
  4601. * @description
  4602. * Get access to a cache object by the `cacheId` used when it was created.
  4603. *
  4604. * @param {string} cacheId Name or id of a cache to access.
  4605. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4606. */
  4607. cacheFactory.get = function(cacheId) {
  4608. return caches[cacheId];
  4609. };
  4610. return cacheFactory;
  4611. };
  4612. }
  4613. /**
  4614. * @ngdoc service
  4615. * @name $templateCache
  4616. *
  4617. * @description
  4618. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4619. * can load templates directly into the cache in a `script` tag, or by consuming the
  4620. * `$templateCache` service directly.
  4621. *
  4622. * Adding via the `script` tag:
  4623. *
  4624. * ```html
  4625. * <script type="text/ng-template" id="templateId.html">
  4626. * <p>This is the content of the template</p>
  4627. * </script>
  4628. * ```
  4629. *
  4630. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4631. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  4632. * element with ng-app attribute), otherwise the template will be ignored.
  4633. *
  4634. * Adding via the $templateCache service:
  4635. *
  4636. * ```js
  4637. * var myApp = angular.module('myApp', []);
  4638. * myApp.run(function($templateCache) {
  4639. * $templateCache.put('templateId.html', 'This is the content of the template');
  4640. * });
  4641. * ```
  4642. *
  4643. * To retrieve the template later, simply use it in your HTML:
  4644. * ```html
  4645. * <div ng-include=" 'templateId.html' "></div>
  4646. * ```
  4647. *
  4648. * or get it via Javascript:
  4649. * ```js
  4650. * $templateCache.get('templateId.html')
  4651. * ```
  4652. *
  4653. * See {@link ng.$cacheFactory $cacheFactory}.
  4654. *
  4655. */
  4656. function $TemplateCacheProvider() {
  4657. this.$get = ['$cacheFactory', function($cacheFactory) {
  4658. return $cacheFactory('templates');
  4659. }];
  4660. }
  4661. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4662. *
  4663. * DOM-related variables:
  4664. *
  4665. * - "node" - DOM Node
  4666. * - "element" - DOM Element or Node
  4667. * - "$node" or "$element" - jqLite-wrapped node or element
  4668. *
  4669. *
  4670. * Compiler related stuff:
  4671. *
  4672. * - "linkFn" - linking fn of a single directive
  4673. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4674. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4675. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4676. */
  4677. /**
  4678. * @ngdoc service
  4679. * @name $compile
  4680. * @kind function
  4681. *
  4682. * @description
  4683. * Compiles an HTML string or DOM into a template and produces a template function, which
  4684. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4685. *
  4686. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4687. * {@link ng.$compileProvider#directive directives}.
  4688. *
  4689. * <div class="alert alert-warning">
  4690. * **Note:** This document is an in-depth reference of all directive options.
  4691. * For a gentle introduction to directives with examples of common use cases,
  4692. * see the {@link guide/directive directive guide}.
  4693. * </div>
  4694. *
  4695. * ## Comprehensive Directive API
  4696. *
  4697. * There are many different options for a directive.
  4698. *
  4699. * The difference resides in the return value of the factory function.
  4700. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4701. * or just the `postLink` function (all other properties will have the default values).
  4702. *
  4703. * <div class="alert alert-success">
  4704. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4705. * </div>
  4706. *
  4707. * Here's an example directive declared with a Directive Definition Object:
  4708. *
  4709. * ```js
  4710. * var myModule = angular.module(...);
  4711. *
  4712. * myModule.directive('directiveName', function factory(injectables) {
  4713. * var directiveDefinitionObject = {
  4714. * priority: 0,
  4715. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4716. * // or
  4717. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4718. * transclude: false,
  4719. * restrict: 'A',
  4720. * scope: false,
  4721. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4722. * controllerAs: 'stringAlias',
  4723. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4724. * compile: function compile(tElement, tAttrs, transclude) {
  4725. * return {
  4726. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4727. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4728. * }
  4729. * // or
  4730. * // return function postLink( ... ) { ... }
  4731. * },
  4732. * // or
  4733. * // link: {
  4734. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4735. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4736. * // }
  4737. * // or
  4738. * // link: function postLink( ... ) { ... }
  4739. * };
  4740. * return directiveDefinitionObject;
  4741. * });
  4742. * ```
  4743. *
  4744. * <div class="alert alert-warning">
  4745. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4746. * </div>
  4747. *
  4748. * Therefore the above can be simplified as:
  4749. *
  4750. * ```js
  4751. * var myModule = angular.module(...);
  4752. *
  4753. * myModule.directive('directiveName', function factory(injectables) {
  4754. * var directiveDefinitionObject = {
  4755. * link: function postLink(scope, iElement, iAttrs) { ... }
  4756. * };
  4757. * return directiveDefinitionObject;
  4758. * // or
  4759. * // return function postLink(scope, iElement, iAttrs) { ... }
  4760. * });
  4761. * ```
  4762. *
  4763. *
  4764. *
  4765. * ### Directive Definition Object
  4766. *
  4767. * The directive definition object provides instructions to the {@link ng.$compile
  4768. * compiler}. The attributes are:
  4769. *
  4770. * #### `priority`
  4771. * When there are multiple directives defined on a single DOM element, sometimes it
  4772. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4773. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4774. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4775. * are also run in priority order, but post-link functions are run in reverse order. The order
  4776. * of directives with the same priority is undefined. The default priority is `0`.
  4777. *
  4778. * #### `terminal`
  4779. * If set to true then the current `priority` will be the last set of directives
  4780. * which will execute (any directives at the current priority will still execute
  4781. * as the order of execution on same `priority` is undefined).
  4782. *
  4783. * #### `scope`
  4784. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4785. * same element request a new scope, only one new scope is created. The new scope rule does not
  4786. * apply for the root of the template since the root of the template always gets a new scope.
  4787. *
  4788. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4789. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4790. * when creating reusable components, which should not accidentally read or modify data in the
  4791. * parent scope.
  4792. *
  4793. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4794. * derived from the parent scope. These local properties are useful for aliasing values for
  4795. * templates. Locals definition is a hash of local scope property to its source:
  4796. *
  4797. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4798. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4799. * attribute name is assumed to be the same as the local name.
  4800. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4801. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4802. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4803. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4804. * component scope).
  4805. *
  4806. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4807. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4808. * name is specified then the attribute name is assumed to be the same as the local name.
  4809. * Given `<widget my-attr="parentModel">` and widget definition of
  4810. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4811. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4812. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4813. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4814. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4815. *
  4816. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4817. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4818. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4819. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4820. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4821. * pass data from the isolated scope via an expression to the parent scope, this can be
  4822. * done by passing a map of local variable names and values into the expression wrapper fn.
  4823. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4824. * by calling the `localFn` as `localFn({amount: 22})`.
  4825. *
  4826. *
  4827. *
  4828. * #### `controller`
  4829. * Controller constructor function. The controller is instantiated before the
  4830. * pre-linking phase and it is shared with other directives (see
  4831. * `require` attribute). This allows the directives to communicate with each other and augment
  4832. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4833. *
  4834. * * `$scope` - Current scope associated with the element
  4835. * * `$element` - Current element
  4836. * * `$attrs` - Current attributes object for the element
  4837. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4838. * The scope can be overridden by an optional first argument.
  4839. * `function([scope], cloneLinkingFn)`.
  4840. *
  4841. *
  4842. * #### `require`
  4843. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4844. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4845. * injected argument will be an array in corresponding order. If no such directive can be
  4846. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4847. *
  4848. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4849. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4850. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  4851. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  4852. * `null` to the `link` fn if not found.
  4853. *
  4854. *
  4855. * #### `controllerAs`
  4856. * Controller alias at the directive scope. An alias for the controller so it
  4857. * can be referenced at the directive template. The directive needs to define a scope for this
  4858. * configuration to be used. Useful in the case when directive is used as component.
  4859. *
  4860. *
  4861. * #### `restrict`
  4862. * String of subset of `EACM` which restricts the directive to a specific directive
  4863. * declaration style. If omitted, the default (attributes only) is used.
  4864. *
  4865. * * `E` - Element name: `<my-directive></my-directive>`
  4866. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4867. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4868. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4869. *
  4870. *
  4871. * #### `template`
  4872. * HTML markup that may:
  4873. * * Replace the contents of the directive's element (default).
  4874. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  4875. * * Wrap the contents of the directive's element (if `transclude` is true).
  4876. *
  4877. * Value may be:
  4878. *
  4879. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  4880. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  4881. * function api below) and returns a string value.
  4882. *
  4883. *
  4884. * #### `templateUrl`
  4885. * Same as `template` but the template is loaded from the specified URL. Because
  4886. * the template loading is asynchronous the compilation/linking is suspended until the template
  4887. * is loaded.
  4888. *
  4889. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4890. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4891. * a string value representing the url. In either case, the template URL is passed through {@link
  4892. * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4893. *
  4894. *
  4895. * #### `replace` ([*DEPRECATED*!], will be removed in next major release)
  4896. * specify what the template should replace. Defaults to `false`.
  4897. *
  4898. * * `true` - the template will replace the directive's element.
  4899. * * `false` - the template will replace the contents of the directive's element.
  4900. *
  4901. * The replacement process migrates all of the attributes / classes from the old element to the new
  4902. * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4903. * Directives Guide} for an example.
  4904. *
  4905. * #### `transclude`
  4906. * compile the content of the element and make it available to the directive.
  4907. * Typically used with {@link ng.directive:ngTransclude
  4908. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4909. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4910. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4911. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4912. * be bound to the parent (pre-`isolate`) scope.
  4913. *
  4914. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  4915. * directive's element or the entire element:
  4916. *
  4917. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  4918. * * `'element'` - transclude the whole of the directive's element including any directives on this
  4919. * element that defined at a lower priority than this directive. When used, the `template`
  4920. * property is ignored.
  4921. *
  4922. * <div class="alert alert-warning">
  4923. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  4924. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  4925. * Testing Transclusion Directives}.
  4926. * </div>
  4927. *
  4928. * #### `compile`
  4929. *
  4930. * ```js
  4931. * function compile(tElement, tAttrs, transclude) { ... }
  4932. * ```
  4933. *
  4934. * The compile function deals with transforming the template DOM. Since most directives do not do
  4935. * template transformation, it is not used often. The compile function takes the following arguments:
  4936. *
  4937. * * `tElement` - template element - The element where the directive has been declared. It is
  4938. * safe to do template transformation on the element and child elements only.
  4939. *
  4940. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4941. * between all directive compile functions.
  4942. *
  4943. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4944. *
  4945. * <div class="alert alert-warning">
  4946. * **Note:** The template instance and the link instance may be different objects if the template has
  4947. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4948. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4949. * should be done in a linking function rather than in a compile function.
  4950. * </div>
  4951. * <div class="alert alert-warning">
  4952. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  4953. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  4954. * stack overflow errors.
  4955. *
  4956. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  4957. * a directive's template instead of relying on automatic template compilation via `template` or
  4958. * `templateUrl` declaration or manual compilation inside the compile function.
  4959. * </div>
  4960. *
  4961. * <div class="alert alert-error">
  4962. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4963. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4964. * to the link function instead.
  4965. * </div>
  4966. * A compile function can have a return value which can be either a function or an object.
  4967. *
  4968. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4969. * `link` property of the config object when the compile function is empty.
  4970. *
  4971. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4972. * control when a linking function should be called during the linking phase. See info about
  4973. * pre-linking and post-linking functions below.
  4974. *
  4975. *
  4976. * #### `link`
  4977. * This property is used only if the `compile` property is not defined.
  4978. *
  4979. * ```js
  4980. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4981. * ```
  4982. *
  4983. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4984. * executed after the template has been cloned. This is where most of the directive logic will be
  4985. * put.
  4986. *
  4987. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  4988. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  4989. *
  4990. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4991. * manipulate the children of the element only in `postLink` function since the children have
  4992. * already been linked.
  4993. *
  4994. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4995. * between all directive linking functions.
  4996. *
  4997. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4998. * element defines a controller. The controller is shared among all the directives, which allows
  4999. * the directives to use the controllers as a communication channel.
  5000. *
  5001. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5002. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  5003. * parameter of directive controllers.
  5004. * `function([scope], cloneLinkingFn)`.
  5005. *
  5006. *
  5007. * #### Pre-linking function
  5008. *
  5009. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5010. * compiler linking function will fail to locate the correct elements for linking.
  5011. *
  5012. * #### Post-linking function
  5013. *
  5014. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  5015. *
  5016. * <a name="Attributes"></a>
  5017. * ### Attributes
  5018. *
  5019. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5020. * `link()` or `compile()` functions. It has a variety of uses.
  5021. *
  5022. * accessing *Normalized attribute names:*
  5023. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5024. * the attributes object allows for normalized access to
  5025. * the attributes.
  5026. *
  5027. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5028. * object which allows the directives to use the attributes object as inter directive
  5029. * communication.
  5030. *
  5031. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5032. * allowing other directives to read the interpolated value.
  5033. *
  5034. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5035. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5036. * the only way to easily get the actual value because during the linking phase the interpolation
  5037. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5038. *
  5039. * ```js
  5040. * function linkingFn(scope, elm, attrs, ctrl) {
  5041. * // get the attribute value
  5042. * console.log(attrs.ngModel);
  5043. *
  5044. * // change the attribute
  5045. * attrs.$set('ngModel', 'new value');
  5046. *
  5047. * // observe changes to interpolated attribute
  5048. * attrs.$observe('ngModel', function(value) {
  5049. * console.log('ngModel has changed value to ' + value);
  5050. * });
  5051. * }
  5052. * ```
  5053. *
  5054. * ## Example
  5055. *
  5056. * <div class="alert alert-warning">
  5057. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5058. * to illustrate how `$compile` works.
  5059. * </div>
  5060. *
  5061. <example module="compileExample">
  5062. <file name="index.html">
  5063. <script>
  5064. angular.module('compileExample', [], function($compileProvider) {
  5065. // configure new 'compile' directive by passing a directive
  5066. // factory function. The factory function injects the '$compile'
  5067. $compileProvider.directive('compile', function($compile) {
  5068. // directive factory creates a link function
  5069. return function(scope, element, attrs) {
  5070. scope.$watch(
  5071. function(scope) {
  5072. // watch the 'compile' expression for changes
  5073. return scope.$eval(attrs.compile);
  5074. },
  5075. function(value) {
  5076. // when the 'compile' expression changes
  5077. // assign it into the current DOM
  5078. element.html(value);
  5079. // compile the new DOM and link it to the current
  5080. // scope.
  5081. // NOTE: we only compile .childNodes so that
  5082. // we don't get into infinite loop compiling ourselves
  5083. $compile(element.contents())(scope);
  5084. }
  5085. );
  5086. };
  5087. });
  5088. })
  5089. .controller('GreeterController', ['$scope', function($scope) {
  5090. $scope.name = 'Angular';
  5091. $scope.html = 'Hello {{name}}';
  5092. }]);
  5093. </script>
  5094. <div ng-controller="GreeterController">
  5095. <input ng-model="name"> <br>
  5096. <textarea ng-model="html"></textarea> <br>
  5097. <div compile="html"></div>
  5098. </div>
  5099. </file>
  5100. <file name="protractor.js" type="protractor">
  5101. it('should auto compile', function() {
  5102. var textarea = $('textarea');
  5103. var output = $('div[compile]');
  5104. // The initial state reads 'Hello Angular'.
  5105. expect(output.getText()).toBe('Hello Angular');
  5106. textarea.clear();
  5107. textarea.sendKeys('{{name}}!');
  5108. expect(output.getText()).toBe('Angular!');
  5109. });
  5110. </file>
  5111. </example>
  5112. *
  5113. *
  5114. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5115. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  5116. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5117. * root element(s), not their children)
  5118. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  5119. * (a DOM element/tree) to a scope. Where:
  5120. *
  5121. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5122. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5123. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5124. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5125. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5126. *
  5127. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5128. * * `scope` - is the current scope with which the linking function is working with.
  5129. *
  5130. * Calling the linking function returns the element of the template. It is either the original
  5131. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5132. *
  5133. * After linking the view is not updated until after a call to $digest which typically is done by
  5134. * Angular automatically.
  5135. *
  5136. * If you need access to the bound view, there are two ways to do it:
  5137. *
  5138. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5139. * before you send them to the compiler and keep this reference around.
  5140. * ```js
  5141. * var element = $compile('<p>{{total}}</p>')(scope);
  5142. * ```
  5143. *
  5144. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5145. * example would not point to the clone, but rather to the original template that was cloned. In
  5146. * this case, you can access the clone via the cloneAttachFn:
  5147. * ```js
  5148. * var templateElement = angular.element('<p>{{total}}</p>'),
  5149. * scope = ....;
  5150. *
  5151. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5152. * //attach the clone to DOM document at the right place
  5153. * });
  5154. *
  5155. * //now we have reference to the cloned DOM via `clonedElement`
  5156. * ```
  5157. *
  5158. *
  5159. * For information on how the compiler works, see the
  5160. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5161. */
  5162. var $compileMinErr = minErr('$compile');
  5163. /**
  5164. * @ngdoc provider
  5165. * @name $compileProvider
  5166. * @kind function
  5167. *
  5168. * @description
  5169. */
  5170. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5171. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5172. var hasDirectives = {},
  5173. Suffix = 'Directive',
  5174. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
  5175. CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/;
  5176. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5177. // The assumption is that future DOM event attribute names will begin with
  5178. // 'on' and be composed of only English letters.
  5179. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5180. /**
  5181. * @ngdoc method
  5182. * @name $compileProvider#directive
  5183. * @kind function
  5184. *
  5185. * @description
  5186. * Register a new directive with the compiler.
  5187. *
  5188. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5189. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5190. * names and the values are the factories.
  5191. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5192. * {@link guide/directive} for more info.
  5193. * @returns {ng.$compileProvider} Self for chaining.
  5194. */
  5195. this.directive = function registerDirective(name, directiveFactory) {
  5196. assertNotHasOwnProperty(name, 'directive');
  5197. if (isString(name)) {
  5198. assertArg(directiveFactory, 'directiveFactory');
  5199. if (!hasDirectives.hasOwnProperty(name)) {
  5200. hasDirectives[name] = [];
  5201. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5202. function($injector, $exceptionHandler) {
  5203. var directives = [];
  5204. forEach(hasDirectives[name], function(directiveFactory, index) {
  5205. try {
  5206. var directive = $injector.invoke(directiveFactory);
  5207. if (isFunction(directive)) {
  5208. directive = { compile: valueFn(directive) };
  5209. } else if (!directive.compile && directive.link) {
  5210. directive.compile = valueFn(directive.link);
  5211. }
  5212. directive.priority = directive.priority || 0;
  5213. directive.index = index;
  5214. directive.name = directive.name || name;
  5215. directive.require = directive.require || (directive.controller && directive.name);
  5216. directive.restrict = directive.restrict || 'A';
  5217. directives.push(directive);
  5218. } catch (e) {
  5219. $exceptionHandler(e);
  5220. }
  5221. });
  5222. return directives;
  5223. }]);
  5224. }
  5225. hasDirectives[name].push(directiveFactory);
  5226. } else {
  5227. forEach(name, reverseParams(registerDirective));
  5228. }
  5229. return this;
  5230. };
  5231. /**
  5232. * @ngdoc method
  5233. * @name $compileProvider#aHrefSanitizationWhitelist
  5234. * @kind function
  5235. *
  5236. * @description
  5237. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5238. * urls during a[href] sanitization.
  5239. *
  5240. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5241. *
  5242. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5243. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5244. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5245. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5246. *
  5247. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5248. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5249. * chaining otherwise.
  5250. */
  5251. this.aHrefSanitizationWhitelist = function(regexp) {
  5252. if (isDefined(regexp)) {
  5253. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5254. return this;
  5255. } else {
  5256. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5257. }
  5258. };
  5259. /**
  5260. * @ngdoc method
  5261. * @name $compileProvider#imgSrcSanitizationWhitelist
  5262. * @kind function
  5263. *
  5264. * @description
  5265. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5266. * urls during img[src] sanitization.
  5267. *
  5268. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5269. *
  5270. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5271. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5272. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5273. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5274. *
  5275. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5276. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5277. * chaining otherwise.
  5278. */
  5279. this.imgSrcSanitizationWhitelist = function(regexp) {
  5280. if (isDefined(regexp)) {
  5281. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5282. return this;
  5283. } else {
  5284. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5285. }
  5286. };
  5287. this.$get = [
  5288. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  5289. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5290. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  5291. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5292. var Attributes = function(element, attr) {
  5293. this.$$element = element;
  5294. this.$attr = attr || {};
  5295. };
  5296. Attributes.prototype = {
  5297. /**
  5298. * @ngdoc method
  5299. * @name $compile.directive.Attributes#$normalize
  5300. * @kind function
  5301. *
  5302. * @description
  5303. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  5304. * `data-`) to its normalized, camelCase form.
  5305. *
  5306. * Also there is special case for Moz prefix starting with upper case letter.
  5307. *
  5308. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  5309. *
  5310. * @param {string} name Name to normalize
  5311. */
  5312. $normalize: directiveNormalize,
  5313. /**
  5314. * @ngdoc method
  5315. * @name $compile.directive.Attributes#$addClass
  5316. * @kind function
  5317. *
  5318. * @description
  5319. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5320. * are enabled then an animation will be triggered for the class addition.
  5321. *
  5322. * @param {string} classVal The className value that will be added to the element
  5323. */
  5324. $addClass : function(classVal) {
  5325. if(classVal && classVal.length > 0) {
  5326. $animate.addClass(this.$$element, classVal);
  5327. }
  5328. },
  5329. /**
  5330. * @ngdoc method
  5331. * @name $compile.directive.Attributes#$removeClass
  5332. * @kind function
  5333. *
  5334. * @description
  5335. * Removes the CSS class value specified by the classVal parameter from the element. If
  5336. * animations are enabled then an animation will be triggered for the class removal.
  5337. *
  5338. * @param {string} classVal The className value that will be removed from the element
  5339. */
  5340. $removeClass : function(classVal) {
  5341. if(classVal && classVal.length > 0) {
  5342. $animate.removeClass(this.$$element, classVal);
  5343. }
  5344. },
  5345. /**
  5346. * @ngdoc method
  5347. * @name $compile.directive.Attributes#$updateClass
  5348. * @kind function
  5349. *
  5350. * @description
  5351. * Adds and removes the appropriate CSS class values to the element based on the difference
  5352. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5353. *
  5354. * @param {string} newClasses The current CSS className value
  5355. * @param {string} oldClasses The former CSS className value
  5356. */
  5357. $updateClass : function(newClasses, oldClasses) {
  5358. var toAdd = tokenDifference(newClasses, oldClasses);
  5359. var toRemove = tokenDifference(oldClasses, newClasses);
  5360. if(toAdd.length === 0) {
  5361. $animate.removeClass(this.$$element, toRemove);
  5362. } else if(toRemove.length === 0) {
  5363. $animate.addClass(this.$$element, toAdd);
  5364. } else {
  5365. $animate.setClass(this.$$element, toAdd, toRemove);
  5366. }
  5367. },
  5368. /**
  5369. * Set a normalized attribute on the element in a way such that all directives
  5370. * can share the attribute. This function properly handles boolean attributes.
  5371. * @param {string} key Normalized key. (ie ngAttribute)
  5372. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5373. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5374. * Defaults to true.
  5375. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5376. */
  5377. $set: function(key, value, writeAttr, attrName) {
  5378. // TODO: decide whether or not to throw an error if "class"
  5379. //is set through this function since it may cause $updateClass to
  5380. //become unstable.
  5381. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5382. normalizedVal,
  5383. nodeName;
  5384. if (booleanKey) {
  5385. this.$$element.prop(key, value);
  5386. attrName = booleanKey;
  5387. }
  5388. this[key] = value;
  5389. // translate normalized key to actual key
  5390. if (attrName) {
  5391. this.$attr[key] = attrName;
  5392. } else {
  5393. attrName = this.$attr[key];
  5394. if (!attrName) {
  5395. this.$attr[key] = attrName = snake_case(key, '-');
  5396. }
  5397. }
  5398. // SVG elements' `nodeName` can be lowercase
  5399. nodeName = nodeName_(this.$$element).toUpperCase();
  5400. // sanitize a[href] and img[src] values
  5401. if ((nodeName === 'A' && (key === 'href' || key === 'xlinkHref')) ||
  5402. (nodeName === 'IMG' && key === 'src')) {
  5403. this[key] = value = $$sanitizeUri(value, key === 'src');
  5404. }
  5405. if (writeAttr !== false) {
  5406. if (value === null || value === undefined) {
  5407. this.$$element.removeAttr(attrName);
  5408. } else {
  5409. this.$$element.attr(attrName, value);
  5410. }
  5411. }
  5412. // fire observers
  5413. var $$observers = this.$$observers;
  5414. $$observers && forEach($$observers[key], function(fn) {
  5415. try {
  5416. fn(value);
  5417. } catch (e) {
  5418. $exceptionHandler(e);
  5419. }
  5420. });
  5421. },
  5422. /**
  5423. * @ngdoc method
  5424. * @name $compile.directive.Attributes#$observe
  5425. * @kind function
  5426. *
  5427. * @description
  5428. * Observes an interpolated attribute.
  5429. *
  5430. * The observer function will be invoked once during the next `$digest` following
  5431. * compilation. The observer is then invoked whenever the interpolated value
  5432. * changes.
  5433. *
  5434. * @param {string} key Normalized key. (ie ngAttribute) .
  5435. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5436. the interpolated value of the attribute changes.
  5437. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5438. * @returns {function()} the `fn` parameter.
  5439. */
  5440. $observe: function(key, fn) {
  5441. var attrs = this,
  5442. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5443. listeners = ($$observers[key] || ($$observers[key] = []));
  5444. listeners.push(fn);
  5445. $rootScope.$evalAsync(function() {
  5446. if (!listeners.$$inter) {
  5447. // no one registered attribute interpolation function, so lets call it manually
  5448. fn(attrs[key]);
  5449. }
  5450. });
  5451. return fn;
  5452. }
  5453. };
  5454. var startSymbol = $interpolate.startSymbol(),
  5455. endSymbol = $interpolate.endSymbol(),
  5456. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5457. ? identity
  5458. : function denormalizeTemplate(template) {
  5459. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5460. },
  5461. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5462. return compile;
  5463. //================================
  5464. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5465. previousCompileContext) {
  5466. if (!($compileNodes instanceof jqLite)) {
  5467. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5468. // modify it.
  5469. $compileNodes = jqLite($compileNodes);
  5470. }
  5471. // We can not compile top level text elements since text nodes can be merged and we will
  5472. // not be able to attach scope data to them, so we will wrap them in <span>
  5473. forEach($compileNodes, function(node, index){
  5474. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5475. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5476. }
  5477. });
  5478. var compositeLinkFn =
  5479. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5480. maxPriority, ignoreDirective, previousCompileContext);
  5481. safeAddClass($compileNodes, 'ng-scope');
  5482. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){
  5483. assertArg(scope, 'scope');
  5484. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5485. // and sometimes changes the structure of the DOM.
  5486. var $linkNode = cloneConnectFn
  5487. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5488. : $compileNodes;
  5489. forEach(transcludeControllers, function(instance, name) {
  5490. $linkNode.data('$' + name + 'Controller', instance);
  5491. });
  5492. // Attach scope only to non-text nodes.
  5493. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5494. var node = $linkNode[i],
  5495. nodeType = node.nodeType;
  5496. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5497. $linkNode.eq(i).data('$scope', scope);
  5498. }
  5499. }
  5500. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5501. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  5502. return $linkNode;
  5503. };
  5504. }
  5505. function safeAddClass($element, className) {
  5506. try {
  5507. $element.addClass(className);
  5508. } catch(e) {
  5509. // ignore, since it means that we are trying to set class on
  5510. // SVG element, where class name is read-only.
  5511. }
  5512. }
  5513. /**
  5514. * Compile function matches each node in nodeList against the directives. Once all directives
  5515. * for a particular node are collected their compile functions are executed. The compile
  5516. * functions return values - the linking functions - are combined into a composite linking
  5517. * function, which is the a linking function for the node.
  5518. *
  5519. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5520. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5521. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5522. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5523. * the rootElement must be set the jqLite collection of the compile root. This is
  5524. * needed so that the jqLite collection items can be replaced with widgets.
  5525. * @param {number=} maxPriority Max directive priority.
  5526. * @returns {Function} A composite linking function of all of the matched directives or null.
  5527. */
  5528. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5529. previousCompileContext) {
  5530. var linkFns = [],
  5531. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5532. for (var i = 0; i < nodeList.length; i++) {
  5533. attrs = new Attributes();
  5534. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5535. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5536. ignoreDirective);
  5537. nodeLinkFn = (directives.length)
  5538. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5539. null, [], [], previousCompileContext)
  5540. : null;
  5541. if (nodeLinkFn && nodeLinkFn.scope) {
  5542. safeAddClass(attrs.$$element, 'ng-scope');
  5543. }
  5544. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5545. !(childNodes = nodeList[i].childNodes) ||
  5546. !childNodes.length)
  5547. ? null
  5548. : compileNodes(childNodes,
  5549. nodeLinkFn ? (
  5550. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  5551. && nodeLinkFn.transclude) : transcludeFn);
  5552. linkFns.push(nodeLinkFn, childLinkFn);
  5553. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5554. //use the previous context only for the first element in the virtual group
  5555. previousCompileContext = null;
  5556. }
  5557. // return a linking function if we have found anything, null otherwise
  5558. return linkFnFound ? compositeLinkFn : null;
  5559. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  5560. var nodeLinkFn, childLinkFn, node, childScope, i, ii, n, childBoundTranscludeFn;
  5561. // copy nodeList so that linking doesn't break due to live list updates.
  5562. var nodeListLength = nodeList.length,
  5563. stableNodeList = new Array(nodeListLength);
  5564. for (i = 0; i < nodeListLength; i++) {
  5565. stableNodeList[i] = nodeList[i];
  5566. }
  5567. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5568. node = stableNodeList[n];
  5569. nodeLinkFn = linkFns[i++];
  5570. childLinkFn = linkFns[i++];
  5571. if (nodeLinkFn) {
  5572. if (nodeLinkFn.scope) {
  5573. childScope = scope.$new();
  5574. jqLite.data(node, '$scope', childScope);
  5575. } else {
  5576. childScope = scope;
  5577. }
  5578. if ( nodeLinkFn.transcludeOnThisElement ) {
  5579. childBoundTranscludeFn = createBoundTranscludeFn(scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  5580. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  5581. childBoundTranscludeFn = parentBoundTranscludeFn;
  5582. } else if (!parentBoundTranscludeFn && transcludeFn) {
  5583. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  5584. } else {
  5585. childBoundTranscludeFn = null;
  5586. }
  5587. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  5588. } else if (childLinkFn) {
  5589. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  5590. }
  5591. }
  5592. }
  5593. }
  5594. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  5595. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers) {
  5596. var scopeCreated = false;
  5597. if (!transcludedScope) {
  5598. transcludedScope = scope.$new();
  5599. transcludedScope.$$transcluded = true;
  5600. scopeCreated = true;
  5601. }
  5602. var clone = transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn);
  5603. if (scopeCreated) {
  5604. clone.on('$destroy', function() { transcludedScope.$destroy(); });
  5605. }
  5606. return clone;
  5607. };
  5608. return boundTranscludeFn;
  5609. }
  5610. /**
  5611. * Looks for directives on the given node and adds them to the directive collection which is
  5612. * sorted.
  5613. *
  5614. * @param node Node to search.
  5615. * @param directives An array to which the directives are added to. This array is sorted before
  5616. * the function returns.
  5617. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5618. * @param {number=} maxPriority Max directive priority.
  5619. */
  5620. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5621. var nodeType = node.nodeType,
  5622. attrsMap = attrs.$attr,
  5623. match,
  5624. className;
  5625. switch(nodeType) {
  5626. case 1: /* Element */
  5627. // use the node name: <directive>
  5628. addDirective(directives,
  5629. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5630. // iterate over the attributes
  5631. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  5632. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5633. var attrStartName = false;
  5634. var attrEndName = false;
  5635. attr = nAttrs[j];
  5636. if (!msie || msie >= 8 || attr.specified) {
  5637. name = attr.name;
  5638. value = trim(attr.value);
  5639. // support ngAttr attribute binding
  5640. ngAttrName = directiveNormalize(name);
  5641. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  5642. name = snake_case(ngAttrName.substr(6), '-');
  5643. }
  5644. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5645. if (ngAttrName === directiveNName + 'Start') {
  5646. attrStartName = name;
  5647. attrEndName = name.substr(0, name.length - 5) + 'end';
  5648. name = name.substr(0, name.length - 6);
  5649. }
  5650. nName = directiveNormalize(name.toLowerCase());
  5651. attrsMap[nName] = name;
  5652. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  5653. attrs[nName] = value;
  5654. if (getBooleanAttrName(node, nName)) {
  5655. attrs[nName] = true; // presence means true
  5656. }
  5657. }
  5658. addAttrInterpolateDirective(node, directives, value, nName);
  5659. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5660. attrEndName);
  5661. }
  5662. }
  5663. // use class as directive
  5664. className = node.className;
  5665. if (isString(className) && className !== '') {
  5666. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5667. nName = directiveNormalize(match[2]);
  5668. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5669. attrs[nName] = trim(match[3]);
  5670. }
  5671. className = className.substr(match.index + match[0].length);
  5672. }
  5673. }
  5674. break;
  5675. case 3: /* Text Node */
  5676. if (msie === 11) {
  5677. // Workaround for #11781
  5678. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === 3 /* Text Node */) {
  5679. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  5680. node.parentNode.removeChild(node.nextSibling);
  5681. }
  5682. }
  5683. addTextInterpolateDirective(directives, node.nodeValue);
  5684. break;
  5685. case 8: /* Comment */
  5686. try {
  5687. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5688. if (match) {
  5689. nName = directiveNormalize(match[1]);
  5690. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5691. attrs[nName] = trim(match[2]);
  5692. }
  5693. }
  5694. } catch (e) {
  5695. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5696. // comment's node value.
  5697. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5698. }
  5699. break;
  5700. }
  5701. directives.sort(byPriority);
  5702. return directives;
  5703. }
  5704. /**
  5705. * Given a node with an directive-start it collects all of the siblings until it finds
  5706. * directive-end.
  5707. * @param node
  5708. * @param attrStart
  5709. * @param attrEnd
  5710. * @returns {*}
  5711. */
  5712. function groupScan(node, attrStart, attrEnd) {
  5713. var nodes = [];
  5714. var depth = 0;
  5715. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5716. var startNode = node;
  5717. do {
  5718. if (!node) {
  5719. throw $compileMinErr('uterdir',
  5720. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5721. attrStart, attrEnd);
  5722. }
  5723. if (node.nodeType == 1 /** Element **/) {
  5724. if (node.hasAttribute(attrStart)) depth++;
  5725. if (node.hasAttribute(attrEnd)) depth--;
  5726. }
  5727. nodes.push(node);
  5728. node = node.nextSibling;
  5729. } while (depth > 0);
  5730. } else {
  5731. nodes.push(node);
  5732. }
  5733. return jqLite(nodes);
  5734. }
  5735. /**
  5736. * Wrapper for linking function which converts normal linking function into a grouped
  5737. * linking function.
  5738. * @param linkFn
  5739. * @param attrStart
  5740. * @param attrEnd
  5741. * @returns {Function}
  5742. */
  5743. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5744. return function(scope, element, attrs, controllers, transcludeFn) {
  5745. element = groupScan(element[0], attrStart, attrEnd);
  5746. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5747. };
  5748. }
  5749. /**
  5750. * Once the directives have been collected, their compile functions are executed. This method
  5751. * is responsible for inlining directive templates as well as terminating the application
  5752. * of the directives if the terminal directive has been reached.
  5753. *
  5754. * @param {Array} directives Array of collected directives to execute their compile function.
  5755. * this needs to be pre-sorted by priority order.
  5756. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5757. * @param {Object} templateAttrs The shared attribute function
  5758. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5759. * scope argument is auto-generated to the new
  5760. * child of the transcluded parent scope.
  5761. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5762. * argument has the root jqLite array so that we can replace nodes
  5763. * on it.
  5764. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5765. * compiling the transclusion.
  5766. * @param {Array.<Function>} preLinkFns
  5767. * @param {Array.<Function>} postLinkFns
  5768. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5769. * node
  5770. * @returns {Function} linkFn
  5771. */
  5772. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5773. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5774. previousCompileContext) {
  5775. previousCompileContext = previousCompileContext || {};
  5776. var terminalPriority = -Number.MAX_VALUE,
  5777. newScopeDirective,
  5778. controllerDirectives = previousCompileContext.controllerDirectives,
  5779. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5780. templateDirective = previousCompileContext.templateDirective,
  5781. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5782. hasTranscludeDirective = false,
  5783. hasTemplate = false,
  5784. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5785. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5786. directive,
  5787. directiveName,
  5788. $template,
  5789. replaceDirective = originalReplaceDirective,
  5790. childTranscludeFn = transcludeFn,
  5791. linkFn,
  5792. directiveValue;
  5793. // executes all directives on the current element
  5794. for(var i = 0, ii = directives.length; i < ii; i++) {
  5795. directive = directives[i];
  5796. var attrStart = directive.$$start;
  5797. var attrEnd = directive.$$end;
  5798. // collect multiblock sections
  5799. if (attrStart) {
  5800. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5801. }
  5802. $template = undefined;
  5803. if (terminalPriority > directive.priority) {
  5804. break; // prevent further processing of directives
  5805. }
  5806. if (directiveValue = directive.scope) {
  5807. newScopeDirective = newScopeDirective || directive;
  5808. // skip the check for directives with async templates, we'll check the derived sync
  5809. // directive when the template arrives
  5810. if (!directive.templateUrl) {
  5811. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5812. $compileNode);
  5813. if (isObject(directiveValue)) {
  5814. newIsolateScopeDirective = directive;
  5815. }
  5816. }
  5817. }
  5818. directiveName = directive.name;
  5819. if (!directive.templateUrl && directive.controller) {
  5820. directiveValue = directive.controller;
  5821. controllerDirectives = controllerDirectives || {};
  5822. assertNoDuplicate("'" + directiveName + "' controller",
  5823. controllerDirectives[directiveName], directive, $compileNode);
  5824. controllerDirectives[directiveName] = directive;
  5825. }
  5826. if (directiveValue = directive.transclude) {
  5827. hasTranscludeDirective = true;
  5828. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5829. // This option should only be used by directives that know how to safely handle element transclusion,
  5830. // where the transcluded nodes are added or replaced after linking.
  5831. if (!directive.$$tlb) {
  5832. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5833. nonTlbTranscludeDirective = directive;
  5834. }
  5835. if (directiveValue == 'element') {
  5836. hasElementTranscludeDirective = true;
  5837. terminalPriority = directive.priority;
  5838. $template = $compileNode;
  5839. $compileNode = templateAttrs.$$element =
  5840. jqLite(document.createComment(' ' + directiveName + ': ' +
  5841. templateAttrs[directiveName] + ' '));
  5842. compileNode = $compileNode[0];
  5843. replaceWith(jqCollection, sliceArgs($template), compileNode);
  5844. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5845. replaceDirective && replaceDirective.name, {
  5846. // Don't pass in:
  5847. // - controllerDirectives - otherwise we'll create duplicates controllers
  5848. // - newIsolateScopeDirective or templateDirective - combining templates with
  5849. // element transclusion doesn't make sense.
  5850. //
  5851. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5852. // on the same element more than once.
  5853. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5854. });
  5855. } else {
  5856. $template = jqLite(jqLiteClone(compileNode)).contents();
  5857. $compileNode.empty(); // clear contents
  5858. childTranscludeFn = compile($template, transcludeFn);
  5859. }
  5860. }
  5861. if (directive.template) {
  5862. hasTemplate = true;
  5863. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5864. templateDirective = directive;
  5865. directiveValue = (isFunction(directive.template))
  5866. ? directive.template($compileNode, templateAttrs)
  5867. : directive.template;
  5868. directiveValue = denormalizeTemplate(directiveValue);
  5869. if (directive.replace) {
  5870. replaceDirective = directive;
  5871. if (jqLiteIsTextNode(directiveValue)) {
  5872. $template = [];
  5873. } else {
  5874. $template = jqLite(trim(directiveValue));
  5875. }
  5876. compileNode = $template[0];
  5877. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5878. throw $compileMinErr('tplrt',
  5879. "Template for directive '{0}' must have exactly one root element. {1}",
  5880. directiveName, '');
  5881. }
  5882. replaceWith(jqCollection, $compileNode, compileNode);
  5883. var newTemplateAttrs = {$attr: {}};
  5884. // combine directives from the original node and from the template:
  5885. // - take the array of directives for this element
  5886. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5887. // - collect directives from the template and sort them by priority
  5888. // - combine directives as: processed + template + unprocessed
  5889. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5890. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5891. if (newIsolateScopeDirective) {
  5892. markDirectivesAsIsolate(templateDirectives);
  5893. }
  5894. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5895. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5896. ii = directives.length;
  5897. } else {
  5898. $compileNode.html(directiveValue);
  5899. }
  5900. }
  5901. if (directive.templateUrl) {
  5902. hasTemplate = true;
  5903. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5904. templateDirective = directive;
  5905. if (directive.replace) {
  5906. replaceDirective = directive;
  5907. }
  5908. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5909. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  5910. controllerDirectives: controllerDirectives,
  5911. newIsolateScopeDirective: newIsolateScopeDirective,
  5912. templateDirective: templateDirective,
  5913. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5914. });
  5915. ii = directives.length;
  5916. } else if (directive.compile) {
  5917. try {
  5918. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5919. if (isFunction(linkFn)) {
  5920. addLinkFns(null, linkFn, attrStart, attrEnd);
  5921. } else if (linkFn) {
  5922. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5923. }
  5924. } catch (e) {
  5925. $exceptionHandler(e, startingTag($compileNode));
  5926. }
  5927. }
  5928. if (directive.terminal) {
  5929. nodeLinkFn.terminal = true;
  5930. terminalPriority = Math.max(terminalPriority, directive.priority);
  5931. }
  5932. }
  5933. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5934. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  5935. nodeLinkFn.templateOnThisElement = hasTemplate;
  5936. nodeLinkFn.transclude = childTranscludeFn;
  5937. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5938. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5939. return nodeLinkFn;
  5940. ////////////////////
  5941. function addLinkFns(pre, post, attrStart, attrEnd) {
  5942. if (pre) {
  5943. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5944. pre.require = directive.require;
  5945. pre.directiveName = directiveName;
  5946. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5947. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5948. }
  5949. preLinkFns.push(pre);
  5950. }
  5951. if (post) {
  5952. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5953. post.require = directive.require;
  5954. post.directiveName = directiveName;
  5955. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5956. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5957. }
  5958. postLinkFns.push(post);
  5959. }
  5960. }
  5961. function getControllers(directiveName, require, $element, elementControllers) {
  5962. var value, retrievalMethod = 'data', optional = false;
  5963. if (isString(require)) {
  5964. while((value = require.charAt(0)) == '^' || value == '?') {
  5965. require = require.substr(1);
  5966. if (value == '^') {
  5967. retrievalMethod = 'inheritedData';
  5968. }
  5969. optional = optional || value == '?';
  5970. }
  5971. value = null;
  5972. if (elementControllers && retrievalMethod === 'data') {
  5973. value = elementControllers[require];
  5974. }
  5975. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5976. if (!value && !optional) {
  5977. throw $compileMinErr('ctreq',
  5978. "Controller '{0}', required by directive '{1}', can't be found!",
  5979. require, directiveName);
  5980. }
  5981. return value;
  5982. } else if (isArray(require)) {
  5983. value = [];
  5984. forEach(require, function(require) {
  5985. value.push(getControllers(directiveName, require, $element, elementControllers));
  5986. });
  5987. }
  5988. return value;
  5989. }
  5990. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5991. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5992. attrs = (compileNode === linkNode)
  5993. ? templateAttrs
  5994. : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5995. $element = attrs.$$element;
  5996. if (newIsolateScopeDirective) {
  5997. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5998. isolateScope = scope.$new(true);
  5999. if (templateDirective && (templateDirective === newIsolateScopeDirective ||
  6000. templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  6001. $element.data('$isolateScope', isolateScope);
  6002. } else {
  6003. $element.data('$isolateScopeNoTemplate', isolateScope);
  6004. }
  6005. safeAddClass($element, 'ng-isolate-scope');
  6006. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  6007. var match = definition.match(LOCAL_REGEXP) || [],
  6008. attrName = match[3] || scopeName,
  6009. optional = (match[2] == '?'),
  6010. mode = match[1], // @, =, or &
  6011. lastValue,
  6012. parentGet, parentSet, compare;
  6013. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  6014. switch (mode) {
  6015. case '@':
  6016. attrs.$observe(attrName, function(value) {
  6017. isolateScope[scopeName] = value;
  6018. });
  6019. attrs.$$observers[attrName].$$scope = scope;
  6020. if( attrs[attrName] ) {
  6021. // If the attribute has been provided then we trigger an interpolation to ensure
  6022. // the value is there for use in the link fn
  6023. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  6024. }
  6025. break;
  6026. case '=':
  6027. if (optional && !attrs[attrName]) {
  6028. return;
  6029. }
  6030. parentGet = $parse(attrs[attrName]);
  6031. if (parentGet.literal) {
  6032. compare = equals;
  6033. } else {
  6034. compare = function(a,b) { return a === b || (a !== a && b !== b); };
  6035. }
  6036. parentSet = parentGet.assign || function() {
  6037. // reset the change, or we will throw this exception on every $digest
  6038. lastValue = isolateScope[scopeName] = parentGet(scope);
  6039. throw $compileMinErr('nonassign',
  6040. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6041. attrs[attrName], newIsolateScopeDirective.name);
  6042. };
  6043. lastValue = isolateScope[scopeName] = parentGet(scope);
  6044. isolateScope.$watch(function parentValueWatch() {
  6045. var parentValue = parentGet(scope);
  6046. if (!compare(parentValue, isolateScope[scopeName])) {
  6047. // we are out of sync and need to copy
  6048. if (!compare(parentValue, lastValue)) {
  6049. // parent changed and it has precedence
  6050. isolateScope[scopeName] = parentValue;
  6051. } else {
  6052. // if the parent can be assigned then do so
  6053. parentSet(scope, parentValue = isolateScope[scopeName]);
  6054. }
  6055. }
  6056. return lastValue = parentValue;
  6057. }, null, parentGet.literal);
  6058. break;
  6059. case '&':
  6060. parentGet = $parse(attrs[attrName]);
  6061. isolateScope[scopeName] = function(locals) {
  6062. return parentGet(scope, locals);
  6063. };
  6064. break;
  6065. default:
  6066. throw $compileMinErr('iscp',
  6067. "Invalid isolate scope definition for directive '{0}'." +
  6068. " Definition: {... {1}: '{2}' ...}",
  6069. newIsolateScopeDirective.name, scopeName, definition);
  6070. }
  6071. });
  6072. }
  6073. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  6074. if (controllerDirectives) {
  6075. forEach(controllerDirectives, function(directive) {
  6076. var locals = {
  6077. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6078. $element: $element,
  6079. $attrs: attrs,
  6080. $transclude: transcludeFn
  6081. }, controllerInstance;
  6082. controller = directive.controller;
  6083. if (controller == '@') {
  6084. controller = attrs[directive.name];
  6085. }
  6086. controllerInstance = $controller(controller, locals);
  6087. // For directives with element transclusion the element is a comment,
  6088. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6089. // clean up (http://bugs.jquery.com/ticket/8335).
  6090. // Instead, we save the controllers for the element in a local hash and attach to .data
  6091. // later, once we have the actual element.
  6092. elementControllers[directive.name] = controllerInstance;
  6093. if (!hasElementTranscludeDirective) {
  6094. $element.data('$' + directive.name + 'Controller', controllerInstance);
  6095. }
  6096. if (directive.controllerAs) {
  6097. locals.$scope[directive.controllerAs] = controllerInstance;
  6098. }
  6099. });
  6100. }
  6101. // PRELINKING
  6102. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  6103. try {
  6104. linkFn = preLinkFns[i];
  6105. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6106. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6107. } catch (e) {
  6108. $exceptionHandler(e, startingTag($element));
  6109. }
  6110. }
  6111. // RECURSION
  6112. // We only pass the isolate scope, if the isolate directive has a template,
  6113. // otherwise the child elements do not belong to the isolate directive.
  6114. var scopeToChild = scope;
  6115. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6116. scopeToChild = isolateScope;
  6117. }
  6118. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6119. // POSTLINKING
  6120. for(i = postLinkFns.length - 1; i >= 0; i--) {
  6121. try {
  6122. linkFn = postLinkFns[i];
  6123. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6124. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6125. } catch (e) {
  6126. $exceptionHandler(e, startingTag($element));
  6127. }
  6128. }
  6129. // This is the function that is injected as `$transclude`.
  6130. function controllersBoundTransclude(scope, cloneAttachFn) {
  6131. var transcludeControllers;
  6132. // no scope passed
  6133. if (arguments.length < 2) {
  6134. cloneAttachFn = scope;
  6135. scope = undefined;
  6136. }
  6137. if (hasElementTranscludeDirective) {
  6138. transcludeControllers = elementControllers;
  6139. }
  6140. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  6141. }
  6142. }
  6143. }
  6144. function markDirectivesAsIsolate(directives) {
  6145. // mark all directives as needing isolate scope.
  6146. for (var j = 0, jj = directives.length; j < jj; j++) {
  6147. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6148. }
  6149. }
  6150. /**
  6151. * looks up the directive and decorates it with exception handling and proper parameters. We
  6152. * call this the boundDirective.
  6153. *
  6154. * @param {string} name name of the directive to look up.
  6155. * @param {string} location The directive must be found in specific format.
  6156. * String containing any of theses characters:
  6157. *
  6158. * * `E`: element name
  6159. * * `A': attribute
  6160. * * `C`: class
  6161. * * `M`: comment
  6162. * @returns {boolean} true if directive was added.
  6163. */
  6164. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6165. endAttrName) {
  6166. if (name === ignoreDirective) return null;
  6167. var match = null;
  6168. if (hasDirectives.hasOwnProperty(name)) {
  6169. for(var directive, directives = $injector.get(name + Suffix),
  6170. i = 0, ii = directives.length; i<ii; i++) {
  6171. try {
  6172. directive = directives[i];
  6173. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6174. directive.restrict.indexOf(location) != -1) {
  6175. if (startAttrName) {
  6176. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6177. }
  6178. tDirectives.push(directive);
  6179. match = directive;
  6180. }
  6181. } catch(e) { $exceptionHandler(e); }
  6182. }
  6183. }
  6184. return match;
  6185. }
  6186. /**
  6187. * When the element is replaced with HTML template then the new attributes
  6188. * on the template need to be merged with the existing attributes in the DOM.
  6189. * The desired effect is to have both of the attributes present.
  6190. *
  6191. * @param {object} dst destination attributes (original DOM)
  6192. * @param {object} src source attributes (from the directive template)
  6193. */
  6194. function mergeTemplateAttributes(dst, src) {
  6195. var srcAttr = src.$attr,
  6196. dstAttr = dst.$attr,
  6197. $element = dst.$$element;
  6198. // reapply the old attributes to the new element
  6199. forEach(dst, function(value, key) {
  6200. if (key.charAt(0) != '$') {
  6201. if (src[key] && src[key] !== value) {
  6202. value += (key === 'style' ? ';' : ' ') + src[key];
  6203. }
  6204. dst.$set(key, value, true, srcAttr[key]);
  6205. }
  6206. });
  6207. // copy the new attributes on the old attrs object
  6208. forEach(src, function(value, key) {
  6209. if (key == 'class') {
  6210. safeAddClass($element, value);
  6211. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6212. } else if (key == 'style') {
  6213. $element.attr('style', $element.attr('style') + ';' + value);
  6214. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6215. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6216. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6217. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6218. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6219. dst[key] = value;
  6220. dstAttr[key] = srcAttr[key];
  6221. }
  6222. });
  6223. }
  6224. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6225. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6226. var linkQueue = [],
  6227. afterTemplateNodeLinkFn,
  6228. afterTemplateChildLinkFn,
  6229. beforeTemplateCompileNode = $compileNode[0],
  6230. origAsyncDirective = directives.shift(),
  6231. // The fact that we have to copy and patch the directive seems wrong!
  6232. derivedSyncDirective = extend({}, origAsyncDirective, {
  6233. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6234. }),
  6235. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6236. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6237. : origAsyncDirective.templateUrl;
  6238. $compileNode.empty();
  6239. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6240. success(function(content) {
  6241. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6242. content = denormalizeTemplate(content);
  6243. if (origAsyncDirective.replace) {
  6244. if (jqLiteIsTextNode(content)) {
  6245. $template = [];
  6246. } else {
  6247. $template = jqLite(trim(content));
  6248. }
  6249. compileNode = $template[0];
  6250. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6251. throw $compileMinErr('tplrt',
  6252. "Template for directive '{0}' must have exactly one root element. {1}",
  6253. origAsyncDirective.name, templateUrl);
  6254. }
  6255. tempTemplateAttrs = {$attr: {}};
  6256. replaceWith($rootElement, $compileNode, compileNode);
  6257. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6258. if (isObject(origAsyncDirective.scope)) {
  6259. markDirectivesAsIsolate(templateDirectives);
  6260. }
  6261. directives = templateDirectives.concat(directives);
  6262. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6263. } else {
  6264. compileNode = beforeTemplateCompileNode;
  6265. $compileNode.html(content);
  6266. }
  6267. directives.unshift(derivedSyncDirective);
  6268. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6269. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6270. previousCompileContext);
  6271. forEach($rootElement, function(node, i) {
  6272. if (node == compileNode) {
  6273. $rootElement[i] = $compileNode[0];
  6274. }
  6275. });
  6276. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6277. while(linkQueue.length) {
  6278. var scope = linkQueue.shift(),
  6279. beforeTemplateLinkNode = linkQueue.shift(),
  6280. linkRootElement = linkQueue.shift(),
  6281. boundTranscludeFn = linkQueue.shift(),
  6282. linkNode = $compileNode[0];
  6283. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6284. var oldClasses = beforeTemplateLinkNode.className;
  6285. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6286. origAsyncDirective.replace)) {
  6287. // it was cloned therefore we have to clone as well.
  6288. linkNode = jqLiteClone(compileNode);
  6289. }
  6290. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6291. // Copy in CSS classes from original node
  6292. safeAddClass(jqLite(linkNode), oldClasses);
  6293. }
  6294. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6295. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6296. } else {
  6297. childBoundTranscludeFn = boundTranscludeFn;
  6298. }
  6299. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6300. childBoundTranscludeFn);
  6301. }
  6302. linkQueue = null;
  6303. }).
  6304. error(function(response, code, headers, config) {
  6305. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6306. });
  6307. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6308. var childBoundTranscludeFn = boundTranscludeFn;
  6309. if (linkQueue) {
  6310. linkQueue.push(scope);
  6311. linkQueue.push(node);
  6312. linkQueue.push(rootElement);
  6313. linkQueue.push(childBoundTranscludeFn);
  6314. } else {
  6315. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6316. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6317. }
  6318. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  6319. }
  6320. };
  6321. }
  6322. /**
  6323. * Sorting function for bound directives.
  6324. */
  6325. function byPriority(a, b) {
  6326. var diff = b.priority - a.priority;
  6327. if (diff !== 0) return diff;
  6328. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6329. return a.index - b.index;
  6330. }
  6331. function assertNoDuplicate(what, previousDirective, directive, element) {
  6332. if (previousDirective) {
  6333. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6334. previousDirective.name, directive.name, what, startingTag(element));
  6335. }
  6336. }
  6337. function addTextInterpolateDirective(directives, text) {
  6338. var interpolateFn = $interpolate(text, true);
  6339. if (interpolateFn) {
  6340. directives.push({
  6341. priority: 0,
  6342. compile: function textInterpolateCompileFn(templateNode) {
  6343. // when transcluding a template that has bindings in the root
  6344. // then we don't have a parent and should do this in the linkFn
  6345. var parent = templateNode.parent(), hasCompileParent = parent.length;
  6346. if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding');
  6347. return function textInterpolateLinkFn(scope, node) {
  6348. var parent = node.parent(),
  6349. bindings = parent.data('$binding') || [];
  6350. bindings.push(interpolateFn);
  6351. parent.data('$binding', bindings);
  6352. if (!hasCompileParent) safeAddClass(parent, 'ng-binding');
  6353. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6354. node[0].nodeValue = value;
  6355. });
  6356. };
  6357. }
  6358. });
  6359. }
  6360. }
  6361. function getTrustedContext(node, attrNormalizedName) {
  6362. if (attrNormalizedName == "srcdoc") {
  6363. return $sce.HTML;
  6364. }
  6365. var tag = nodeName_(node);
  6366. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6367. if (attrNormalizedName == "xlinkHref" ||
  6368. (tag == "FORM" && attrNormalizedName == "action") ||
  6369. // links can be stylesheets or imports, which can run script in the current origin
  6370. (tag == "LINK" && attrNormalizedName == "href") ||
  6371. (tag != "IMG" && (attrNormalizedName == "src" ||
  6372. attrNormalizedName == "ngSrc"))) {
  6373. return $sce.RESOURCE_URL;
  6374. }
  6375. }
  6376. function addAttrInterpolateDirective(node, directives, value, name) {
  6377. var interpolateFn = $interpolate(value, true);
  6378. // no interpolation found -> ignore
  6379. if (!interpolateFn) return;
  6380. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6381. throw $compileMinErr("selmulti",
  6382. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6383. startingTag(node));
  6384. }
  6385. directives.push({
  6386. priority: 100,
  6387. compile: function() {
  6388. return {
  6389. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6390. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6391. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6392. throw $compileMinErr('nodomevents',
  6393. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6394. "ng- versions (such as ng-click instead of onclick) instead.");
  6395. }
  6396. // we need to interpolate again, in case the attribute value has been updated
  6397. // (e.g. by another directive's compile function)
  6398. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6399. // if attribute was updated so that there is no interpolation going on we don't want to
  6400. // register any observers
  6401. if (!interpolateFn) return;
  6402. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6403. // actual attr value
  6404. attr[name] = interpolateFn(scope);
  6405. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6406. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6407. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6408. //special case for class attribute addition + removal
  6409. //so that class changes can tap into the animation
  6410. //hooks provided by the $animate service. Be sure to
  6411. //skip animations when the first digest occurs (when
  6412. //both the new and the old values are the same) since
  6413. //the CSS classes are the non-interpolated values
  6414. if(name === 'class' && newValue != oldValue) {
  6415. attr.$updateClass(newValue, oldValue);
  6416. } else {
  6417. attr.$set(name, newValue);
  6418. }
  6419. });
  6420. }
  6421. };
  6422. }
  6423. });
  6424. }
  6425. /**
  6426. * This is a special jqLite.replaceWith, which can replace items which
  6427. * have no parents, provided that the containing jqLite collection is provided.
  6428. *
  6429. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6430. * in the root of the tree.
  6431. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6432. * the shell, but replace its DOM node reference.
  6433. * @param {Node} newNode The new DOM node.
  6434. */
  6435. function replaceWith($rootElement, elementsToRemove, newNode) {
  6436. var firstElementToRemove = elementsToRemove[0],
  6437. removeCount = elementsToRemove.length,
  6438. parent = firstElementToRemove.parentNode,
  6439. i, ii;
  6440. if ($rootElement) {
  6441. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6442. if ($rootElement[i] == firstElementToRemove) {
  6443. $rootElement[i++] = newNode;
  6444. for (var j = i, j2 = j + removeCount - 1,
  6445. jj = $rootElement.length;
  6446. j < jj; j++, j2++) {
  6447. if (j2 < jj) {
  6448. $rootElement[j] = $rootElement[j2];
  6449. } else {
  6450. delete $rootElement[j];
  6451. }
  6452. }
  6453. $rootElement.length -= removeCount - 1;
  6454. break;
  6455. }
  6456. }
  6457. }
  6458. if (parent) {
  6459. parent.replaceChild(newNode, firstElementToRemove);
  6460. }
  6461. var fragment = document.createDocumentFragment();
  6462. fragment.appendChild(firstElementToRemove);
  6463. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6464. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6465. var element = elementsToRemove[k];
  6466. jqLite(element).remove(); // must do this way to clean up expando
  6467. fragment.appendChild(element);
  6468. delete elementsToRemove[k];
  6469. }
  6470. elementsToRemove[0] = newNode;
  6471. elementsToRemove.length = 1;
  6472. }
  6473. function cloneAndAnnotateFn(fn, annotation) {
  6474. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6475. }
  6476. }];
  6477. }
  6478. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6479. /**
  6480. * Converts all accepted directives format into proper directive name.
  6481. * @param name Name to normalize
  6482. */
  6483. function directiveNormalize(name) {
  6484. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6485. }
  6486. /**
  6487. * @ngdoc type
  6488. * @name $compile.directive.Attributes
  6489. *
  6490. * @description
  6491. * A shared object between directive compile / linking functions which contains normalized DOM
  6492. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6493. * needed since all of these are treated as equivalent in Angular:
  6494. *
  6495. * ```
  6496. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6497. * ```
  6498. */
  6499. /**
  6500. * @ngdoc property
  6501. * @name $compile.directive.Attributes#$attr
  6502. *
  6503. * @description
  6504. * A map of DOM element attribute names to the normalized name. This is
  6505. * needed to do reverse lookup from normalized name back to actual name.
  6506. */
  6507. /**
  6508. * @ngdoc method
  6509. * @name $compile.directive.Attributes#$set
  6510. * @kind function
  6511. *
  6512. * @description
  6513. * Set DOM element attribute value.
  6514. *
  6515. *
  6516. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6517. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6518. * property to the original name.
  6519. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6520. */
  6521. /**
  6522. * Closure compiler type information
  6523. */
  6524. function nodesetLinkingFn(
  6525. /* angular.Scope */ scope,
  6526. /* NodeList */ nodeList,
  6527. /* Element */ rootElement,
  6528. /* function(Function) */ boundTranscludeFn
  6529. ){}
  6530. function directiveLinkingFn(
  6531. /* nodesetLinkingFn */ nodesetLinkingFn,
  6532. /* angular.Scope */ scope,
  6533. /* Node */ node,
  6534. /* Element */ rootElement,
  6535. /* function(Function) */ boundTranscludeFn
  6536. ){}
  6537. function tokenDifference(str1, str2) {
  6538. var values = '',
  6539. tokens1 = str1.split(/\s+/),
  6540. tokens2 = str2.split(/\s+/);
  6541. outer:
  6542. for(var i = 0; i < tokens1.length; i++) {
  6543. var token = tokens1[i];
  6544. for(var j = 0; j < tokens2.length; j++) {
  6545. if(token == tokens2[j]) continue outer;
  6546. }
  6547. values += (values.length > 0 ? ' ' : '') + token;
  6548. }
  6549. return values;
  6550. }
  6551. /**
  6552. * @ngdoc provider
  6553. * @name $controllerProvider
  6554. * @description
  6555. * The {@link ng.$controller $controller service} is used by Angular to create new
  6556. * controllers.
  6557. *
  6558. * This provider allows controller registration via the
  6559. * {@link ng.$controllerProvider#register register} method.
  6560. */
  6561. function $ControllerProvider() {
  6562. var controllers = {},
  6563. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6564. /**
  6565. * @ngdoc method
  6566. * @name $controllerProvider#register
  6567. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6568. * the names and the values are the constructors.
  6569. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6570. * annotations in the array notation).
  6571. */
  6572. this.register = function(name, constructor) {
  6573. assertNotHasOwnProperty(name, 'controller');
  6574. if (isObject(name)) {
  6575. extend(controllers, name);
  6576. } else {
  6577. controllers[name] = constructor;
  6578. }
  6579. };
  6580. this.$get = ['$injector', '$window', function($injector, $window) {
  6581. /**
  6582. * @ngdoc service
  6583. * @name $controller
  6584. * @requires $injector
  6585. *
  6586. * @param {Function|string} constructor If called with a function then it's considered to be the
  6587. * controller constructor function. Otherwise it's considered to be a string which is used
  6588. * to retrieve the controller constructor using the following steps:
  6589. *
  6590. * * check if a controller with given name is registered via `$controllerProvider`
  6591. * * check if evaluating the string on the current scope returns a constructor
  6592. * * check `window[constructor]` on the global `window` object
  6593. *
  6594. * @param {Object} locals Injection locals for Controller.
  6595. * @return {Object} Instance of given controller.
  6596. *
  6597. * @description
  6598. * `$controller` service is responsible for instantiating controllers.
  6599. *
  6600. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6601. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6602. */
  6603. return function(expression, locals) {
  6604. var instance, match, constructor, identifier;
  6605. if(isString(expression)) {
  6606. match = expression.match(CNTRL_REG),
  6607. constructor = match[1],
  6608. identifier = match[3];
  6609. expression = controllers.hasOwnProperty(constructor)
  6610. ? controllers[constructor]
  6611. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6612. assertArgFn(expression, constructor, true);
  6613. }
  6614. instance = $injector.instantiate(expression, locals);
  6615. if (identifier) {
  6616. if (!(locals && typeof locals.$scope === 'object')) {
  6617. throw minErr('$controller')('noscp',
  6618. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6619. constructor || expression.name, identifier);
  6620. }
  6621. locals.$scope[identifier] = instance;
  6622. }
  6623. return instance;
  6624. };
  6625. }];
  6626. }
  6627. /**
  6628. * @ngdoc service
  6629. * @name $document
  6630. * @requires $window
  6631. *
  6632. * @description
  6633. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6634. *
  6635. * @example
  6636. <example module="documentExample">
  6637. <file name="index.html">
  6638. <div ng-controller="ExampleController">
  6639. <p>$document title: <b ng-bind="title"></b></p>
  6640. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6641. </div>
  6642. </file>
  6643. <file name="script.js">
  6644. angular.module('documentExample', [])
  6645. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  6646. $scope.title = $document[0].title;
  6647. $scope.windowTitle = angular.element(window.document)[0].title;
  6648. }]);
  6649. </file>
  6650. </example>
  6651. */
  6652. function $DocumentProvider(){
  6653. this.$get = ['$window', function(window){
  6654. return jqLite(window.document);
  6655. }];
  6656. }
  6657. /**
  6658. * @ngdoc service
  6659. * @name $exceptionHandler
  6660. * @requires ng.$log
  6661. *
  6662. * @description
  6663. * Any uncaught exception in angular expressions is delegated to this service.
  6664. * The default implementation simply delegates to `$log.error` which logs it into
  6665. * the browser console.
  6666. *
  6667. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6668. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6669. *
  6670. * ## Example:
  6671. *
  6672. * ```js
  6673. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6674. * return function (exception, cause) {
  6675. * exception.message += ' (caused by "' + cause + '")';
  6676. * throw exception;
  6677. * };
  6678. * });
  6679. * ```
  6680. *
  6681. * This example will override the normal action of `$exceptionHandler`, to make angular
  6682. * exceptions fail hard when they happen, instead of just logging to the console.
  6683. *
  6684. * @param {Error} exception Exception associated with the error.
  6685. * @param {string=} cause optional information about the context in which
  6686. * the error was thrown.
  6687. *
  6688. */
  6689. function $ExceptionHandlerProvider() {
  6690. this.$get = ['$log', function($log) {
  6691. return function(exception, cause) {
  6692. $log.error.apply($log, arguments);
  6693. };
  6694. }];
  6695. }
  6696. /**
  6697. * Parse headers into key value object
  6698. *
  6699. * @param {string} headers Raw headers as a string
  6700. * @returns {Object} Parsed headers as key value object
  6701. */
  6702. function parseHeaders(headers) {
  6703. var parsed = {}, key, val, i;
  6704. if (!headers) return parsed;
  6705. forEach(headers.split('\n'), function(line) {
  6706. i = line.indexOf(':');
  6707. key = lowercase(trim(line.substr(0, i)));
  6708. val = trim(line.substr(i + 1));
  6709. if (key) {
  6710. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6711. }
  6712. });
  6713. return parsed;
  6714. }
  6715. /**
  6716. * Returns a function that provides access to parsed headers.
  6717. *
  6718. * Headers are lazy parsed when first requested.
  6719. * @see parseHeaders
  6720. *
  6721. * @param {(string|Object)} headers Headers to provide access to.
  6722. * @returns {function(string=)} Returns a getter function which if called with:
  6723. *
  6724. * - if called with single an argument returns a single header value or null
  6725. * - if called with no arguments returns an object containing all headers.
  6726. */
  6727. function headersGetter(headers) {
  6728. var headersObj = isObject(headers) ? headers : undefined;
  6729. return function(name) {
  6730. if (!headersObj) headersObj = parseHeaders(headers);
  6731. if (name) {
  6732. return headersObj[lowercase(name)] || null;
  6733. }
  6734. return headersObj;
  6735. };
  6736. }
  6737. /**
  6738. * Chain all given functions
  6739. *
  6740. * This function is used for both request and response transforming
  6741. *
  6742. * @param {*} data Data to transform.
  6743. * @param {function(string=)} headers Http headers getter fn.
  6744. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6745. * @returns {*} Transformed data.
  6746. */
  6747. function transformData(data, headers, fns) {
  6748. if (isFunction(fns))
  6749. return fns(data, headers);
  6750. forEach(fns, function(fn) {
  6751. data = fn(data, headers);
  6752. });
  6753. return data;
  6754. }
  6755. function isSuccess(status) {
  6756. return 200 <= status && status < 300;
  6757. }
  6758. /**
  6759. * @ngdoc provider
  6760. * @name $httpProvider
  6761. * @description
  6762. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  6763. * */
  6764. function $HttpProvider() {
  6765. var JSON_START = /^\s*(\[|\{[^\{])/,
  6766. JSON_END = /[\}\]]\s*$/,
  6767. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6768. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6769. /**
  6770. * @ngdoc property
  6771. * @name $httpProvider#defaults
  6772. * @description
  6773. *
  6774. * Object containing default values for all {@link ng.$http $http} requests.
  6775. *
  6776. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  6777. * Defaults value is `'XSRF-TOKEN'`.
  6778. *
  6779. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  6780. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  6781. *
  6782. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  6783. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  6784. * setting default headers.
  6785. * - **`defaults.headers.common`**
  6786. * - **`defaults.headers.post`**
  6787. * - **`defaults.headers.put`**
  6788. * - **`defaults.headers.patch`**
  6789. **/
  6790. var defaults = this.defaults = {
  6791. // transform incoming response data
  6792. transformResponse: [function(data) {
  6793. if (isString(data)) {
  6794. // strip json vulnerability protection prefix
  6795. data = data.replace(PROTECTION_PREFIX, '');
  6796. if (JSON_START.test(data) && JSON_END.test(data))
  6797. data = fromJson(data);
  6798. }
  6799. return data;
  6800. }],
  6801. // transform outgoing request data
  6802. transformRequest: [function(d) {
  6803. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6804. }],
  6805. // default headers
  6806. headers: {
  6807. common: {
  6808. 'Accept': 'application/json, text/plain, */*'
  6809. },
  6810. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6811. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6812. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  6813. },
  6814. xsrfCookieName: 'XSRF-TOKEN',
  6815. xsrfHeaderName: 'X-XSRF-TOKEN'
  6816. };
  6817. /**
  6818. * @ngdoc property
  6819. * @name $httpProvider#interceptors
  6820. * @description
  6821. *
  6822. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  6823. * pre-processing of request or postprocessing of responses.
  6824. *
  6825. * These service factories are ordered by request, i.e. they are applied in the same order as the
  6826. * array, on request, but reverse order, on response.
  6827. *
  6828. * {@link ng.$http#interceptors Interceptors detailed info}
  6829. **/
  6830. var interceptorFactories = this.interceptors = [];
  6831. /**
  6832. * For historical reasons, response interceptors are ordered by the order in which
  6833. * they are applied to the response. (This is the opposite of interceptorFactories)
  6834. */
  6835. var responseInterceptorFactories = this.responseInterceptors = [];
  6836. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6837. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6838. var defaultCache = $cacheFactory('$http');
  6839. /**
  6840. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6841. * The reversal is needed so that we can build up the interception chain around the
  6842. * server request.
  6843. */
  6844. var reversedInterceptors = [];
  6845. forEach(interceptorFactories, function(interceptorFactory) {
  6846. reversedInterceptors.unshift(isString(interceptorFactory)
  6847. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6848. });
  6849. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6850. var responseFn = isString(interceptorFactory)
  6851. ? $injector.get(interceptorFactory)
  6852. : $injector.invoke(interceptorFactory);
  6853. /**
  6854. * Response interceptors go before "around" interceptors (no real reason, just
  6855. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6856. * the splice.
  6857. */
  6858. reversedInterceptors.splice(index, 0, {
  6859. response: function(response) {
  6860. return responseFn($q.when(response));
  6861. },
  6862. responseError: function(response) {
  6863. return responseFn($q.reject(response));
  6864. }
  6865. });
  6866. });
  6867. /**
  6868. * @ngdoc service
  6869. * @kind function
  6870. * @name $http
  6871. * @requires ng.$httpBackend
  6872. * @requires $cacheFactory
  6873. * @requires $rootScope
  6874. * @requires $q
  6875. * @requires $injector
  6876. *
  6877. * @description
  6878. * The `$http` service is a core Angular service that facilitates communication with the remote
  6879. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6880. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6881. *
  6882. * For unit testing applications that use `$http` service, see
  6883. * {@link ngMock.$httpBackend $httpBackend mock}.
  6884. *
  6885. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6886. * $resource} service.
  6887. *
  6888. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6889. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6890. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6891. *
  6892. *
  6893. * # General usage
  6894. * The `$http` service is a function which takes a single argument — a configuration object —
  6895. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6896. * with two $http specific methods: `success` and `error`.
  6897. *
  6898. * ```js
  6899. * $http({method: 'GET', url: '/someUrl'}).
  6900. * success(function(data, status, headers, config) {
  6901. * // this callback will be called asynchronously
  6902. * // when the response is available
  6903. * }).
  6904. * error(function(data, status, headers, config) {
  6905. * // called asynchronously if an error occurs
  6906. * // or server returns response with an error status.
  6907. * });
  6908. * ```
  6909. *
  6910. * Since the returned value of calling the $http function is a `promise`, you can also use
  6911. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6912. * an object representing the response. See the API signature and type info below for more
  6913. * details.
  6914. *
  6915. * A response status code between 200 and 299 is considered a success status and
  6916. * will result in the success callback being called. Note that if the response is a redirect,
  6917. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6918. * called for such responses.
  6919. *
  6920. * # Writing Unit Tests that use $http
  6921. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6922. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6923. * request using trained responses.
  6924. *
  6925. * ```
  6926. * $httpBackend.expectGET(...);
  6927. * $http.get(...);
  6928. * $httpBackend.flush();
  6929. * ```
  6930. *
  6931. * # Shortcut methods
  6932. *
  6933. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6934. * request data must be passed in for POST/PUT requests.
  6935. *
  6936. * ```js
  6937. * $http.get('/someUrl').success(successCallback);
  6938. * $http.post('/someUrl', data).success(successCallback);
  6939. * ```
  6940. *
  6941. * Complete list of shortcut methods:
  6942. *
  6943. * - {@link ng.$http#get $http.get}
  6944. * - {@link ng.$http#head $http.head}
  6945. * - {@link ng.$http#post $http.post}
  6946. * - {@link ng.$http#put $http.put}
  6947. * - {@link ng.$http#delete $http.delete}
  6948. * - {@link ng.$http#jsonp $http.jsonp}
  6949. * - {@link ng.$http#patch $http.patch}
  6950. *
  6951. *
  6952. * # Setting HTTP Headers
  6953. *
  6954. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6955. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6956. * object, which currently contains this default configuration:
  6957. *
  6958. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6959. * - `Accept: application/json, text/plain, * / *`
  6960. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6961. * - `Content-Type: application/json`
  6962. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6963. * - `Content-Type: application/json`
  6964. *
  6965. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6966. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6967. * with the lowercased HTTP method name as the key, e.g.
  6968. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6969. *
  6970. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6971. * fashion. For example:
  6972. *
  6973. * ```
  6974. * module.run(function($http) {
  6975. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6976. * });
  6977. * ```
  6978. *
  6979. * In addition, you can supply a `headers` property in the config object passed when
  6980. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6981. *
  6982. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  6983. * Use the `headers` property, setting the desired header to `undefined`. For example:
  6984. *
  6985. * ```js
  6986. * var req = {
  6987. * method: 'POST',
  6988. * url: 'http://example.com',
  6989. * headers: {
  6990. * 'Content-Type': undefined
  6991. * },
  6992. * data: { test: 'test' },
  6993. * }
  6994. *
  6995. * $http(req).success(function(){...}).error(function(){...});
  6996. * ```
  6997. *
  6998. * # Transforming Requests and Responses
  6999. *
  7000. * Both requests and responses can be transformed using transform functions. By default, Angular
  7001. * applies these transformations:
  7002. *
  7003. * Request transformations:
  7004. *
  7005. * - If the `data` property of the request configuration object contains an object, serialize it
  7006. * into JSON format.
  7007. *
  7008. * Response transformations:
  7009. *
  7010. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  7011. * - If JSON response is detected, deserialize it using a JSON parser.
  7012. *
  7013. * To globally augment or override the default transforms, modify the
  7014. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  7015. * properties. These properties are by default an array of transform functions, which allows you
  7016. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  7017. * also decide to completely override any default transformations by assigning your
  7018. * transformation functions to these properties directly without the array wrapper. These defaults
  7019. * are again available on the $http factory at run-time, which may be useful if you have run-time
  7020. * services you wish to be involved in your transformations.
  7021. *
  7022. * Similarly, to locally override the request/response transforms, augment the
  7023. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  7024. * into `$http`.
  7025. *
  7026. *
  7027. * # Caching
  7028. *
  7029. * To enable caching, set the request configuration `cache` property to `true` (to use default
  7030. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  7031. * When the cache is enabled, `$http` stores the response from the server in the specified
  7032. * cache. The next time the same request is made, the response is served from the cache without
  7033. * sending a request to the server.
  7034. *
  7035. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  7036. * the same way that real requests are.
  7037. *
  7038. * If there are multiple GET requests for the same URL that should be cached using the same
  7039. * cache, but the cache is not populated yet, only one request to the server will be made and
  7040. * the remaining requests will be fulfilled using the response from the first request.
  7041. *
  7042. * You can change the default cache to a new object (built with
  7043. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  7044. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  7045. * their `cache` property to `true` will now use this cache object.
  7046. *
  7047. * If you set the default cache to `false` then only requests that specify their own custom
  7048. * cache object will be cached.
  7049. *
  7050. * # Interceptors
  7051. *
  7052. * Before you start creating interceptors, be sure to understand the
  7053. * {@link ng.$q $q and deferred/promise APIs}.
  7054. *
  7055. * For purposes of global error handling, authentication, or any kind of synchronous or
  7056. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  7057. * able to intercept requests before they are handed to the server and
  7058. * responses before they are handed over to the application code that
  7059. * initiated these requests. The interceptors leverage the {@link ng.$q
  7060. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  7061. *
  7062. * The interceptors are service factories that are registered with the `$httpProvider` by
  7063. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  7064. * injected with dependencies (if specified) and returns the interceptor.
  7065. *
  7066. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  7067. *
  7068. * * `request`: interceptors get called with a http `config` object. The function is free to
  7069. * modify the `config` object or create a new one. The function needs to return the `config`
  7070. * object directly, or a promise containing the `config` or a new `config` object.
  7071. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  7072. * resolved with a rejection.
  7073. * * `response`: interceptors get called with http `response` object. The function is free to
  7074. * modify the `response` object or create a new one. The function needs to return the `response`
  7075. * object directly, or as a promise containing the `response` or a new `response` object.
  7076. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  7077. * resolved with a rejection.
  7078. *
  7079. *
  7080. * ```js
  7081. * // register the interceptor as a service
  7082. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7083. * return {
  7084. * // optional method
  7085. * 'request': function(config) {
  7086. * // do something on success
  7087. * return config;
  7088. * },
  7089. *
  7090. * // optional method
  7091. * 'requestError': function(rejection) {
  7092. * // do something on error
  7093. * if (canRecover(rejection)) {
  7094. * return responseOrNewPromise
  7095. * }
  7096. * return $q.reject(rejection);
  7097. * },
  7098. *
  7099. *
  7100. *
  7101. * // optional method
  7102. * 'response': function(response) {
  7103. * // do something on success
  7104. * return response;
  7105. * },
  7106. *
  7107. * // optional method
  7108. * 'responseError': function(rejection) {
  7109. * // do something on error
  7110. * if (canRecover(rejection)) {
  7111. * return responseOrNewPromise
  7112. * }
  7113. * return $q.reject(rejection);
  7114. * }
  7115. * };
  7116. * });
  7117. *
  7118. * $httpProvider.interceptors.push('myHttpInterceptor');
  7119. *
  7120. *
  7121. * // alternatively, register the interceptor via an anonymous factory
  7122. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  7123. * return {
  7124. * 'request': function(config) {
  7125. * // same as above
  7126. * },
  7127. *
  7128. * 'response': function(response) {
  7129. * // same as above
  7130. * }
  7131. * };
  7132. * });
  7133. * ```
  7134. *
  7135. * # Response interceptors (DEPRECATED)
  7136. *
  7137. * Before you start creating interceptors, be sure to understand the
  7138. * {@link ng.$q $q and deferred/promise APIs}.
  7139. *
  7140. * For purposes of global error handling, authentication or any kind of synchronous or
  7141. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  7142. * responses for http requests before they are handed over to the application code that
  7143. * initiated these requests. The response interceptors leverage the {@link ng.$q
  7144. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  7145. *
  7146. * The interceptors are service factories that are registered with the $httpProvider by
  7147. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  7148. * injected with dependencies (if specified) and returns the interceptor — a function that
  7149. * takes a {@link ng.$q promise} and returns the original or a new promise.
  7150. *
  7151. * ```js
  7152. * // register the interceptor as a service
  7153. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7154. * return function(promise) {
  7155. * return promise.then(function(response) {
  7156. * // do something on success
  7157. * return response;
  7158. * }, function(response) {
  7159. * // do something on error
  7160. * if (canRecover(response)) {
  7161. * return responseOrNewPromise
  7162. * }
  7163. * return $q.reject(response);
  7164. * });
  7165. * }
  7166. * });
  7167. *
  7168. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  7169. *
  7170. *
  7171. * // register the interceptor via an anonymous factory
  7172. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  7173. * return function(promise) {
  7174. * // same as above
  7175. * }
  7176. * });
  7177. * ```
  7178. *
  7179. *
  7180. * # Security Considerations
  7181. *
  7182. * When designing web applications, consider security threats from:
  7183. *
  7184. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7185. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  7186. *
  7187. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  7188. * pre-configured with strategies that address these issues, but for this to work backend server
  7189. * cooperation is required.
  7190. *
  7191. * ## JSON Vulnerability Protection
  7192. *
  7193. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7194. * allows third party website to turn your JSON resource URL into
  7195. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  7196. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  7197. * Angular will automatically strip the prefix before processing it as JSON.
  7198. *
  7199. * For example if your server needs to return:
  7200. * ```js
  7201. * ['one','two']
  7202. * ```
  7203. *
  7204. * which is vulnerable to attack, your server can return:
  7205. * ```js
  7206. * )]}',
  7207. * ['one','two']
  7208. * ```
  7209. *
  7210. * Angular will strip the prefix, before processing the JSON.
  7211. *
  7212. *
  7213. * ## Cross Site Request Forgery (XSRF) Protection
  7214. *
  7215. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  7216. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  7217. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  7218. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  7219. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  7220. * the XHR came from JavaScript running on your domain. The header will not be set for
  7221. * cross-domain requests.
  7222. *
  7223. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7224. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7225. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7226. * that only JavaScript running on your domain could have sent the request. The token must be
  7227. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7228. * making up its own tokens). We recommend that the token is a digest of your site's
  7229. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  7230. * for added security.
  7231. *
  7232. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7233. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7234. * or the per-request config object.
  7235. *
  7236. *
  7237. * @param {object} config Object describing the request to be made and how it should be
  7238. * processed. The object has following properties:
  7239. *
  7240. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7241. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7242. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7243. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7244. * JSONified.
  7245. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7246. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7247. * HTTP headers to send to the server. If the return value of a function is null, the
  7248. * header will not be sent.
  7249. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7250. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7251. * - **transformRequest** –
  7252. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7253. * transform function or an array of such functions. The transform function takes the http
  7254. * request body and headers and returns its transformed (typically serialized) version.
  7255. * - **transformResponse** –
  7256. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7257. * transform function or an array of such functions. The transform function takes the http
  7258. * response body and headers and returns its transformed (typically deserialized) version.
  7259. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7260. * GET request, otherwise if a cache instance built with
  7261. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7262. * caching.
  7263. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7264. * that should abort the request when resolved.
  7265. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  7266. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  7267. * for more information.
  7268. * - **responseType** - `{string}` - see
  7269. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7270. *
  7271. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7272. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7273. * method takes two arguments a success and an error callback which will be called with a
  7274. * response object. The `success` and `error` methods take a single argument - a function that
  7275. * will be called when the request succeeds or fails respectively. The arguments passed into
  7276. * these functions are destructured representation of the response object passed into the
  7277. * `then` method. The response object has these properties:
  7278. *
  7279. * - **data** – `{string|Object}` – The response body transformed with the transform
  7280. * functions.
  7281. * - **status** – `{number}` – HTTP status code of the response.
  7282. * - **headers** – `{function([headerName])}` – Header getter function.
  7283. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7284. * - **statusText** – `{string}` – HTTP status text of the response.
  7285. *
  7286. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7287. * requests. This is primarily meant to be used for debugging purposes.
  7288. *
  7289. *
  7290. * @example
  7291. <example module="httpExample">
  7292. <file name="index.html">
  7293. <div ng-controller="FetchController">
  7294. <select ng-model="method">
  7295. <option>GET</option>
  7296. <option>JSONP</option>
  7297. </select>
  7298. <input type="text" ng-model="url" size="80"/>
  7299. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7300. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7301. <button id="samplejsonpbtn"
  7302. ng-click="updateModel('JSONP',
  7303. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7304. Sample JSONP
  7305. </button>
  7306. <button id="invalidjsonpbtn"
  7307. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7308. Invalid JSONP
  7309. </button>
  7310. <pre>http status code: {{status}}</pre>
  7311. <pre>http response data: {{data}}</pre>
  7312. </div>
  7313. </file>
  7314. <file name="script.js">
  7315. angular.module('httpExample', [])
  7316. .controller('FetchController', ['$scope', '$http', '$templateCache',
  7317. function($scope, $http, $templateCache) {
  7318. $scope.method = 'GET';
  7319. $scope.url = 'http-hello.html';
  7320. $scope.fetch = function() {
  7321. $scope.code = null;
  7322. $scope.response = null;
  7323. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7324. success(function(data, status) {
  7325. $scope.status = status;
  7326. $scope.data = data;
  7327. }).
  7328. error(function(data, status) {
  7329. $scope.data = data || "Request failed";
  7330. $scope.status = status;
  7331. });
  7332. };
  7333. $scope.updateModel = function(method, url) {
  7334. $scope.method = method;
  7335. $scope.url = url;
  7336. };
  7337. }]);
  7338. </file>
  7339. <file name="http-hello.html">
  7340. Hello, $http!
  7341. </file>
  7342. <file name="protractor.js" type="protractor">
  7343. var status = element(by.binding('status'));
  7344. var data = element(by.binding('data'));
  7345. var fetchBtn = element(by.id('fetchbtn'));
  7346. var sampleGetBtn = element(by.id('samplegetbtn'));
  7347. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7348. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7349. it('should make an xhr GET request', function() {
  7350. sampleGetBtn.click();
  7351. fetchBtn.click();
  7352. expect(status.getText()).toMatch('200');
  7353. expect(data.getText()).toMatch(/Hello, \$http!/);
  7354. });
  7355. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  7356. // it('should make a JSONP request to angularjs.org', function() {
  7357. // sampleJsonpBtn.click();
  7358. // fetchBtn.click();
  7359. // expect(status.getText()).toMatch('200');
  7360. // expect(data.getText()).toMatch(/Super Hero!/);
  7361. // });
  7362. it('should make JSONP request to invalid URL and invoke the error handler',
  7363. function() {
  7364. invalidJsonpBtn.click();
  7365. fetchBtn.click();
  7366. expect(status.getText()).toMatch('0');
  7367. expect(data.getText()).toMatch('Request failed');
  7368. });
  7369. </file>
  7370. </example>
  7371. */
  7372. function $http(requestConfig) {
  7373. var config = {
  7374. method: 'get',
  7375. transformRequest: defaults.transformRequest,
  7376. transformResponse: defaults.transformResponse
  7377. };
  7378. var headers = mergeHeaders(requestConfig);
  7379. extend(config, requestConfig);
  7380. config.headers = headers;
  7381. config.method = uppercase(config.method);
  7382. var serverRequest = function(config) {
  7383. headers = config.headers;
  7384. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7385. // strip content-type if data is undefined
  7386. if (isUndefined(reqData)) {
  7387. forEach(headers, function(value, header) {
  7388. if (lowercase(header) === 'content-type') {
  7389. delete headers[header];
  7390. }
  7391. });
  7392. }
  7393. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7394. config.withCredentials = defaults.withCredentials;
  7395. }
  7396. // send request
  7397. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7398. };
  7399. var chain = [serverRequest, undefined];
  7400. var promise = $q.when(config);
  7401. // apply interceptors
  7402. forEach(reversedInterceptors, function(interceptor) {
  7403. if (interceptor.request || interceptor.requestError) {
  7404. chain.unshift(interceptor.request, interceptor.requestError);
  7405. }
  7406. if (interceptor.response || interceptor.responseError) {
  7407. chain.push(interceptor.response, interceptor.responseError);
  7408. }
  7409. });
  7410. while(chain.length) {
  7411. var thenFn = chain.shift();
  7412. var rejectFn = chain.shift();
  7413. promise = promise.then(thenFn, rejectFn);
  7414. }
  7415. promise.success = function(fn) {
  7416. promise.then(function(response) {
  7417. fn(response.data, response.status, response.headers, config);
  7418. });
  7419. return promise;
  7420. };
  7421. promise.error = function(fn) {
  7422. promise.then(null, function(response) {
  7423. fn(response.data, response.status, response.headers, config);
  7424. });
  7425. return promise;
  7426. };
  7427. return promise;
  7428. function transformResponse(response) {
  7429. // make a copy since the response must be cacheable
  7430. var resp = extend({}, response, {
  7431. data: transformData(response.data, response.headers, config.transformResponse)
  7432. });
  7433. return (isSuccess(response.status))
  7434. ? resp
  7435. : $q.reject(resp);
  7436. }
  7437. function mergeHeaders(config) {
  7438. var defHeaders = defaults.headers,
  7439. reqHeaders = extend({}, config.headers),
  7440. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7441. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7442. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7443. defaultHeadersIteration:
  7444. for (defHeaderName in defHeaders) {
  7445. lowercaseDefHeaderName = lowercase(defHeaderName);
  7446. for (reqHeaderName in reqHeaders) {
  7447. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7448. continue defaultHeadersIteration;
  7449. }
  7450. }
  7451. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7452. }
  7453. // execute if header value is a function for merged headers
  7454. execHeaders(reqHeaders);
  7455. return reqHeaders;
  7456. function execHeaders(headers) {
  7457. var headerContent;
  7458. forEach(headers, function(headerFn, header) {
  7459. if (isFunction(headerFn)) {
  7460. headerContent = headerFn();
  7461. if (headerContent != null) {
  7462. headers[header] = headerContent;
  7463. } else {
  7464. delete headers[header];
  7465. }
  7466. }
  7467. });
  7468. }
  7469. }
  7470. }
  7471. $http.pendingRequests = [];
  7472. /**
  7473. * @ngdoc method
  7474. * @name $http#get
  7475. *
  7476. * @description
  7477. * Shortcut method to perform `GET` request.
  7478. *
  7479. * @param {string} url Relative or absolute URL specifying the destination of the request
  7480. * @param {Object=} config Optional configuration object
  7481. * @returns {HttpPromise} Future object
  7482. */
  7483. /**
  7484. * @ngdoc method
  7485. * @name $http#delete
  7486. *
  7487. * @description
  7488. * Shortcut method to perform `DELETE` request.
  7489. *
  7490. * @param {string} url Relative or absolute URL specifying the destination of the request
  7491. * @param {Object=} config Optional configuration object
  7492. * @returns {HttpPromise} Future object
  7493. */
  7494. /**
  7495. * @ngdoc method
  7496. * @name $http#head
  7497. *
  7498. * @description
  7499. * Shortcut method to perform `HEAD` request.
  7500. *
  7501. * @param {string} url Relative or absolute URL specifying the destination of the request
  7502. * @param {Object=} config Optional configuration object
  7503. * @returns {HttpPromise} Future object
  7504. */
  7505. /**
  7506. * @ngdoc method
  7507. * @name $http#jsonp
  7508. *
  7509. * @description
  7510. * Shortcut method to perform `JSONP` request.
  7511. *
  7512. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7513. * The name of the callback should be the string `JSON_CALLBACK`.
  7514. * @param {Object=} config Optional configuration object
  7515. * @returns {HttpPromise} Future object
  7516. */
  7517. createShortMethods('get', 'delete', 'head', 'jsonp');
  7518. /**
  7519. * @ngdoc method
  7520. * @name $http#post
  7521. *
  7522. * @description
  7523. * Shortcut method to perform `POST` request.
  7524. *
  7525. * @param {string} url Relative or absolute URL specifying the destination of the request
  7526. * @param {*} data Request content
  7527. * @param {Object=} config Optional configuration object
  7528. * @returns {HttpPromise} Future object
  7529. */
  7530. /**
  7531. * @ngdoc method
  7532. * @name $http#put
  7533. *
  7534. * @description
  7535. * Shortcut method to perform `PUT` request.
  7536. *
  7537. * @param {string} url Relative or absolute URL specifying the destination of the request
  7538. * @param {*} data Request content
  7539. * @param {Object=} config Optional configuration object
  7540. * @returns {HttpPromise} Future object
  7541. */
  7542. /**
  7543. * @ngdoc method
  7544. * @name $http#patch
  7545. *
  7546. * @description
  7547. * Shortcut method to perform `PATCH` request.
  7548. *
  7549. * @param {string} url Relative or absolute URL specifying the destination of the request
  7550. * @param {*} data Request content
  7551. * @param {Object=} config Optional configuration object
  7552. * @returns {HttpPromise} Future object
  7553. */
  7554. createShortMethodsWithData('post', 'put', 'patch');
  7555. /**
  7556. * @ngdoc property
  7557. * @name $http#defaults
  7558. *
  7559. * @description
  7560. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7561. * default headers, withCredentials as well as request and response transformations.
  7562. *
  7563. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7564. */
  7565. $http.defaults = defaults;
  7566. return $http;
  7567. function createShortMethods(names) {
  7568. forEach(arguments, function(name) {
  7569. $http[name] = function(url, config) {
  7570. return $http(extend(config || {}, {
  7571. method: name,
  7572. url: url
  7573. }));
  7574. };
  7575. });
  7576. }
  7577. function createShortMethodsWithData(name) {
  7578. forEach(arguments, function(name) {
  7579. $http[name] = function(url, data, config) {
  7580. return $http(extend(config || {}, {
  7581. method: name,
  7582. url: url,
  7583. data: data
  7584. }));
  7585. };
  7586. });
  7587. }
  7588. /**
  7589. * Makes the request.
  7590. *
  7591. * !!! ACCESSES CLOSURE VARS:
  7592. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7593. */
  7594. function sendReq(config, reqData, reqHeaders) {
  7595. var deferred = $q.defer(),
  7596. promise = deferred.promise,
  7597. cache,
  7598. cachedResp,
  7599. url = buildUrl(config.url, config.params);
  7600. $http.pendingRequests.push(config);
  7601. promise.then(removePendingReq, removePendingReq);
  7602. if ((config.cache || defaults.cache) && config.cache !== false &&
  7603. (config.method === 'GET' || config.method === 'JSONP')) {
  7604. cache = isObject(config.cache) ? config.cache
  7605. : isObject(defaults.cache) ? defaults.cache
  7606. : defaultCache;
  7607. }
  7608. if (cache) {
  7609. cachedResp = cache.get(url);
  7610. if (isDefined(cachedResp)) {
  7611. if (isPromiseLike(cachedResp)) {
  7612. // cached request has already been sent, but there is no response yet
  7613. cachedResp.then(removePendingReq, removePendingReq);
  7614. return cachedResp;
  7615. } else {
  7616. // serving from cache
  7617. if (isArray(cachedResp)) {
  7618. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  7619. } else {
  7620. resolvePromise(cachedResp, 200, {}, 'OK');
  7621. }
  7622. }
  7623. } else {
  7624. // put the promise for the non-transformed response into cache as a placeholder
  7625. cache.put(url, promise);
  7626. }
  7627. }
  7628. // if we won't have the response in cache, set the xsrf headers and
  7629. // send the request to the backend
  7630. if (isUndefined(cachedResp)) {
  7631. var xsrfValue = urlIsSameOrigin(config.url)
  7632. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7633. : undefined;
  7634. if (xsrfValue) {
  7635. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7636. }
  7637. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7638. config.withCredentials, config.responseType);
  7639. }
  7640. return promise;
  7641. /**
  7642. * Callback registered to $httpBackend():
  7643. * - caches the response if desired
  7644. * - resolves the raw $http promise
  7645. * - calls $apply
  7646. */
  7647. function done(status, response, headersString, statusText) {
  7648. if (cache) {
  7649. if (isSuccess(status)) {
  7650. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7651. } else {
  7652. // remove promise from the cache
  7653. cache.remove(url);
  7654. }
  7655. }
  7656. resolvePromise(response, status, headersString, statusText);
  7657. if (!$rootScope.$$phase) $rootScope.$apply();
  7658. }
  7659. /**
  7660. * Resolves the raw $http promise.
  7661. */
  7662. function resolvePromise(response, status, headers, statusText) {
  7663. // normalize internal statuses to 0
  7664. status = Math.max(status, 0);
  7665. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7666. data: response,
  7667. status: status,
  7668. headers: headersGetter(headers),
  7669. config: config,
  7670. statusText : statusText
  7671. });
  7672. }
  7673. function removePendingReq() {
  7674. var idx = indexOf($http.pendingRequests, config);
  7675. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7676. }
  7677. }
  7678. function buildUrl(url, params) {
  7679. if (!params) return url;
  7680. var parts = [];
  7681. forEachSorted(params, function(value, key) {
  7682. if (value === null || isUndefined(value)) return;
  7683. if (!isArray(value)) value = [value];
  7684. forEach(value, function(v) {
  7685. if (isObject(v)) {
  7686. if (isDate(v)){
  7687. v = v.toISOString();
  7688. } else {
  7689. v = toJson(v);
  7690. }
  7691. }
  7692. parts.push(encodeUriQuery(key) + '=' +
  7693. encodeUriQuery(v));
  7694. });
  7695. });
  7696. if(parts.length > 0) {
  7697. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7698. }
  7699. return url;
  7700. }
  7701. }];
  7702. }
  7703. function createXhr(method) {
  7704. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7705. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7706. //if it is available
  7707. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7708. !window.XMLHttpRequest)) {
  7709. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7710. } else if (window.XMLHttpRequest) {
  7711. return new window.XMLHttpRequest();
  7712. }
  7713. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7714. }
  7715. /**
  7716. * @ngdoc service
  7717. * @name $httpBackend
  7718. * @requires $window
  7719. * @requires $document
  7720. *
  7721. * @description
  7722. * HTTP backend used by the {@link ng.$http service} that delegates to
  7723. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7724. *
  7725. * You should never need to use this service directly, instead use the higher-level abstractions:
  7726. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7727. *
  7728. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7729. * $httpBackend} which can be trained with responses.
  7730. */
  7731. function $HttpBackendProvider() {
  7732. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7733. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7734. }];
  7735. }
  7736. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7737. var ABORTED = -1;
  7738. // TODO(vojta): fix the signature
  7739. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7740. var status;
  7741. $browser.$$incOutstandingRequestCount();
  7742. url = url || $browser.url();
  7743. if (lowercase(method) == 'jsonp') {
  7744. var callbackId = '_' + (callbacks.counter++).toString(36);
  7745. callbacks[callbackId] = function(data) {
  7746. callbacks[callbackId].data = data;
  7747. callbacks[callbackId].called = true;
  7748. };
  7749. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7750. callbackId, function(status, text) {
  7751. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  7752. callbacks[callbackId] = noop;
  7753. });
  7754. } else {
  7755. var xhr = createXhr(method);
  7756. xhr.open(method, url, true);
  7757. forEach(headers, function(value, key) {
  7758. if (isDefined(value)) {
  7759. xhr.setRequestHeader(key, value);
  7760. }
  7761. });
  7762. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7763. // response is in the cache. the promise api will ensure that to the app code the api is
  7764. // always async
  7765. xhr.onreadystatechange = function() {
  7766. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7767. // xhrs that are resolved while the app is in the background (see #5426).
  7768. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7769. // continuing
  7770. //
  7771. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7772. // Safari respectively.
  7773. if (xhr && xhr.readyState == 4) {
  7774. var responseHeaders = null,
  7775. response = null,
  7776. statusText = '';
  7777. if(status !== ABORTED) {
  7778. responseHeaders = xhr.getAllResponseHeaders();
  7779. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7780. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7781. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7782. }
  7783. // Accessing statusText on an aborted xhr object will
  7784. // throw an 'c00c023f error' in IE9 and lower, don't touch it.
  7785. if (!(status === ABORTED && msie < 10)) {
  7786. statusText = xhr.statusText;
  7787. }
  7788. completeRequest(callback,
  7789. status || xhr.status,
  7790. response,
  7791. responseHeaders,
  7792. statusText);
  7793. }
  7794. };
  7795. if (withCredentials) {
  7796. xhr.withCredentials = true;
  7797. }
  7798. if (responseType) {
  7799. try {
  7800. xhr.responseType = responseType;
  7801. } catch (e) {
  7802. // WebKit added support for the json responseType value on 09/03/2013
  7803. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7804. // known to throw when setting the value "json" as the response type. Other older
  7805. // browsers implementing the responseType
  7806. //
  7807. // The json response type can be ignored if not supported, because JSON payloads are
  7808. // parsed on the client-side regardless.
  7809. if (responseType !== 'json') {
  7810. throw e;
  7811. }
  7812. }
  7813. }
  7814. xhr.send(post || null);
  7815. }
  7816. if (timeout > 0) {
  7817. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7818. } else if (isPromiseLike(timeout)) {
  7819. timeout.then(timeoutRequest);
  7820. }
  7821. function timeoutRequest() {
  7822. status = ABORTED;
  7823. jsonpDone && jsonpDone();
  7824. xhr && xhr.abort();
  7825. }
  7826. function completeRequest(callback, status, response, headersString, statusText) {
  7827. // cancel timeout and subsequent timeout promise resolution
  7828. timeoutId && $browserDefer.cancel(timeoutId);
  7829. jsonpDone = xhr = null;
  7830. // fix status code when it is 0 (0 status is undocumented).
  7831. // Occurs when accessing file resources or on Android 4.1 stock browser
  7832. // while retrieving files from application cache.
  7833. if (status === 0) {
  7834. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7835. }
  7836. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7837. status = status === 1223 ? 204 : status;
  7838. statusText = statusText || '';
  7839. callback(status, response, headersString, statusText);
  7840. $browser.$$completeOutstandingRequest(noop);
  7841. }
  7842. };
  7843. function jsonpReq(url, callbackId, done) {
  7844. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7845. // - fetches local scripts via XHR and evals them
  7846. // - adds and immediately removes script elements from the document
  7847. var script = rawDocument.createElement('script'), callback = null;
  7848. script.type = "text/javascript";
  7849. script.src = url;
  7850. script.async = true;
  7851. callback = function(event) {
  7852. removeEventListenerFn(script, "load", callback);
  7853. removeEventListenerFn(script, "error", callback);
  7854. rawDocument.body.removeChild(script);
  7855. script = null;
  7856. var status = -1;
  7857. var text = "unknown";
  7858. if (event) {
  7859. if (event.type === "load" && !callbacks[callbackId].called) {
  7860. event = { type: "error" };
  7861. }
  7862. text = event.type;
  7863. status = event.type === "error" ? 404 : 200;
  7864. }
  7865. if (done) {
  7866. done(status, text);
  7867. }
  7868. };
  7869. addEventListenerFn(script, "load", callback);
  7870. addEventListenerFn(script, "error", callback);
  7871. if (msie <= 8) {
  7872. script.onreadystatechange = function() {
  7873. if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) {
  7874. script.onreadystatechange = null;
  7875. callback({
  7876. type: 'load'
  7877. });
  7878. }
  7879. };
  7880. }
  7881. rawDocument.body.appendChild(script);
  7882. return callback;
  7883. }
  7884. }
  7885. var $interpolateMinErr = minErr('$interpolate');
  7886. /**
  7887. * @ngdoc provider
  7888. * @name $interpolateProvider
  7889. * @kind function
  7890. *
  7891. * @description
  7892. *
  7893. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7894. *
  7895. * @example
  7896. <example module="customInterpolationApp">
  7897. <file name="index.html">
  7898. <script>
  7899. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7900. customInterpolationApp.config(function($interpolateProvider) {
  7901. $interpolateProvider.startSymbol('//');
  7902. $interpolateProvider.endSymbol('//');
  7903. });
  7904. customInterpolationApp.controller('DemoController', function() {
  7905. this.label = "This binding is brought you by // interpolation symbols.";
  7906. });
  7907. </script>
  7908. <div ng-app="App" ng-controller="DemoController as demo">
  7909. //demo.label//
  7910. </div>
  7911. </file>
  7912. <file name="protractor.js" type="protractor">
  7913. it('should interpolate binding with custom symbols', function() {
  7914. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7915. });
  7916. </file>
  7917. </example>
  7918. */
  7919. function $InterpolateProvider() {
  7920. var startSymbol = '{{';
  7921. var endSymbol = '}}';
  7922. /**
  7923. * @ngdoc method
  7924. * @name $interpolateProvider#startSymbol
  7925. * @description
  7926. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7927. *
  7928. * @param {string=} value new value to set the starting symbol to.
  7929. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7930. */
  7931. this.startSymbol = function(value){
  7932. if (value) {
  7933. startSymbol = value;
  7934. return this;
  7935. } else {
  7936. return startSymbol;
  7937. }
  7938. };
  7939. /**
  7940. * @ngdoc method
  7941. * @name $interpolateProvider#endSymbol
  7942. * @description
  7943. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7944. *
  7945. * @param {string=} value new value to set the ending symbol to.
  7946. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7947. */
  7948. this.endSymbol = function(value){
  7949. if (value) {
  7950. endSymbol = value;
  7951. return this;
  7952. } else {
  7953. return endSymbol;
  7954. }
  7955. };
  7956. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7957. var startSymbolLength = startSymbol.length,
  7958. endSymbolLength = endSymbol.length;
  7959. /**
  7960. * @ngdoc service
  7961. * @name $interpolate
  7962. * @kind function
  7963. *
  7964. * @requires $parse
  7965. * @requires $sce
  7966. *
  7967. * @description
  7968. *
  7969. * Compiles a string with markup into an interpolation function. This service is used by the
  7970. * HTML {@link ng.$compile $compile} service for data binding. See
  7971. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7972. * interpolation markup.
  7973. *
  7974. *
  7975. * ```js
  7976. * var $interpolate = ...; // injected
  7977. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7978. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7979. * ```
  7980. *
  7981. *
  7982. * @param {string} text The text with markup to interpolate.
  7983. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7984. * embedded expression in order to return an interpolation function. Strings with no
  7985. * embedded expression will return null for the interpolation function.
  7986. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7987. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7988. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7989. * provides Strict Contextual Escaping for details.
  7990. * @returns {function(context)} an interpolation function which is used to compute the
  7991. * interpolated string. The function has these parameters:
  7992. *
  7993. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7994. * against.
  7995. *
  7996. */
  7997. function $interpolate(text, mustHaveExpression, trustedContext) {
  7998. var startIndex,
  7999. endIndex,
  8000. index = 0,
  8001. parts = [],
  8002. length = text.length,
  8003. hasInterpolation = false,
  8004. fn,
  8005. exp,
  8006. concat = [];
  8007. while(index < length) {
  8008. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  8009. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  8010. (index != startIndex) && parts.push(text.substring(index, startIndex));
  8011. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  8012. fn.exp = exp;
  8013. index = endIndex + endSymbolLength;
  8014. hasInterpolation = true;
  8015. } else {
  8016. // we did not find anything, so we have to add the remainder to the parts array
  8017. (index != length) && parts.push(text.substring(index));
  8018. index = length;
  8019. }
  8020. }
  8021. if (!(length = parts.length)) {
  8022. // we added, nothing, must have been an empty string.
  8023. parts.push('');
  8024. length = 1;
  8025. }
  8026. // Concatenating expressions makes it hard to reason about whether some combination of
  8027. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  8028. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  8029. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  8030. // make it obvious that you bound the value to some user controlled value. This helps reduce
  8031. // the load when auditing for XSS issues.
  8032. if (trustedContext && parts.length > 1) {
  8033. throw $interpolateMinErr('noconcat',
  8034. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  8035. "interpolations that concatenate multiple expressions when a trusted value is " +
  8036. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  8037. }
  8038. if (!mustHaveExpression || hasInterpolation) {
  8039. concat.length = length;
  8040. fn = function(context) {
  8041. try {
  8042. for(var i = 0, ii = length, part; i<ii; i++) {
  8043. if (typeof (part = parts[i]) == 'function') {
  8044. part = part(context);
  8045. if (trustedContext) {
  8046. part = $sce.getTrusted(trustedContext, part);
  8047. } else {
  8048. part = $sce.valueOf(part);
  8049. }
  8050. if (part == null) { // null || undefined
  8051. part = '';
  8052. } else {
  8053. switch (typeof part) {
  8054. case 'string':
  8055. {
  8056. break;
  8057. }
  8058. case 'number':
  8059. {
  8060. part = '' + part;
  8061. break;
  8062. }
  8063. default:
  8064. {
  8065. part = toJson(part);
  8066. }
  8067. }
  8068. }
  8069. }
  8070. concat[i] = part;
  8071. }
  8072. return concat.join('');
  8073. }
  8074. catch(err) {
  8075. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  8076. err.toString());
  8077. $exceptionHandler(newErr);
  8078. }
  8079. };
  8080. fn.exp = text;
  8081. fn.parts = parts;
  8082. return fn;
  8083. }
  8084. }
  8085. /**
  8086. * @ngdoc method
  8087. * @name $interpolate#startSymbol
  8088. * @description
  8089. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  8090. *
  8091. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  8092. * the symbol.
  8093. *
  8094. * @returns {string} start symbol.
  8095. */
  8096. $interpolate.startSymbol = function() {
  8097. return startSymbol;
  8098. };
  8099. /**
  8100. * @ngdoc method
  8101. * @name $interpolate#endSymbol
  8102. * @description
  8103. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8104. *
  8105. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  8106. * the symbol.
  8107. *
  8108. * @returns {string} end symbol.
  8109. */
  8110. $interpolate.endSymbol = function() {
  8111. return endSymbol;
  8112. };
  8113. return $interpolate;
  8114. }];
  8115. }
  8116. function $IntervalProvider() {
  8117. this.$get = ['$rootScope', '$window', '$q',
  8118. function($rootScope, $window, $q) {
  8119. var intervals = {};
  8120. /**
  8121. * @ngdoc service
  8122. * @name $interval
  8123. *
  8124. * @description
  8125. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  8126. * milliseconds.
  8127. *
  8128. * The return value of registering an interval function is a promise. This promise will be
  8129. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  8130. * run indefinitely if `count` is not defined. The value of the notification will be the
  8131. * number of iterations that have run.
  8132. * To cancel an interval, call `$interval.cancel(promise)`.
  8133. *
  8134. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  8135. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  8136. * time.
  8137. *
  8138. * <div class="alert alert-warning">
  8139. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  8140. * with them. In particular they are not automatically destroyed when a controller's scope or a
  8141. * directive's element are destroyed.
  8142. * You should take this into consideration and make sure to always cancel the interval at the
  8143. * appropriate moment. See the example below for more details on how and when to do this.
  8144. * </div>
  8145. *
  8146. * @param {function()} fn A function that should be called repeatedly.
  8147. * @param {number} delay Number of milliseconds between each function call.
  8148. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  8149. * indefinitely.
  8150. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  8151. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  8152. * @returns {promise} A promise which will be notified on each iteration.
  8153. *
  8154. * @example
  8155. * <example module="intervalExample">
  8156. * <file name="index.html">
  8157. * <script>
  8158. * angular.module('intervalExample', [])
  8159. * .controller('ExampleController', ['$scope', '$interval',
  8160. * function($scope, $interval) {
  8161. * $scope.format = 'M/d/yy h:mm:ss a';
  8162. * $scope.blood_1 = 100;
  8163. * $scope.blood_2 = 120;
  8164. *
  8165. * var stop;
  8166. * $scope.fight = function() {
  8167. * // Don't start a new fight if we are already fighting
  8168. * if ( angular.isDefined(stop) ) return;
  8169. *
  8170. * stop = $interval(function() {
  8171. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  8172. * $scope.blood_1 = $scope.blood_1 - 3;
  8173. * $scope.blood_2 = $scope.blood_2 - 4;
  8174. * } else {
  8175. * $scope.stopFight();
  8176. * }
  8177. * }, 100);
  8178. * };
  8179. *
  8180. * $scope.stopFight = function() {
  8181. * if (angular.isDefined(stop)) {
  8182. * $interval.cancel(stop);
  8183. * stop = undefined;
  8184. * }
  8185. * };
  8186. *
  8187. * $scope.resetFight = function() {
  8188. * $scope.blood_1 = 100;
  8189. * $scope.blood_2 = 120;
  8190. * };
  8191. *
  8192. * $scope.$on('$destroy', function() {
  8193. * // Make sure that the interval is destroyed too
  8194. * $scope.stopFight();
  8195. * });
  8196. * }])
  8197. * // Register the 'myCurrentTime' directive factory method.
  8198. * // We inject $interval and dateFilter service since the factory method is DI.
  8199. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  8200. * function($interval, dateFilter) {
  8201. * // return the directive link function. (compile function not needed)
  8202. * return function(scope, element, attrs) {
  8203. * var format, // date format
  8204. * stopTime; // so that we can cancel the time updates
  8205. *
  8206. * // used to update the UI
  8207. * function updateTime() {
  8208. * element.text(dateFilter(new Date(), format));
  8209. * }
  8210. *
  8211. * // watch the expression, and update the UI on change.
  8212. * scope.$watch(attrs.myCurrentTime, function(value) {
  8213. * format = value;
  8214. * updateTime();
  8215. * });
  8216. *
  8217. * stopTime = $interval(updateTime, 1000);
  8218. *
  8219. * // listen on DOM destroy (removal) event, and cancel the next UI update
  8220. * // to prevent updating time after the DOM element was removed.
  8221. * element.bind('$destroy', function() {
  8222. * $interval.cancel(stopTime);
  8223. * });
  8224. * }
  8225. * }]);
  8226. * </script>
  8227. *
  8228. * <div>
  8229. * <div ng-controller="ExampleController">
  8230. * Date format: <input ng-model="format"> <hr/>
  8231. * Current time is: <span my-current-time="format"></span>
  8232. * <hr/>
  8233. * Blood 1 : <font color='red'>{{blood_1}}</font>
  8234. * Blood 2 : <font color='red'>{{blood_2}}</font>
  8235. * <button type="button" data-ng-click="fight()">Fight</button>
  8236. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  8237. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  8238. * </div>
  8239. * </div>
  8240. *
  8241. * </file>
  8242. * </example>
  8243. */
  8244. function interval(fn, delay, count, invokeApply) {
  8245. var setInterval = $window.setInterval,
  8246. clearInterval = $window.clearInterval,
  8247. deferred = $q.defer(),
  8248. promise = deferred.promise,
  8249. iteration = 0,
  8250. skipApply = (isDefined(invokeApply) && !invokeApply);
  8251. count = isDefined(count) ? count : 0;
  8252. promise.then(null, null, fn);
  8253. promise.$$intervalId = setInterval(function tick() {
  8254. deferred.notify(iteration++);
  8255. if (count > 0 && iteration >= count) {
  8256. deferred.resolve(iteration);
  8257. clearInterval(promise.$$intervalId);
  8258. delete intervals[promise.$$intervalId];
  8259. }
  8260. if (!skipApply) $rootScope.$apply();
  8261. }, delay);
  8262. intervals[promise.$$intervalId] = deferred;
  8263. return promise;
  8264. }
  8265. /**
  8266. * @ngdoc method
  8267. * @name $interval#cancel
  8268. *
  8269. * @description
  8270. * Cancels a task associated with the `promise`.
  8271. *
  8272. * @param {promise} promise returned by the `$interval` function.
  8273. * @returns {boolean} Returns `true` if the task was successfully canceled.
  8274. */
  8275. interval.cancel = function(promise) {
  8276. if (promise && promise.$$intervalId in intervals) {
  8277. intervals[promise.$$intervalId].reject('canceled');
  8278. $window.clearInterval(promise.$$intervalId);
  8279. delete intervals[promise.$$intervalId];
  8280. return true;
  8281. }
  8282. return false;
  8283. };
  8284. return interval;
  8285. }];
  8286. }
  8287. /**
  8288. * @ngdoc service
  8289. * @name $locale
  8290. *
  8291. * @description
  8292. * $locale service provides localization rules for various Angular components. As of right now the
  8293. * only public api is:
  8294. *
  8295. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8296. */
  8297. function $LocaleProvider(){
  8298. this.$get = function() {
  8299. return {
  8300. id: 'en-us',
  8301. NUMBER_FORMATS: {
  8302. DECIMAL_SEP: '.',
  8303. GROUP_SEP: ',',
  8304. PATTERNS: [
  8305. { // Decimal Pattern
  8306. minInt: 1,
  8307. minFrac: 0,
  8308. maxFrac: 3,
  8309. posPre: '',
  8310. posSuf: '',
  8311. negPre: '-',
  8312. negSuf: '',
  8313. gSize: 3,
  8314. lgSize: 3
  8315. },{ //Currency Pattern
  8316. minInt: 1,
  8317. minFrac: 2,
  8318. maxFrac: 2,
  8319. posPre: '\u00A4',
  8320. posSuf: '',
  8321. negPre: '(\u00A4',
  8322. negSuf: ')',
  8323. gSize: 3,
  8324. lgSize: 3
  8325. }
  8326. ],
  8327. CURRENCY_SYM: '$'
  8328. },
  8329. DATETIME_FORMATS: {
  8330. MONTH:
  8331. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8332. .split(','),
  8333. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8334. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8335. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8336. AMPMS: ['AM','PM'],
  8337. medium: 'MMM d, y h:mm:ss a',
  8338. short: 'M/d/yy h:mm a',
  8339. fullDate: 'EEEE, MMMM d, y',
  8340. longDate: 'MMMM d, y',
  8341. mediumDate: 'MMM d, y',
  8342. shortDate: 'M/d/yy',
  8343. mediumTime: 'h:mm:ss a',
  8344. shortTime: 'h:mm a'
  8345. },
  8346. pluralCat: function(num) {
  8347. if (num === 1) {
  8348. return 'one';
  8349. }
  8350. return 'other';
  8351. }
  8352. };
  8353. };
  8354. }
  8355. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8356. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8357. var $locationMinErr = minErr('$location');
  8358. /**
  8359. * Encode path using encodeUriSegment, ignoring forward slashes
  8360. *
  8361. * @param {string} path Path to encode
  8362. * @returns {string}
  8363. */
  8364. function encodePath(path) {
  8365. var segments = path.split('/'),
  8366. i = segments.length;
  8367. while (i--) {
  8368. segments[i] = encodeUriSegment(segments[i]);
  8369. }
  8370. return segments.join('/');
  8371. }
  8372. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8373. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8374. locationObj.$$protocol = parsedUrl.protocol;
  8375. locationObj.$$host = parsedUrl.hostname;
  8376. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8377. }
  8378. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8379. var prefixed = (relativeUrl.charAt(0) !== '/');
  8380. if (prefixed) {
  8381. relativeUrl = '/' + relativeUrl;
  8382. }
  8383. var match = urlResolve(relativeUrl, appBase);
  8384. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8385. match.pathname.substring(1) : match.pathname);
  8386. locationObj.$$search = parseKeyValue(match.search);
  8387. locationObj.$$hash = decodeURIComponent(match.hash);
  8388. // make sure path starts with '/';
  8389. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8390. locationObj.$$path = '/' + locationObj.$$path;
  8391. }
  8392. }
  8393. /**
  8394. *
  8395. * @param {string} begin
  8396. * @param {string} whole
  8397. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8398. * expected string.
  8399. */
  8400. function beginsWith(begin, whole) {
  8401. if (whole.indexOf(begin) === 0) {
  8402. return whole.substr(begin.length);
  8403. }
  8404. }
  8405. function stripHash(url) {
  8406. var index = url.indexOf('#');
  8407. return index == -1 ? url : url.substr(0, index);
  8408. }
  8409. function trimEmptyHash(url) {
  8410. return url.replace(/(#.+)|#$/, '$1');
  8411. }
  8412. function stripFile(url) {
  8413. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8414. }
  8415. /* return the server only (scheme://host:port) */
  8416. function serverBase(url) {
  8417. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8418. }
  8419. /**
  8420. * LocationHtml5Url represents an url
  8421. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8422. *
  8423. * @constructor
  8424. * @param {string} appBase application base URL
  8425. * @param {string} basePrefix url path prefix
  8426. */
  8427. function LocationHtml5Url(appBase, basePrefix) {
  8428. this.$$html5 = true;
  8429. basePrefix = basePrefix || '';
  8430. var appBaseNoFile = stripFile(appBase);
  8431. parseAbsoluteUrl(appBase, this, appBase);
  8432. /**
  8433. * Parse given html5 (regular) url string into properties
  8434. * @param {string} newAbsoluteUrl HTML5 url
  8435. * @private
  8436. */
  8437. this.$$parse = function(url) {
  8438. var pathUrl = beginsWith(appBaseNoFile, url);
  8439. if (!isString(pathUrl)) {
  8440. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8441. appBaseNoFile);
  8442. }
  8443. parseAppUrl(pathUrl, this, appBase);
  8444. if (!this.$$path) {
  8445. this.$$path = '/';
  8446. }
  8447. this.$$compose();
  8448. };
  8449. /**
  8450. * Compose url and update `absUrl` property
  8451. * @private
  8452. */
  8453. this.$$compose = function() {
  8454. var search = toKeyValue(this.$$search),
  8455. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8456. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8457. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8458. };
  8459. this.$$parseLinkUrl = function(url, relHref) {
  8460. var appUrl, prevAppUrl;
  8461. var rewrittenUrl;
  8462. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8463. prevAppUrl = appUrl;
  8464. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8465. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8466. } else {
  8467. rewrittenUrl = appBase + prevAppUrl;
  8468. }
  8469. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8470. rewrittenUrl = appBaseNoFile + appUrl;
  8471. } else if (appBaseNoFile == url + '/') {
  8472. rewrittenUrl = appBaseNoFile;
  8473. }
  8474. if (rewrittenUrl) {
  8475. this.$$parse(rewrittenUrl);
  8476. }
  8477. return !!rewrittenUrl;
  8478. };
  8479. }
  8480. /**
  8481. * LocationHashbangUrl represents url
  8482. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8483. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8484. *
  8485. * @constructor
  8486. * @param {string} appBase application base URL
  8487. * @param {string} hashPrefix hashbang prefix
  8488. */
  8489. function LocationHashbangUrl(appBase, hashPrefix) {
  8490. var appBaseNoFile = stripFile(appBase);
  8491. parseAbsoluteUrl(appBase, this, appBase);
  8492. /**
  8493. * Parse given hashbang url into properties
  8494. * @param {string} url Hashbang url
  8495. * @private
  8496. */
  8497. this.$$parse = function(url) {
  8498. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8499. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8500. ? beginsWith(hashPrefix, withoutBaseUrl)
  8501. : (this.$$html5)
  8502. ? withoutBaseUrl
  8503. : '';
  8504. if (!isString(withoutHashUrl)) {
  8505. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8506. hashPrefix);
  8507. }
  8508. parseAppUrl(withoutHashUrl, this, appBase);
  8509. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8510. this.$$compose();
  8511. /*
  8512. * In Windows, on an anchor node on documents loaded from
  8513. * the filesystem, the browser will return a pathname
  8514. * prefixed with the drive name ('/C:/path') when a
  8515. * pathname without a drive is set:
  8516. * * a.setAttribute('href', '/foo')
  8517. * * a.pathname === '/C:/foo' //true
  8518. *
  8519. * Inside of Angular, we're always using pathnames that
  8520. * do not include drive names for routing.
  8521. */
  8522. function removeWindowsDriveName (path, url, base) {
  8523. /*
  8524. Matches paths for file protocol on windows,
  8525. such as /C:/foo/bar, and captures only /foo/bar.
  8526. */
  8527. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  8528. var firstPathSegmentMatch;
  8529. //Get the relative path from the input URL.
  8530. if (url.indexOf(base) === 0) {
  8531. url = url.replace(base, '');
  8532. }
  8533. // The input URL intentionally contains a first path segment that ends with a colon.
  8534. if (windowsFilePathExp.exec(url)) {
  8535. return path;
  8536. }
  8537. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8538. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8539. }
  8540. };
  8541. /**
  8542. * Compose hashbang url and update `absUrl` property
  8543. * @private
  8544. */
  8545. this.$$compose = function() {
  8546. var search = toKeyValue(this.$$search),
  8547. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8548. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8549. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8550. };
  8551. this.$$parseLinkUrl = function(url, relHref) {
  8552. if(stripHash(appBase) == stripHash(url)) {
  8553. this.$$parse(url);
  8554. return true;
  8555. }
  8556. return false;
  8557. };
  8558. }
  8559. /**
  8560. * LocationHashbangUrl represents url
  8561. * This object is exposed as $location service when html5 history api is enabled but the browser
  8562. * does not support it.
  8563. *
  8564. * @constructor
  8565. * @param {string} appBase application base URL
  8566. * @param {string} hashPrefix hashbang prefix
  8567. */
  8568. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8569. this.$$html5 = true;
  8570. LocationHashbangUrl.apply(this, arguments);
  8571. var appBaseNoFile = stripFile(appBase);
  8572. this.$$parseLinkUrl = function(url, relHref) {
  8573. var rewrittenUrl;
  8574. var appUrl;
  8575. if ( appBase == stripHash(url) ) {
  8576. rewrittenUrl = url;
  8577. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8578. rewrittenUrl = appBase + hashPrefix + appUrl;
  8579. } else if ( appBaseNoFile === url + '/') {
  8580. rewrittenUrl = appBaseNoFile;
  8581. }
  8582. if (rewrittenUrl) {
  8583. this.$$parse(rewrittenUrl);
  8584. }
  8585. return !!rewrittenUrl;
  8586. };
  8587. this.$$compose = function() {
  8588. var search = toKeyValue(this.$$search),
  8589. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8590. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8591. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  8592. this.$$absUrl = appBase + hashPrefix + this.$$url;
  8593. };
  8594. }
  8595. LocationHashbangInHtml5Url.prototype =
  8596. LocationHashbangUrl.prototype =
  8597. LocationHtml5Url.prototype = {
  8598. /**
  8599. * Are we in html5 mode?
  8600. * @private
  8601. */
  8602. $$html5: false,
  8603. /**
  8604. * Has any change been replacing ?
  8605. * @private
  8606. */
  8607. $$replace: false,
  8608. /**
  8609. * @ngdoc method
  8610. * @name $location#absUrl
  8611. *
  8612. * @description
  8613. * This method is getter only.
  8614. *
  8615. * Return full url representation with all segments encoded according to rules specified in
  8616. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8617. *
  8618. * @return {string} full url
  8619. */
  8620. absUrl: locationGetter('$$absUrl'),
  8621. /**
  8622. * @ngdoc method
  8623. * @name $location#url
  8624. *
  8625. * @description
  8626. * This method is getter / setter.
  8627. *
  8628. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8629. *
  8630. * Change path, search and hash, when called with parameter and return `$location`.
  8631. *
  8632. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8633. * @return {string} url
  8634. */
  8635. url: function(url) {
  8636. if (isUndefined(url))
  8637. return this.$$url;
  8638. var match = PATH_MATCH.exec(url);
  8639. if (match[1]) this.path(decodeURIComponent(match[1]));
  8640. if (match[2] || match[1]) this.search(match[3] || '');
  8641. this.hash(match[5] || '');
  8642. return this;
  8643. },
  8644. /**
  8645. * @ngdoc method
  8646. * @name $location#protocol
  8647. *
  8648. * @description
  8649. * This method is getter only.
  8650. *
  8651. * Return protocol of current url.
  8652. *
  8653. * @return {string} protocol of current url
  8654. */
  8655. protocol: locationGetter('$$protocol'),
  8656. /**
  8657. * @ngdoc method
  8658. * @name $location#host
  8659. *
  8660. * @description
  8661. * This method is getter only.
  8662. *
  8663. * Return host of current url.
  8664. *
  8665. * @return {string} host of current url.
  8666. */
  8667. host: locationGetter('$$host'),
  8668. /**
  8669. * @ngdoc method
  8670. * @name $location#port
  8671. *
  8672. * @description
  8673. * This method is getter only.
  8674. *
  8675. * Return port of current url.
  8676. *
  8677. * @return {Number} port
  8678. */
  8679. port: locationGetter('$$port'),
  8680. /**
  8681. * @ngdoc method
  8682. * @name $location#path
  8683. *
  8684. * @description
  8685. * This method is getter / setter.
  8686. *
  8687. * Return path of current url when called without any parameter.
  8688. *
  8689. * Change path when called with parameter and return `$location`.
  8690. *
  8691. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8692. * if it is missing.
  8693. *
  8694. * @param {(string|number)=} path New path
  8695. * @return {string} path
  8696. */
  8697. path: locationGetterSetter('$$path', function(path) {
  8698. path = path !== null ? path.toString() : '';
  8699. return path.charAt(0) == '/' ? path : '/' + path;
  8700. }),
  8701. /**
  8702. * @ngdoc method
  8703. * @name $location#search
  8704. *
  8705. * @description
  8706. * This method is getter / setter.
  8707. *
  8708. * Return search part (as object) of current url when called without any parameter.
  8709. *
  8710. * Change search part when called with parameter and return `$location`.
  8711. *
  8712. *
  8713. * ```js
  8714. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  8715. * var searchObject = $location.search();
  8716. * // => {foo: 'bar', baz: 'xoxo'}
  8717. *
  8718. *
  8719. * // set foo to 'yipee'
  8720. * $location.search('foo', 'yipee');
  8721. * // => $location
  8722. * ```
  8723. *
  8724. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8725. * hash object.
  8726. *
  8727. * When called with a single argument the method acts as a setter, setting the `search` component
  8728. * of `$location` to the specified value.
  8729. *
  8730. * If the argument is a hash object containing an array of values, these values will be encoded
  8731. * as duplicate search parameters in the url.
  8732. *
  8733. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  8734. * will override only a single search property.
  8735. *
  8736. * If `paramValue` is an array, it will override the property of the `search` component of
  8737. * `$location` specified via the first argument.
  8738. *
  8739. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  8740. *
  8741. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  8742. * value nor trailing equal sign.
  8743. *
  8744. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  8745. * one or more arguments returns `$location` object itself.
  8746. */
  8747. search: function(search, paramValue) {
  8748. switch (arguments.length) {
  8749. case 0:
  8750. return this.$$search;
  8751. case 1:
  8752. if (isString(search) || isNumber(search)) {
  8753. search = search.toString();
  8754. this.$$search = parseKeyValue(search);
  8755. } else if (isObject(search)) {
  8756. // remove object undefined or null properties
  8757. forEach(search, function(value, key) {
  8758. if (value == null) delete search[key];
  8759. });
  8760. this.$$search = search;
  8761. } else {
  8762. throw $locationMinErr('isrcharg',
  8763. 'The first argument of the `$location#search()` call must be a string or an object.');
  8764. }
  8765. break;
  8766. default:
  8767. if (isUndefined(paramValue) || paramValue === null) {
  8768. delete this.$$search[search];
  8769. } else {
  8770. this.$$search[search] = paramValue;
  8771. }
  8772. }
  8773. this.$$compose();
  8774. return this;
  8775. },
  8776. /**
  8777. * @ngdoc method
  8778. * @name $location#hash
  8779. *
  8780. * @description
  8781. * This method is getter / setter.
  8782. *
  8783. * Return hash fragment when called without any parameter.
  8784. *
  8785. * Change hash fragment when called with parameter and return `$location`.
  8786. *
  8787. * @param {(string|number)=} hash New hash fragment
  8788. * @return {string} hash
  8789. */
  8790. hash: locationGetterSetter('$$hash', function(hash) {
  8791. return hash !== null ? hash.toString() : '';
  8792. }),
  8793. /**
  8794. * @ngdoc method
  8795. * @name $location#replace
  8796. *
  8797. * @description
  8798. * If called, all changes to $location during current `$digest` will be replacing current history
  8799. * record, instead of adding new one.
  8800. */
  8801. replace: function() {
  8802. this.$$replace = true;
  8803. return this;
  8804. }
  8805. };
  8806. function locationGetter(property) {
  8807. return function() {
  8808. return this[property];
  8809. };
  8810. }
  8811. function locationGetterSetter(property, preprocess) {
  8812. return function(value) {
  8813. if (isUndefined(value))
  8814. return this[property];
  8815. this[property] = preprocess(value);
  8816. this.$$compose();
  8817. return this;
  8818. };
  8819. }
  8820. /**
  8821. * @ngdoc service
  8822. * @name $location
  8823. *
  8824. * @requires $rootElement
  8825. *
  8826. * @description
  8827. * The $location service parses the URL in the browser address bar (based on the
  8828. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8829. * available to your application. Changes to the URL in the address bar are reflected into
  8830. * $location service and changes to $location are reflected into the browser address bar.
  8831. *
  8832. * **The $location service:**
  8833. *
  8834. * - Exposes the current URL in the browser address bar, so you can
  8835. * - Watch and observe the URL.
  8836. * - Change the URL.
  8837. * - Synchronizes the URL with the browser when the user
  8838. * - Changes the address bar.
  8839. * - Clicks the back or forward button (or clicks a History link).
  8840. * - Clicks on a link.
  8841. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8842. *
  8843. * For more information see {@link guide/$location Developer Guide: Using $location}
  8844. */
  8845. /**
  8846. * @ngdoc provider
  8847. * @name $locationProvider
  8848. * @description
  8849. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8850. */
  8851. function $LocationProvider(){
  8852. var hashPrefix = '',
  8853. html5Mode = false;
  8854. /**
  8855. * @ngdoc method
  8856. * @name $locationProvider#hashPrefix
  8857. * @description
  8858. * @param {string=} prefix Prefix for hash part (containing path and search)
  8859. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8860. */
  8861. this.hashPrefix = function(prefix) {
  8862. if (isDefined(prefix)) {
  8863. hashPrefix = prefix;
  8864. return this;
  8865. } else {
  8866. return hashPrefix;
  8867. }
  8868. };
  8869. /**
  8870. * @ngdoc method
  8871. * @name $locationProvider#html5Mode
  8872. * @description
  8873. * @param {boolean=} mode Use HTML5 strategy if available.
  8874. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8875. */
  8876. this.html5Mode = function(mode) {
  8877. if (isDefined(mode)) {
  8878. html5Mode = mode;
  8879. return this;
  8880. } else {
  8881. return html5Mode;
  8882. }
  8883. };
  8884. /**
  8885. * @ngdoc event
  8886. * @name $location#$locationChangeStart
  8887. * @eventType broadcast on root scope
  8888. * @description
  8889. * Broadcasted before a URL will change. This change can be prevented by calling
  8890. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8891. * details about event object. Upon successful change
  8892. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8893. *
  8894. * @param {Object} angularEvent Synthetic event object.
  8895. * @param {string} newUrl New URL
  8896. * @param {string=} oldUrl URL that was before it was changed.
  8897. */
  8898. /**
  8899. * @ngdoc event
  8900. * @name $location#$locationChangeSuccess
  8901. * @eventType broadcast on root scope
  8902. * @description
  8903. * Broadcasted after a URL was changed.
  8904. *
  8905. * @param {Object} angularEvent Synthetic event object.
  8906. * @param {string} newUrl New URL
  8907. * @param {string=} oldUrl URL that was before it was changed.
  8908. */
  8909. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8910. function( $rootScope, $browser, $sniffer, $rootElement) {
  8911. var $location,
  8912. LocationMode,
  8913. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8914. initialUrl = $browser.url(),
  8915. appBase;
  8916. if (html5Mode) {
  8917. appBase = serverBase(initialUrl) + (baseHref || '/');
  8918. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8919. } else {
  8920. appBase = stripHash(initialUrl);
  8921. LocationMode = LocationHashbangUrl;
  8922. }
  8923. $location = new LocationMode(appBase, '#' + hashPrefix);
  8924. $location.$$parseLinkUrl(initialUrl, initialUrl);
  8925. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  8926. $rootElement.on('click', function(event) {
  8927. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8928. // currently we open nice url link and redirect then
  8929. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8930. var elm = jqLite(event.target);
  8931. // traverse the DOM up to find first A tag
  8932. while (lowercase(elm[0].nodeName) !== 'a') {
  8933. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8934. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8935. }
  8936. var absHref = elm.prop('href');
  8937. // get the actual href attribute - see
  8938. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  8939. var relHref = elm.attr('href') || elm.attr('xlink:href');
  8940. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8941. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8942. // an animation.
  8943. absHref = urlResolve(absHref.animVal).href;
  8944. }
  8945. // Ignore when url is started with javascript: or mailto:
  8946. if (IGNORE_URI_REGEXP.test(absHref)) return;
  8947. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  8948. if ($location.$$parseLinkUrl(absHref, relHref)) {
  8949. // We do a preventDefault for all urls that are part of the angular application,
  8950. // in html5mode and also without, so that we are able to abort navigation without
  8951. // getting double entries in the location history.
  8952. event.preventDefault();
  8953. // update location manually
  8954. if ($location.absUrl() != $browser.url()) {
  8955. $rootScope.$apply();
  8956. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8957. window.angular['ff-684208-preventDefault'] = true;
  8958. }
  8959. }
  8960. }
  8961. });
  8962. // rewrite hashbang url <> html5 url
  8963. if ($location.absUrl() != initialUrl) {
  8964. $browser.url($location.absUrl(), true);
  8965. }
  8966. // update $location when $browser url changes
  8967. $browser.onUrlChange(function(newUrl) {
  8968. if ($location.absUrl() != newUrl) {
  8969. $rootScope.$evalAsync(function() {
  8970. var oldUrl = $location.absUrl();
  8971. $location.$$parse(newUrl);
  8972. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8973. oldUrl).defaultPrevented) {
  8974. $location.$$parse(oldUrl);
  8975. $browser.url(oldUrl);
  8976. } else {
  8977. afterLocationChange(oldUrl);
  8978. }
  8979. });
  8980. if (!$rootScope.$$phase) $rootScope.$digest();
  8981. }
  8982. });
  8983. // update browser
  8984. var changeCounter = 0;
  8985. $rootScope.$watch(function $locationWatch() {
  8986. var oldUrl = trimEmptyHash($browser.url());
  8987. var newUrl = trimEmptyHash($location.absUrl());
  8988. var currentReplace = $location.$$replace;
  8989. if (!changeCounter || oldUrl != newUrl) {
  8990. changeCounter++;
  8991. $rootScope.$evalAsync(function() {
  8992. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8993. defaultPrevented) {
  8994. $location.$$parse(oldUrl);
  8995. } else {
  8996. $browser.url($location.absUrl(), currentReplace);
  8997. afterLocationChange(oldUrl);
  8998. }
  8999. });
  9000. }
  9001. $location.$$replace = false;
  9002. return changeCounter;
  9003. });
  9004. return $location;
  9005. function afterLocationChange(oldUrl) {
  9006. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  9007. }
  9008. }];
  9009. }
  9010. /**
  9011. * @ngdoc service
  9012. * @name $log
  9013. * @requires $window
  9014. *
  9015. * @description
  9016. * Simple service for logging. Default implementation safely writes the message
  9017. * into the browser's console (if present).
  9018. *
  9019. * The main purpose of this service is to simplify debugging and troubleshooting.
  9020. *
  9021. * The default is to log `debug` messages. You can use
  9022. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  9023. *
  9024. * @example
  9025. <example module="logExample">
  9026. <file name="script.js">
  9027. angular.module('logExample', [])
  9028. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  9029. $scope.$log = $log;
  9030. $scope.message = 'Hello World!';
  9031. }]);
  9032. </file>
  9033. <file name="index.html">
  9034. <div ng-controller="LogController">
  9035. <p>Reload this page with open console, enter text and hit the log button...</p>
  9036. Message:
  9037. <input type="text" ng-model="message"/>
  9038. <button ng-click="$log.log(message)">log</button>
  9039. <button ng-click="$log.warn(message)">warn</button>
  9040. <button ng-click="$log.info(message)">info</button>
  9041. <button ng-click="$log.error(message)">error</button>
  9042. </div>
  9043. </file>
  9044. </example>
  9045. */
  9046. /**
  9047. * @ngdoc provider
  9048. * @name $logProvider
  9049. * @description
  9050. * Use the `$logProvider` to configure how the application logs messages
  9051. */
  9052. function $LogProvider(){
  9053. var debug = true,
  9054. self = this;
  9055. /**
  9056. * @ngdoc method
  9057. * @name $logProvider#debugEnabled
  9058. * @description
  9059. * @param {boolean=} flag enable or disable debug level messages
  9060. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9061. */
  9062. this.debugEnabled = function(flag) {
  9063. if (isDefined(flag)) {
  9064. debug = flag;
  9065. return this;
  9066. } else {
  9067. return debug;
  9068. }
  9069. };
  9070. this.$get = ['$window', function($window){
  9071. return {
  9072. /**
  9073. * @ngdoc method
  9074. * @name $log#log
  9075. *
  9076. * @description
  9077. * Write a log message
  9078. */
  9079. log: consoleLog('log'),
  9080. /**
  9081. * @ngdoc method
  9082. * @name $log#info
  9083. *
  9084. * @description
  9085. * Write an information message
  9086. */
  9087. info: consoleLog('info'),
  9088. /**
  9089. * @ngdoc method
  9090. * @name $log#warn
  9091. *
  9092. * @description
  9093. * Write a warning message
  9094. */
  9095. warn: consoleLog('warn'),
  9096. /**
  9097. * @ngdoc method
  9098. * @name $log#error
  9099. *
  9100. * @description
  9101. * Write an error message
  9102. */
  9103. error: consoleLog('error'),
  9104. /**
  9105. * @ngdoc method
  9106. * @name $log#debug
  9107. *
  9108. * @description
  9109. * Write a debug message
  9110. */
  9111. debug: (function () {
  9112. var fn = consoleLog('debug');
  9113. return function() {
  9114. if (debug) {
  9115. fn.apply(self, arguments);
  9116. }
  9117. };
  9118. }())
  9119. };
  9120. function formatError(arg) {
  9121. if (arg instanceof Error) {
  9122. if (arg.stack) {
  9123. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  9124. ? 'Error: ' + arg.message + '\n' + arg.stack
  9125. : arg.stack;
  9126. } else if (arg.sourceURL) {
  9127. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  9128. }
  9129. }
  9130. return arg;
  9131. }
  9132. function consoleLog(type) {
  9133. var console = $window.console || {},
  9134. logFn = console[type] || console.log || noop,
  9135. hasApply = false;
  9136. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  9137. // The reason behind this is that console.log has type "object" in IE8...
  9138. try {
  9139. hasApply = !!logFn.apply;
  9140. } catch (e) {}
  9141. if (hasApply) {
  9142. return function() {
  9143. var args = [];
  9144. forEach(arguments, function(arg) {
  9145. args.push(formatError(arg));
  9146. });
  9147. return logFn.apply(console, args);
  9148. };
  9149. }
  9150. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  9151. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  9152. return function(arg1, arg2) {
  9153. logFn(arg1, arg2 == null ? '' : arg2);
  9154. };
  9155. }
  9156. }];
  9157. }
  9158. var $parseMinErr = minErr('$parse');
  9159. var promiseWarningCache = {};
  9160. var promiseWarning;
  9161. // Sandboxing Angular Expressions
  9162. // ------------------------------
  9163. // Angular expressions are generally considered safe because these expressions only have direct
  9164. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  9165. // obtaining a reference to native JS functions such as the Function constructor.
  9166. //
  9167. // As an example, consider the following Angular expression:
  9168. //
  9169. // {}.toString.constructor('alert("evil JS code")')
  9170. //
  9171. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  9172. // against the expression language, but not to prevent exploits that were enabled by exposing
  9173. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  9174. // practice and therefore we are not even trying to protect against interaction with an object
  9175. // explicitly exposed in this way.
  9176. //
  9177. // In general, it is not possible to access a Window object from an angular expression unless a
  9178. // window or some DOM object that has a reference to window is published onto a Scope.
  9179. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  9180. // native objects.
  9181. //
  9182. // See https://docs.angularjs.org/guide/security
  9183. function ensureSafeMemberName(name, fullExpression) {
  9184. if (name === "__defineGetter__" || name === "__defineSetter__"
  9185. || name === "__lookupGetter__" || name === "__lookupSetter__"
  9186. || name === "__proto__") {
  9187. throw $parseMinErr('isecfld',
  9188. 'Attempting to access a disallowed field in Angular expressions! '
  9189. + 'Expression: {0}', fullExpression);
  9190. }
  9191. return name;
  9192. }
  9193. function getStringValue(name, fullExpression) {
  9194. // From the JavaScript docs:
  9195. // Property names must be strings. This means that non-string objects cannot be used
  9196. // as keys in an object. Any non-string object, including a number, is typecasted
  9197. // into a string via the toString method.
  9198. //
  9199. // So, to ensure that we are checking the same `name` that JavaScript would use,
  9200. // we cast it to a string, if possible.
  9201. // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
  9202. // this is, this will handle objects that misbehave.
  9203. name = name + '';
  9204. if (!isString(name)) {
  9205. throw $parseMinErr('iseccst',
  9206. 'Cannot convert object to primitive value! '
  9207. + 'Expression: {0}', fullExpression);
  9208. }
  9209. return name;
  9210. }
  9211. function ensureSafeObject(obj, fullExpression) {
  9212. // nifty check if obj is Function that is fast and works across iframes and other contexts
  9213. if (obj) {
  9214. if (obj.constructor === obj) {
  9215. throw $parseMinErr('isecfn',
  9216. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9217. fullExpression);
  9218. } else if (// isWindow(obj)
  9219. obj.document && obj.location && obj.alert && obj.setInterval) {
  9220. throw $parseMinErr('isecwindow',
  9221. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  9222. fullExpression);
  9223. } else if (// isElement(obj)
  9224. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  9225. throw $parseMinErr('isecdom',
  9226. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  9227. fullExpression);
  9228. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  9229. obj === Object) {
  9230. throw $parseMinErr('isecobj',
  9231. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  9232. fullExpression);
  9233. }
  9234. }
  9235. return obj;
  9236. }
  9237. var CALL = Function.prototype.call;
  9238. var APPLY = Function.prototype.apply;
  9239. var BIND = Function.prototype.bind;
  9240. function ensureSafeFunction(obj, fullExpression) {
  9241. if (obj) {
  9242. if (obj.constructor === obj) {
  9243. throw $parseMinErr('isecfn',
  9244. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9245. fullExpression);
  9246. } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
  9247. throw $parseMinErr('isecff',
  9248. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  9249. fullExpression);
  9250. }
  9251. }
  9252. }
  9253. var OPERATORS = {
  9254. /* jshint bitwise : false */
  9255. 'null':function(){return null;},
  9256. 'true':function(){return true;},
  9257. 'false':function(){return false;},
  9258. undefined:noop,
  9259. '+':function(self, locals, a,b){
  9260. a=a(self, locals); b=b(self, locals);
  9261. if (isDefined(a)) {
  9262. if (isDefined(b)) {
  9263. return a + b;
  9264. }
  9265. return a;
  9266. }
  9267. return isDefined(b)?b:undefined;},
  9268. '-':function(self, locals, a,b){
  9269. a=a(self, locals); b=b(self, locals);
  9270. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  9271. },
  9272. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  9273. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  9274. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  9275. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  9276. '=':noop,
  9277. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  9278. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  9279. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  9280. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  9281. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  9282. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  9283. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  9284. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  9285. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  9286. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  9287. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  9288. // '|':function(self, locals, a,b){return a|b;},
  9289. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  9290. '!':function(self, locals, a){return !a(self, locals);}
  9291. };
  9292. /* jshint bitwise: true */
  9293. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  9294. /////////////////////////////////////////
  9295. /**
  9296. * @constructor
  9297. */
  9298. var Lexer = function (options) {
  9299. this.options = options;
  9300. };
  9301. Lexer.prototype = {
  9302. constructor: Lexer,
  9303. lex: function (text) {
  9304. this.text = text;
  9305. this.index = 0;
  9306. this.ch = undefined;
  9307. this.lastCh = ':'; // can start regexp
  9308. this.tokens = [];
  9309. while (this.index < this.text.length) {
  9310. this.ch = this.text.charAt(this.index);
  9311. if (this.is('"\'')) {
  9312. this.readString(this.ch);
  9313. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  9314. this.readNumber();
  9315. } else if (this.isIdent(this.ch)) {
  9316. this.readIdent();
  9317. } else if (this.is('(){}[].,;:?')) {
  9318. this.tokens.push({
  9319. index: this.index,
  9320. text: this.ch
  9321. });
  9322. this.index++;
  9323. } else if (this.isWhitespace(this.ch)) {
  9324. this.index++;
  9325. continue;
  9326. } else {
  9327. var ch2 = this.ch + this.peek();
  9328. var ch3 = ch2 + this.peek(2);
  9329. var fn = OPERATORS[this.ch];
  9330. var fn2 = OPERATORS[ch2];
  9331. var fn3 = OPERATORS[ch3];
  9332. if (fn3) {
  9333. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  9334. this.index += 3;
  9335. } else if (fn2) {
  9336. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  9337. this.index += 2;
  9338. } else if (fn) {
  9339. this.tokens.push({
  9340. index: this.index,
  9341. text: this.ch,
  9342. fn: fn
  9343. });
  9344. this.index += 1;
  9345. } else {
  9346. this.throwError('Unexpected next character ', this.index, this.index + 1);
  9347. }
  9348. }
  9349. this.lastCh = this.ch;
  9350. }
  9351. return this.tokens;
  9352. },
  9353. is: function(chars) {
  9354. return chars.indexOf(this.ch) !== -1;
  9355. },
  9356. was: function(chars) {
  9357. return chars.indexOf(this.lastCh) !== -1;
  9358. },
  9359. peek: function(i) {
  9360. var num = i || 1;
  9361. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  9362. },
  9363. isNumber: function(ch) {
  9364. return ('0' <= ch && ch <= '9');
  9365. },
  9366. isWhitespace: function(ch) {
  9367. // IE treats non-breaking space as \u00A0
  9368. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9369. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9370. },
  9371. isIdent: function(ch) {
  9372. return ('a' <= ch && ch <= 'z' ||
  9373. 'A' <= ch && ch <= 'Z' ||
  9374. '_' === ch || ch === '$');
  9375. },
  9376. isExpOperator: function(ch) {
  9377. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9378. },
  9379. throwError: function(error, start, end) {
  9380. end = end || this.index;
  9381. var colStr = (isDefined(start)
  9382. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9383. : ' ' + end);
  9384. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9385. error, colStr, this.text);
  9386. },
  9387. readNumber: function() {
  9388. var number = '';
  9389. var start = this.index;
  9390. while (this.index < this.text.length) {
  9391. var ch = lowercase(this.text.charAt(this.index));
  9392. if (ch == '.' || this.isNumber(ch)) {
  9393. number += ch;
  9394. } else {
  9395. var peekCh = this.peek();
  9396. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9397. number += ch;
  9398. } else if (this.isExpOperator(ch) &&
  9399. peekCh && this.isNumber(peekCh) &&
  9400. number.charAt(number.length - 1) == 'e') {
  9401. number += ch;
  9402. } else if (this.isExpOperator(ch) &&
  9403. (!peekCh || !this.isNumber(peekCh)) &&
  9404. number.charAt(number.length - 1) == 'e') {
  9405. this.throwError('Invalid exponent');
  9406. } else {
  9407. break;
  9408. }
  9409. }
  9410. this.index++;
  9411. }
  9412. number = 1 * number;
  9413. this.tokens.push({
  9414. index: start,
  9415. text: number,
  9416. literal: true,
  9417. constant: true,
  9418. fn: function() { return number; }
  9419. });
  9420. },
  9421. readIdent: function() {
  9422. var parser = this;
  9423. var ident = '';
  9424. var start = this.index;
  9425. var lastDot, peekIndex, methodName, ch;
  9426. while (this.index < this.text.length) {
  9427. ch = this.text.charAt(this.index);
  9428. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9429. if (ch === '.') lastDot = this.index;
  9430. ident += ch;
  9431. } else {
  9432. break;
  9433. }
  9434. this.index++;
  9435. }
  9436. //check if this is not a method invocation and if it is back out to last dot
  9437. if (lastDot) {
  9438. peekIndex = this.index;
  9439. while (peekIndex < this.text.length) {
  9440. ch = this.text.charAt(peekIndex);
  9441. if (ch === '(') {
  9442. methodName = ident.substr(lastDot - start + 1);
  9443. ident = ident.substr(0, lastDot - start);
  9444. this.index = peekIndex;
  9445. break;
  9446. }
  9447. if (this.isWhitespace(ch)) {
  9448. peekIndex++;
  9449. } else {
  9450. break;
  9451. }
  9452. }
  9453. }
  9454. var token = {
  9455. index: start,
  9456. text: ident
  9457. };
  9458. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9459. if (OPERATORS.hasOwnProperty(ident)) {
  9460. token.fn = OPERATORS[ident];
  9461. token.literal = true;
  9462. token.constant = true;
  9463. } else {
  9464. var getter = getterFn(ident, this.options, this.text);
  9465. token.fn = extend(function(self, locals) {
  9466. return (getter(self, locals));
  9467. }, {
  9468. assign: function(self, value) {
  9469. return setter(self, ident, value, parser.text, parser.options);
  9470. }
  9471. });
  9472. }
  9473. this.tokens.push(token);
  9474. if (methodName) {
  9475. this.tokens.push({
  9476. index:lastDot,
  9477. text: '.'
  9478. });
  9479. this.tokens.push({
  9480. index: lastDot + 1,
  9481. text: methodName
  9482. });
  9483. }
  9484. },
  9485. readString: function(quote) {
  9486. var start = this.index;
  9487. this.index++;
  9488. var string = '';
  9489. var rawString = quote;
  9490. var escape = false;
  9491. while (this.index < this.text.length) {
  9492. var ch = this.text.charAt(this.index);
  9493. rawString += ch;
  9494. if (escape) {
  9495. if (ch === 'u') {
  9496. var hex = this.text.substring(this.index + 1, this.index + 5);
  9497. if (!hex.match(/[\da-f]{4}/i))
  9498. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9499. this.index += 4;
  9500. string += String.fromCharCode(parseInt(hex, 16));
  9501. } else {
  9502. var rep = ESCAPE[ch];
  9503. string = string + (rep || ch);
  9504. }
  9505. escape = false;
  9506. } else if (ch === '\\') {
  9507. escape = true;
  9508. } else if (ch === quote) {
  9509. this.index++;
  9510. this.tokens.push({
  9511. index: start,
  9512. text: rawString,
  9513. string: string,
  9514. literal: true,
  9515. constant: true,
  9516. fn: function() { return string; }
  9517. });
  9518. return;
  9519. } else {
  9520. string += ch;
  9521. }
  9522. this.index++;
  9523. }
  9524. this.throwError('Unterminated quote', start);
  9525. }
  9526. };
  9527. /**
  9528. * @constructor
  9529. */
  9530. var Parser = function (lexer, $filter, options) {
  9531. this.lexer = lexer;
  9532. this.$filter = $filter;
  9533. this.options = options;
  9534. };
  9535. Parser.ZERO = extend(function () {
  9536. return 0;
  9537. }, {
  9538. constant: true
  9539. });
  9540. Parser.prototype = {
  9541. constructor: Parser,
  9542. parse: function (text) {
  9543. this.text = text;
  9544. this.tokens = this.lexer.lex(text);
  9545. var value = this.statements();
  9546. if (this.tokens.length !== 0) {
  9547. this.throwError('is an unexpected token', this.tokens[0]);
  9548. }
  9549. value.literal = !!value.literal;
  9550. value.constant = !!value.constant;
  9551. return value;
  9552. },
  9553. primary: function () {
  9554. var primary;
  9555. if (this.expect('(')) {
  9556. primary = this.filterChain();
  9557. this.consume(')');
  9558. } else if (this.expect('[')) {
  9559. primary = this.arrayDeclaration();
  9560. } else if (this.expect('{')) {
  9561. primary = this.object();
  9562. } else {
  9563. var token = this.expect();
  9564. primary = token.fn;
  9565. if (!primary) {
  9566. this.throwError('not a primary expression', token);
  9567. }
  9568. primary.literal = !!token.literal;
  9569. primary.constant = !!token.constant;
  9570. }
  9571. var next, context;
  9572. while ((next = this.expect('(', '[', '.'))) {
  9573. if (next.text === '(') {
  9574. primary = this.functionCall(primary, context);
  9575. context = null;
  9576. } else if (next.text === '[') {
  9577. context = primary;
  9578. primary = this.objectIndex(primary);
  9579. } else if (next.text === '.') {
  9580. context = primary;
  9581. primary = this.fieldAccess(primary);
  9582. } else {
  9583. this.throwError('IMPOSSIBLE');
  9584. }
  9585. }
  9586. return primary;
  9587. },
  9588. throwError: function(msg, token) {
  9589. throw $parseMinErr('syntax',
  9590. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9591. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9592. },
  9593. peekToken: function() {
  9594. if (this.tokens.length === 0)
  9595. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9596. return this.tokens[0];
  9597. },
  9598. peek: function(e1, e2, e3, e4) {
  9599. if (this.tokens.length > 0) {
  9600. var token = this.tokens[0];
  9601. var t = token.text;
  9602. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9603. (!e1 && !e2 && !e3 && !e4)) {
  9604. return token;
  9605. }
  9606. }
  9607. return false;
  9608. },
  9609. expect: function(e1, e2, e3, e4){
  9610. var token = this.peek(e1, e2, e3, e4);
  9611. if (token) {
  9612. this.tokens.shift();
  9613. return token;
  9614. }
  9615. return false;
  9616. },
  9617. consume: function(e1){
  9618. if (!this.expect(e1)) {
  9619. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9620. }
  9621. },
  9622. unaryFn: function(fn, right) {
  9623. return extend(function(self, locals) {
  9624. return fn(self, locals, right);
  9625. }, {
  9626. constant:right.constant
  9627. });
  9628. },
  9629. ternaryFn: function(left, middle, right){
  9630. return extend(function(self, locals){
  9631. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9632. }, {
  9633. constant: left.constant && middle.constant && right.constant
  9634. });
  9635. },
  9636. binaryFn: function(left, fn, right) {
  9637. return extend(function(self, locals) {
  9638. return fn(self, locals, left, right);
  9639. }, {
  9640. constant:left.constant && right.constant
  9641. });
  9642. },
  9643. statements: function() {
  9644. var statements = [];
  9645. while (true) {
  9646. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9647. statements.push(this.filterChain());
  9648. if (!this.expect(';')) {
  9649. // optimize for the common case where there is only one statement.
  9650. // TODO(size): maybe we should not support multiple statements?
  9651. return (statements.length === 1)
  9652. ? statements[0]
  9653. : function(self, locals) {
  9654. var value;
  9655. for (var i = 0; i < statements.length; i++) {
  9656. var statement = statements[i];
  9657. if (statement) {
  9658. value = statement(self, locals);
  9659. }
  9660. }
  9661. return value;
  9662. };
  9663. }
  9664. }
  9665. },
  9666. filterChain: function() {
  9667. var left = this.expression();
  9668. var token;
  9669. while (true) {
  9670. if ((token = this.expect('|'))) {
  9671. left = this.binaryFn(left, token.fn, this.filter());
  9672. } else {
  9673. return left;
  9674. }
  9675. }
  9676. },
  9677. filter: function() {
  9678. var token = this.expect();
  9679. var fn = this.$filter(token.text);
  9680. var argsFn = [];
  9681. while (true) {
  9682. if ((token = this.expect(':'))) {
  9683. argsFn.push(this.expression());
  9684. } else {
  9685. var fnInvoke = function(self, locals, input) {
  9686. var args = [input];
  9687. for (var i = 0; i < argsFn.length; i++) {
  9688. args.push(argsFn[i](self, locals));
  9689. }
  9690. return fn.apply(self, args);
  9691. };
  9692. return function() {
  9693. return fnInvoke;
  9694. };
  9695. }
  9696. }
  9697. },
  9698. expression: function() {
  9699. return this.assignment();
  9700. },
  9701. assignment: function() {
  9702. var left = this.ternary();
  9703. var right;
  9704. var token;
  9705. if ((token = this.expect('='))) {
  9706. if (!left.assign) {
  9707. this.throwError('implies assignment but [' +
  9708. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9709. }
  9710. right = this.ternary();
  9711. return function(scope, locals) {
  9712. return left.assign(scope, right(scope, locals), locals);
  9713. };
  9714. }
  9715. return left;
  9716. },
  9717. ternary: function() {
  9718. var left = this.logicalOR();
  9719. var middle;
  9720. var token;
  9721. if ((token = this.expect('?'))) {
  9722. middle = this.assignment();
  9723. if ((token = this.expect(':'))) {
  9724. return this.ternaryFn(left, middle, this.assignment());
  9725. } else {
  9726. this.throwError('expected :', token);
  9727. }
  9728. } else {
  9729. return left;
  9730. }
  9731. },
  9732. logicalOR: function() {
  9733. var left = this.logicalAND();
  9734. var token;
  9735. while (true) {
  9736. if ((token = this.expect('||'))) {
  9737. left = this.binaryFn(left, token.fn, this.logicalAND());
  9738. } else {
  9739. return left;
  9740. }
  9741. }
  9742. },
  9743. logicalAND: function() {
  9744. var left = this.equality();
  9745. var token;
  9746. if ((token = this.expect('&&'))) {
  9747. left = this.binaryFn(left, token.fn, this.logicalAND());
  9748. }
  9749. return left;
  9750. },
  9751. equality: function() {
  9752. var left = this.relational();
  9753. var token;
  9754. if ((token = this.expect('==','!=','===','!=='))) {
  9755. left = this.binaryFn(left, token.fn, this.equality());
  9756. }
  9757. return left;
  9758. },
  9759. relational: function() {
  9760. var left = this.additive();
  9761. var token;
  9762. if ((token = this.expect('<', '>', '<=', '>='))) {
  9763. left = this.binaryFn(left, token.fn, this.relational());
  9764. }
  9765. return left;
  9766. },
  9767. additive: function() {
  9768. var left = this.multiplicative();
  9769. var token;
  9770. while ((token = this.expect('+','-'))) {
  9771. left = this.binaryFn(left, token.fn, this.multiplicative());
  9772. }
  9773. return left;
  9774. },
  9775. multiplicative: function() {
  9776. var left = this.unary();
  9777. var token;
  9778. while ((token = this.expect('*','/','%'))) {
  9779. left = this.binaryFn(left, token.fn, this.unary());
  9780. }
  9781. return left;
  9782. },
  9783. unary: function() {
  9784. var token;
  9785. if (this.expect('+')) {
  9786. return this.primary();
  9787. } else if ((token = this.expect('-'))) {
  9788. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9789. } else if ((token = this.expect('!'))) {
  9790. return this.unaryFn(token.fn, this.unary());
  9791. } else {
  9792. return this.primary();
  9793. }
  9794. },
  9795. fieldAccess: function(object) {
  9796. var parser = this;
  9797. var field = this.expect().text;
  9798. var getter = getterFn(field, this.options, this.text);
  9799. return extend(function(scope, locals, self) {
  9800. return getter(self || object(scope, locals));
  9801. }, {
  9802. assign: function(scope, value, locals) {
  9803. var o = object(scope, locals);
  9804. if (!o) object.assign(scope, o = {});
  9805. return setter(o, field, value, parser.text, parser.options);
  9806. }
  9807. });
  9808. },
  9809. objectIndex: function(obj) {
  9810. var parser = this;
  9811. var indexFn = this.expression();
  9812. this.consume(']');
  9813. return extend(function(self, locals) {
  9814. var o = obj(self, locals),
  9815. i = getStringValue(indexFn(self, locals), parser.text),
  9816. v, p;
  9817. ensureSafeMemberName(i, parser.text);
  9818. if (!o) return undefined;
  9819. v = ensureSafeObject(o[i], parser.text);
  9820. if (v && v.then && parser.options.unwrapPromises) {
  9821. p = v;
  9822. if (!('$$v' in v)) {
  9823. p.$$v = undefined;
  9824. p.then(function(val) { p.$$v = val; });
  9825. }
  9826. v = v.$$v;
  9827. }
  9828. return v;
  9829. }, {
  9830. assign: function(self, value, locals) {
  9831. var key = ensureSafeMemberName(getStringValue(indexFn(self, locals), parser.text), parser.text);
  9832. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9833. var o = ensureSafeObject(obj(self, locals), parser.text);
  9834. if (!o) obj.assign(self, o = {});
  9835. return o[key] = value;
  9836. }
  9837. });
  9838. },
  9839. functionCall: function(fn, contextGetter) {
  9840. var argsFn = [];
  9841. if (this.peekToken().text !== ')') {
  9842. do {
  9843. argsFn.push(this.expression());
  9844. } while (this.expect(','));
  9845. }
  9846. this.consume(')');
  9847. var parser = this;
  9848. return function(scope, locals) {
  9849. var args = [];
  9850. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9851. for (var i = 0; i < argsFn.length; i++) {
  9852. args.push(ensureSafeObject(argsFn[i](scope, locals), parser.text));
  9853. }
  9854. var fnPtr = fn(scope, locals, context) || noop;
  9855. ensureSafeObject(context, parser.text);
  9856. ensureSafeFunction(fnPtr, parser.text);
  9857. // IE doesn't have apply for some native functions
  9858. var v = fnPtr.apply
  9859. ? fnPtr.apply(context, args)
  9860. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9861. return ensureSafeObject(v, parser.text);
  9862. };
  9863. },
  9864. // This is used with json array declaration
  9865. arrayDeclaration: function () {
  9866. var elementFns = [];
  9867. var allConstant = true;
  9868. if (this.peekToken().text !== ']') {
  9869. do {
  9870. if (this.peek(']')) {
  9871. // Support trailing commas per ES5.1.
  9872. break;
  9873. }
  9874. var elementFn = this.expression();
  9875. elementFns.push(elementFn);
  9876. if (!elementFn.constant) {
  9877. allConstant = false;
  9878. }
  9879. } while (this.expect(','));
  9880. }
  9881. this.consume(']');
  9882. return extend(function(self, locals) {
  9883. var array = [];
  9884. for (var i = 0; i < elementFns.length; i++) {
  9885. array.push(elementFns[i](self, locals));
  9886. }
  9887. return array;
  9888. }, {
  9889. literal: true,
  9890. constant: allConstant
  9891. });
  9892. },
  9893. object: function () {
  9894. var keyValues = [];
  9895. var allConstant = true;
  9896. if (this.peekToken().text !== '}') {
  9897. do {
  9898. if (this.peek('}')) {
  9899. // Support trailing commas per ES5.1.
  9900. break;
  9901. }
  9902. var token = this.expect(),
  9903. key = token.string || token.text;
  9904. this.consume(':');
  9905. var value = this.expression();
  9906. keyValues.push({key: key, value: value});
  9907. if (!value.constant) {
  9908. allConstant = false;
  9909. }
  9910. } while (this.expect(','));
  9911. }
  9912. this.consume('}');
  9913. return extend(function(self, locals) {
  9914. var object = {};
  9915. for (var i = 0; i < keyValues.length; i++) {
  9916. var keyValue = keyValues[i];
  9917. object[keyValue.key] = keyValue.value(self, locals);
  9918. }
  9919. return object;
  9920. }, {
  9921. literal: true,
  9922. constant: allConstant
  9923. });
  9924. }
  9925. };
  9926. //////////////////////////////////////////////////
  9927. // Parser helper functions
  9928. //////////////////////////////////////////////////
  9929. function setter(obj, path, setValue, fullExp, options) {
  9930. ensureSafeObject(obj, fullExp);
  9931. //needed?
  9932. options = options || {};
  9933. var element = path.split('.'), key;
  9934. for (var i = 0; element.length > 1; i++) {
  9935. key = ensureSafeMemberName(element.shift(), fullExp);
  9936. var propertyObj = ensureSafeObject(obj[key], fullExp);
  9937. if (!propertyObj) {
  9938. propertyObj = {};
  9939. obj[key] = propertyObj;
  9940. }
  9941. obj = propertyObj;
  9942. if (obj.then && options.unwrapPromises) {
  9943. promiseWarning(fullExp);
  9944. if (!("$$v" in obj)) {
  9945. (function(promise) {
  9946. promise.then(function(val) { promise.$$v = val; }); }
  9947. )(obj);
  9948. }
  9949. if (obj.$$v === undefined) {
  9950. obj.$$v = {};
  9951. }
  9952. obj = obj.$$v;
  9953. }
  9954. }
  9955. key = ensureSafeMemberName(element.shift(), fullExp);
  9956. ensureSafeObject(obj[key], fullExp);
  9957. obj[key] = setValue;
  9958. return setValue;
  9959. }
  9960. var getterFnCacheDefault = {};
  9961. var getterFnCacheExpensive = {};
  9962. function isPossiblyDangerousMemberName(name) {
  9963. return name == 'constructor';
  9964. }
  9965. /**
  9966. * Implementation of the "Black Hole" variant from:
  9967. * - http://jsperf.com/angularjs-parse-getter/4
  9968. * - http://jsperf.com/path-evaluation-simplified/7
  9969. */
  9970. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9971. ensureSafeMemberName(key0, fullExp);
  9972. ensureSafeMemberName(key1, fullExp);
  9973. ensureSafeMemberName(key2, fullExp);
  9974. ensureSafeMemberName(key3, fullExp);
  9975. ensureSafeMemberName(key4, fullExp);
  9976. var eso = function(o) {
  9977. return ensureSafeObject(o, fullExp);
  9978. };
  9979. var expensiveChecks = options.expensiveChecks;
  9980. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  9981. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  9982. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  9983. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  9984. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  9985. return !options.unwrapPromises
  9986. ? function cspSafeGetter(scope, locals) {
  9987. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9988. if (pathVal == null) return pathVal;
  9989. pathVal = eso0(pathVal[key0]);
  9990. if (!key1) return pathVal;
  9991. if (pathVal == null) return undefined;
  9992. pathVal = eso1(pathVal[key1]);
  9993. if (!key2) return pathVal;
  9994. if (pathVal == null) return undefined;
  9995. pathVal = eso2(pathVal[key2]);
  9996. if (!key3) return pathVal;
  9997. if (pathVal == null) return undefined;
  9998. pathVal = eso3(pathVal[key3]);
  9999. if (!key4) return pathVal;
  10000. if (pathVal == null) return undefined;
  10001. pathVal = eso4(pathVal[key4]);
  10002. return pathVal;
  10003. }
  10004. : function cspSafePromiseEnabledGetter(scope, locals) {
  10005. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  10006. promise;
  10007. if (pathVal == null) return pathVal;
  10008. pathVal = eso0(pathVal[key0]);
  10009. if (pathVal && pathVal.then) {
  10010. promiseWarning(fullExp);
  10011. if (!("$$v" in pathVal)) {
  10012. promise = pathVal;
  10013. promise.$$v = undefined;
  10014. promise.then(function(val) { promise.$$v = eso0(val); });
  10015. }
  10016. pathVal = eso0(pathVal.$$v);
  10017. }
  10018. if (!key1) return pathVal;
  10019. if (pathVal == null) return undefined;
  10020. pathVal = eso1(pathVal[key1]);
  10021. if (pathVal && pathVal.then) {
  10022. promiseWarning(fullExp);
  10023. if (!("$$v" in pathVal)) {
  10024. promise = pathVal;
  10025. promise.$$v = undefined;
  10026. promise.then(function(val) { promise.$$v = eso1(val); });
  10027. }
  10028. pathVal = eso1(pathVal.$$v);
  10029. }
  10030. if (!key2) return pathVal;
  10031. if (pathVal == null) return undefined;
  10032. pathVal = eso2(pathVal[key2]);
  10033. if (pathVal && pathVal.then) {
  10034. promiseWarning(fullExp);
  10035. if (!("$$v" in pathVal)) {
  10036. promise = pathVal;
  10037. promise.$$v = undefined;
  10038. promise.then(function(val) { promise.$$v = eso2(val); });
  10039. }
  10040. pathVal = eso2(pathVal.$$v);
  10041. }
  10042. if (!key3) return pathVal;
  10043. if (pathVal == null) return undefined;
  10044. pathVal = eso3(pathVal[key3]);
  10045. if (pathVal && pathVal.then) {
  10046. promiseWarning(fullExp);
  10047. if (!("$$v" in pathVal)) {
  10048. promise = pathVal;
  10049. promise.$$v = undefined;
  10050. promise.then(function(val) { promise.$$v = eso3(val); });
  10051. }
  10052. pathVal = eso3(pathVal.$$v);
  10053. }
  10054. if (!key4) return pathVal;
  10055. if (pathVal == null) return undefined;
  10056. pathVal = eso4(pathVal[key4]);
  10057. if (pathVal && pathVal.then) {
  10058. promiseWarning(fullExp);
  10059. if (!("$$v" in pathVal)) {
  10060. promise = pathVal;
  10061. promise.$$v = undefined;
  10062. promise.then(function(val) { promise.$$v = eso4(val); });
  10063. }
  10064. pathVal = eso4(pathVal.$$v);
  10065. }
  10066. return pathVal;
  10067. };
  10068. }
  10069. function getterFnWithExtraArgs(fn, fullExpression) {
  10070. return function(s, l) {
  10071. return fn(s, l, promiseWarning, ensureSafeObject, fullExpression);
  10072. };
  10073. }
  10074. function getterFn(path, options, fullExp) {
  10075. var expensiveChecks = options.expensiveChecks;
  10076. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  10077. // Check whether the cache has this getter already.
  10078. // We can use hasOwnProperty directly on the cache because we ensure,
  10079. // see below, that the cache never stores a path called 'hasOwnProperty'
  10080. if (getterFnCache.hasOwnProperty(path)) {
  10081. return getterFnCache[path];
  10082. }
  10083. var pathKeys = path.split('.'),
  10084. pathKeysLength = pathKeys.length,
  10085. fn;
  10086. // http://jsperf.com/angularjs-parse-getter/6
  10087. if (options.csp) {
  10088. if (pathKeysLength < 6) {
  10089. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  10090. options);
  10091. } else {
  10092. fn = function(scope, locals) {
  10093. var i = 0, val;
  10094. do {
  10095. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  10096. pathKeys[i++], fullExp, options)(scope, locals);
  10097. locals = undefined; // clear after first iteration
  10098. scope = val;
  10099. } while (i < pathKeysLength);
  10100. return val;
  10101. };
  10102. }
  10103. } else {
  10104. var code = 'var p;\n';
  10105. if (expensiveChecks) {
  10106. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  10107. }
  10108. var needsEnsureSafeObject = expensiveChecks;
  10109. forEach(pathKeys, function(key, index) {
  10110. ensureSafeMemberName(key, fullExp);
  10111. var lookupJs = (index
  10112. // we simply dereference 's' on any .dot notation
  10113. ? 's'
  10114. // but if we are first then we check locals first, and if so read it first
  10115. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '["' + key + '"]';
  10116. var wrapWithEso = expensiveChecks || isPossiblyDangerousMemberName(key);
  10117. if (wrapWithEso) {
  10118. lookupJs = 'eso(' + lookupJs + ', fe)';
  10119. needsEnsureSafeObject = true;
  10120. }
  10121. code += 'if(s == null) return undefined;\n' +
  10122. 's=' + lookupJs + ';\n';
  10123. if (options.unwrapPromises) {
  10124. code += 'if (s && s.then) {\n' +
  10125. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  10126. ' if (!("$$v" in s)) {\n' +
  10127. ' p=s;\n' +
  10128. ' p.$$v = undefined;\n' +
  10129. ' p.then(function(v) {p.$$v=' + (wrapWithEso ? 'eso(v)' : 'v') + ';});\n' +
  10130. '}\n' +
  10131. ' s=' + (wrapWithEso ? 'eso(s.$$v)' : 's.$$v') + '\n' +
  10132. '}\n';
  10133. }
  10134. });
  10135. code += 'return s;';
  10136. /* jshint -W054 */
  10137. // s=scope, l=locals, pw=promiseWarning, eso=ensureSafeObject, fe=fullExpression
  10138. var evaledFnGetter = new Function('s', 'l', 'pw', 'eso', 'fe', code);
  10139. /* jshint +W054 */
  10140. evaledFnGetter.toString = valueFn(code);
  10141. if (needsEnsureSafeObject || options.unwrapPromises) {
  10142. evaledFnGetter = getterFnWithExtraArgs(evaledFnGetter, fullExp);
  10143. }
  10144. fn = evaledFnGetter;
  10145. }
  10146. // Only cache the value if it's not going to mess up the cache object
  10147. // This is more performant that using Object.prototype.hasOwnProperty.call
  10148. if (path !== 'hasOwnProperty') {
  10149. getterFnCache[path] = fn;
  10150. }
  10151. return fn;
  10152. }
  10153. ///////////////////////////////////
  10154. /**
  10155. * @ngdoc service
  10156. * @name $parse
  10157. * @kind function
  10158. *
  10159. * @description
  10160. *
  10161. * Converts Angular {@link guide/expression expression} into a function.
  10162. *
  10163. * ```js
  10164. * var getter = $parse('user.name');
  10165. * var setter = getter.assign;
  10166. * var context = {user:{name:'angular'}};
  10167. * var locals = {user:{name:'local'}};
  10168. *
  10169. * expect(getter(context)).toEqual('angular');
  10170. * setter(context, 'newValue');
  10171. * expect(context.user.name).toEqual('newValue');
  10172. * expect(getter(context, locals)).toEqual('local');
  10173. * ```
  10174. *
  10175. *
  10176. * @param {string} expression String expression to compile.
  10177. * @returns {function(context, locals)} a function which represents the compiled expression:
  10178. *
  10179. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  10180. * are evaluated against (typically a scope object).
  10181. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  10182. * `context`.
  10183. *
  10184. * The returned function also has the following properties:
  10185. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  10186. * literal.
  10187. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  10188. * constant literals.
  10189. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  10190. * set to a function to change its value on the given context.
  10191. *
  10192. */
  10193. /**
  10194. * @ngdoc provider
  10195. * @name $parseProvider
  10196. * @kind function
  10197. *
  10198. * @description
  10199. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  10200. * service.
  10201. */
  10202. function $ParseProvider() {
  10203. var cacheDefault = {};
  10204. var cacheExpensive = {};
  10205. var $parseOptions = {
  10206. csp: false,
  10207. unwrapPromises: false,
  10208. logPromiseWarnings: true,
  10209. expensiveChecks: false
  10210. };
  10211. /**
  10212. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10213. *
  10214. * @ngdoc method
  10215. * @name $parseProvider#unwrapPromises
  10216. * @description
  10217. *
  10218. * **This feature is deprecated, see deprecation notes below for more info**
  10219. *
  10220. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  10221. * found at any part of the expression. In other words, if set to true, the expression will always
  10222. * result in a non-promise value.
  10223. *
  10224. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  10225. * the fulfillment value is used in place of the promise while evaluating the expression.
  10226. *
  10227. * **Deprecation notice**
  10228. *
  10229. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  10230. * dichotomy between data access in templates (accessed as raw values) and controller code
  10231. * (accessed as promises).
  10232. *
  10233. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  10234. * the model access there.
  10235. *
  10236. * Other downsides of automatic promise unwrapping:
  10237. *
  10238. * - when building components it's often desirable to receive the raw promises
  10239. * - adds complexity and slows down expression evaluation
  10240. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  10241. * generated
  10242. * - makes IDE auto-completion and tool support hard
  10243. *
  10244. * **Warning Logs**
  10245. *
  10246. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  10247. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  10248. * `$parseProvider.logPromiseWarnings(false)` api.
  10249. *
  10250. *
  10251. * @param {boolean=} value New value.
  10252. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10253. * setter.
  10254. */
  10255. this.unwrapPromises = function(value) {
  10256. if (isDefined(value)) {
  10257. $parseOptions.unwrapPromises = !!value;
  10258. return this;
  10259. } else {
  10260. return $parseOptions.unwrapPromises;
  10261. }
  10262. };
  10263. /**
  10264. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10265. *
  10266. * @ngdoc method
  10267. * @name $parseProvider#logPromiseWarnings
  10268. * @description
  10269. *
  10270. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  10271. *
  10272. * The default is set to `true`.
  10273. *
  10274. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  10275. *
  10276. * @param {boolean=} value New value.
  10277. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10278. * setter.
  10279. */
  10280. this.logPromiseWarnings = function(value) {
  10281. if (isDefined(value)) {
  10282. $parseOptions.logPromiseWarnings = value;
  10283. return this;
  10284. } else {
  10285. return $parseOptions.logPromiseWarnings;
  10286. }
  10287. };
  10288. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  10289. $parseOptions.csp = $sniffer.csp;
  10290. var $parseOptionsExpensive = {
  10291. csp: $parseOptions.csp,
  10292. unwrapPromises: $parseOptions.unwrapPromises,
  10293. logPromiseWarnings: $parseOptions.logPromiseWarnings,
  10294. expensiveChecks: true
  10295. };
  10296. promiseWarning = function promiseWarningFn(fullExp) {
  10297. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  10298. promiseWarningCache[fullExp] = true;
  10299. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  10300. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  10301. };
  10302. return function(exp, expensiveChecks) {
  10303. var parsedExpression;
  10304. switch (typeof exp) {
  10305. case 'string':
  10306. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  10307. if (cache.hasOwnProperty(exp)) {
  10308. return cache[exp];
  10309. }
  10310. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  10311. var lexer = new Lexer(parseOptions);
  10312. var parser = new Parser(lexer, $filter, parseOptions);
  10313. parsedExpression = parser.parse(exp);
  10314. if (exp !== 'hasOwnProperty') {
  10315. // Only cache the value if it's not going to mess up the cache object
  10316. // This is more performant that using Object.prototype.hasOwnProperty.call
  10317. cache[exp] = parsedExpression;
  10318. }
  10319. return parsedExpression;
  10320. case 'function':
  10321. return exp;
  10322. default:
  10323. return noop;
  10324. }
  10325. };
  10326. }];
  10327. }
  10328. /**
  10329. * @ngdoc service
  10330. * @name $q
  10331. * @requires $rootScope
  10332. *
  10333. * @description
  10334. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  10335. * when they are done processing.
  10336. *
  10337. * This is an implementation of promises/deferred objects inspired by
  10338. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  10339. *
  10340. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  10341. * interface for interacting with an object that represents the result of an action that is
  10342. * performed asynchronously, and may or may not be finished at any given point in time.
  10343. *
  10344. * From the perspective of dealing with error handling, deferred and promise APIs are to
  10345. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  10346. *
  10347. * ```js
  10348. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  10349. * // are available in the current lexical scope (they could have been injected or passed in).
  10350. *
  10351. * function asyncGreet(name) {
  10352. * var deferred = $q.defer();
  10353. *
  10354. * setTimeout(function() {
  10355. * deferred.notify('About to greet ' + name + '.');
  10356. *
  10357. * if (okToGreet(name)) {
  10358. * deferred.resolve('Hello, ' + name + '!');
  10359. * } else {
  10360. * deferred.reject('Greeting ' + name + ' is not allowed.');
  10361. * }
  10362. * }, 1000);
  10363. *
  10364. * return deferred.promise;
  10365. * }
  10366. *
  10367. * var promise = asyncGreet('Robin Hood');
  10368. * promise.then(function(greeting) {
  10369. * alert('Success: ' + greeting);
  10370. * }, function(reason) {
  10371. * alert('Failed: ' + reason);
  10372. * }, function(update) {
  10373. * alert('Got notification: ' + update);
  10374. * });
  10375. * ```
  10376. *
  10377. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10378. * comes in the way of guarantees that promise and deferred APIs make, see
  10379. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10380. *
  10381. * Additionally the promise api allows for composition that is very hard to do with the
  10382. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10383. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10384. * section on serial or parallel joining of promises.
  10385. *
  10386. *
  10387. * # The Deferred API
  10388. *
  10389. * A new instance of deferred is constructed by calling `$q.defer()`.
  10390. *
  10391. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10392. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10393. * of the task.
  10394. *
  10395. * **Methods**
  10396. *
  10397. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10398. * constructed via `$q.reject`, the promise will be rejected instead.
  10399. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10400. * resolving it with a rejection constructed via `$q.reject`.
  10401. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10402. * multiple times before the promise is either resolved or rejected.
  10403. *
  10404. * **Properties**
  10405. *
  10406. * - promise – `{Promise}` – promise object associated with this deferred.
  10407. *
  10408. *
  10409. * # The Promise API
  10410. *
  10411. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10412. * calling `deferred.promise`.
  10413. *
  10414. * The purpose of the promise object is to allow for interested parties to get access to the result
  10415. * of the deferred task when it completes.
  10416. *
  10417. * **Methods**
  10418. *
  10419. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10420. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10421. * as soon as the result is available. The callbacks are called with a single argument: the result
  10422. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10423. * provide a progress indication, before the promise is resolved or rejected.
  10424. *
  10425. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10426. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10427. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10428. * method.
  10429. *
  10430. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10431. *
  10432. * Because `catch` is a reserved word in JavaScript and reserved keywords are not supported as
  10433. * property names by ES3, you'll need to invoke the method like `promise['catch'](callback)` or
  10434. * `promise.then(null, errorCallback)` to make your code IE8 and Android 2.x compatible.
  10435. *
  10436. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10437. * but to do so without modifying the final value. This is useful to release resources or do some
  10438. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10439. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10440. * more information.
  10441. *
  10442. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10443. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10444. * make your code IE8 and Android 2.x compatible.
  10445. *
  10446. * # Chaining promises
  10447. *
  10448. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10449. * possible to create a chain of promises:
  10450. *
  10451. * ```js
  10452. * promiseB = promiseA.then(function(result) {
  10453. * return result + 1;
  10454. * });
  10455. *
  10456. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10457. * // will be the result of promiseA incremented by 1
  10458. * ```
  10459. *
  10460. * It is possible to create chains of any length and since a promise can be resolved with another
  10461. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10462. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10463. * $http's response interceptors.
  10464. *
  10465. *
  10466. * # Differences between Kris Kowal's Q and $q
  10467. *
  10468. * There are two main differences:
  10469. *
  10470. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10471. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10472. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10473. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10474. * all the important functionality needed for common async tasks.
  10475. *
  10476. * # Testing
  10477. *
  10478. * ```js
  10479. * it('should simulate promise', inject(function($q, $rootScope) {
  10480. * var deferred = $q.defer();
  10481. * var promise = deferred.promise;
  10482. * var resolvedValue;
  10483. *
  10484. * promise.then(function(value) { resolvedValue = value; });
  10485. * expect(resolvedValue).toBeUndefined();
  10486. *
  10487. * // Simulate resolving of promise
  10488. * deferred.resolve(123);
  10489. * // Note that the 'then' function does not get called synchronously.
  10490. * // This is because we want the promise API to always be async, whether or not
  10491. * // it got called synchronously or asynchronously.
  10492. * expect(resolvedValue).toBeUndefined();
  10493. *
  10494. * // Propagate promise resolution to 'then' functions using $apply().
  10495. * $rootScope.$apply();
  10496. * expect(resolvedValue).toEqual(123);
  10497. * }));
  10498. * ```
  10499. */
  10500. function $QProvider() {
  10501. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10502. return qFactory(function(callback) {
  10503. $rootScope.$evalAsync(callback);
  10504. }, $exceptionHandler);
  10505. }];
  10506. }
  10507. /**
  10508. * Constructs a promise manager.
  10509. *
  10510. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10511. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10512. * debugging purposes.
  10513. * @returns {object} Promise manager.
  10514. */
  10515. function qFactory(nextTick, exceptionHandler) {
  10516. /**
  10517. * @ngdoc method
  10518. * @name $q#defer
  10519. * @kind function
  10520. *
  10521. * @description
  10522. * Creates a `Deferred` object which represents a task which will finish in the future.
  10523. *
  10524. * @returns {Deferred} Returns a new instance of deferred.
  10525. */
  10526. var defer = function() {
  10527. var pending = [],
  10528. value, deferred;
  10529. deferred = {
  10530. resolve: function(val) {
  10531. if (pending) {
  10532. var callbacks = pending;
  10533. pending = undefined;
  10534. value = ref(val);
  10535. if (callbacks.length) {
  10536. nextTick(function() {
  10537. var callback;
  10538. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10539. callback = callbacks[i];
  10540. value.then(callback[0], callback[1], callback[2]);
  10541. }
  10542. });
  10543. }
  10544. }
  10545. },
  10546. reject: function(reason) {
  10547. deferred.resolve(createInternalRejectedPromise(reason));
  10548. },
  10549. notify: function(progress) {
  10550. if (pending) {
  10551. var callbacks = pending;
  10552. if (pending.length) {
  10553. nextTick(function() {
  10554. var callback;
  10555. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10556. callback = callbacks[i];
  10557. callback[2](progress);
  10558. }
  10559. });
  10560. }
  10561. }
  10562. },
  10563. promise: {
  10564. then: function(callback, errback, progressback) {
  10565. var result = defer();
  10566. var wrappedCallback = function(value) {
  10567. try {
  10568. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10569. } catch(e) {
  10570. result.reject(e);
  10571. exceptionHandler(e);
  10572. }
  10573. };
  10574. var wrappedErrback = function(reason) {
  10575. try {
  10576. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10577. } catch(e) {
  10578. result.reject(e);
  10579. exceptionHandler(e);
  10580. }
  10581. };
  10582. var wrappedProgressback = function(progress) {
  10583. try {
  10584. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10585. } catch(e) {
  10586. exceptionHandler(e);
  10587. }
  10588. };
  10589. if (pending) {
  10590. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10591. } else {
  10592. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10593. }
  10594. return result.promise;
  10595. },
  10596. "catch": function(callback) {
  10597. return this.then(null, callback);
  10598. },
  10599. "finally": function(callback) {
  10600. function makePromise(value, resolved) {
  10601. var result = defer();
  10602. if (resolved) {
  10603. result.resolve(value);
  10604. } else {
  10605. result.reject(value);
  10606. }
  10607. return result.promise;
  10608. }
  10609. function handleCallback(value, isResolved) {
  10610. var callbackOutput = null;
  10611. try {
  10612. callbackOutput = (callback ||defaultCallback)();
  10613. } catch(e) {
  10614. return makePromise(e, false);
  10615. }
  10616. if (isPromiseLike(callbackOutput)) {
  10617. return callbackOutput.then(function() {
  10618. return makePromise(value, isResolved);
  10619. }, function(error) {
  10620. return makePromise(error, false);
  10621. });
  10622. } else {
  10623. return makePromise(value, isResolved);
  10624. }
  10625. }
  10626. return this.then(function(value) {
  10627. return handleCallback(value, true);
  10628. }, function(error) {
  10629. return handleCallback(error, false);
  10630. });
  10631. }
  10632. }
  10633. };
  10634. return deferred;
  10635. };
  10636. var ref = function(value) {
  10637. if (isPromiseLike(value)) return value;
  10638. return {
  10639. then: function(callback) {
  10640. var result = defer();
  10641. nextTick(function() {
  10642. result.resolve(callback(value));
  10643. });
  10644. return result.promise;
  10645. }
  10646. };
  10647. };
  10648. /**
  10649. * @ngdoc method
  10650. * @name $q#reject
  10651. * @kind function
  10652. *
  10653. * @description
  10654. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10655. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10656. * a promise chain, you don't need to worry about it.
  10657. *
  10658. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10659. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10660. * a promise error callback and you want to forward the error to the promise derived from the
  10661. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10662. * `reject`.
  10663. *
  10664. * ```js
  10665. * promiseB = promiseA.then(function(result) {
  10666. * // success: do something and resolve promiseB
  10667. * // with the old or a new result
  10668. * return result;
  10669. * }, function(reason) {
  10670. * // error: handle the error if possible and
  10671. * // resolve promiseB with newPromiseOrValue,
  10672. * // otherwise forward the rejection to promiseB
  10673. * if (canHandle(reason)) {
  10674. * // handle the error and recover
  10675. * return newPromiseOrValue;
  10676. * }
  10677. * return $q.reject(reason);
  10678. * });
  10679. * ```
  10680. *
  10681. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10682. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10683. */
  10684. var reject = function(reason) {
  10685. var result = defer();
  10686. result.reject(reason);
  10687. return result.promise;
  10688. };
  10689. var createInternalRejectedPromise = function(reason) {
  10690. return {
  10691. then: function(callback, errback) {
  10692. var result = defer();
  10693. nextTick(function() {
  10694. try {
  10695. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10696. } catch(e) {
  10697. result.reject(e);
  10698. exceptionHandler(e);
  10699. }
  10700. });
  10701. return result.promise;
  10702. }
  10703. };
  10704. };
  10705. /**
  10706. * @ngdoc method
  10707. * @name $q#when
  10708. * @kind function
  10709. *
  10710. * @description
  10711. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10712. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10713. * the promise comes from a source that can't be trusted.
  10714. *
  10715. * @param {*} value Value or a promise
  10716. * @returns {Promise} Returns a promise of the passed value or promise
  10717. */
  10718. var when = function(value, callback, errback, progressback) {
  10719. var result = defer(),
  10720. done;
  10721. var wrappedCallback = function(value) {
  10722. try {
  10723. return (isFunction(callback) ? callback : defaultCallback)(value);
  10724. } catch (e) {
  10725. exceptionHandler(e);
  10726. return reject(e);
  10727. }
  10728. };
  10729. var wrappedErrback = function(reason) {
  10730. try {
  10731. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10732. } catch (e) {
  10733. exceptionHandler(e);
  10734. return reject(e);
  10735. }
  10736. };
  10737. var wrappedProgressback = function(progress) {
  10738. try {
  10739. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10740. } catch (e) {
  10741. exceptionHandler(e);
  10742. }
  10743. };
  10744. nextTick(function() {
  10745. ref(value).then(function(value) {
  10746. if (done) return;
  10747. done = true;
  10748. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10749. }, function(reason) {
  10750. if (done) return;
  10751. done = true;
  10752. result.resolve(wrappedErrback(reason));
  10753. }, function(progress) {
  10754. if (done) return;
  10755. result.notify(wrappedProgressback(progress));
  10756. });
  10757. });
  10758. return result.promise;
  10759. };
  10760. function defaultCallback(value) {
  10761. return value;
  10762. }
  10763. function defaultErrback(reason) {
  10764. return reject(reason);
  10765. }
  10766. /**
  10767. * @ngdoc method
  10768. * @name $q#all
  10769. * @kind function
  10770. *
  10771. * @description
  10772. * Combines multiple promises into a single promise that is resolved when all of the input
  10773. * promises are resolved.
  10774. *
  10775. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10776. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10777. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10778. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10779. * with the same rejection value.
  10780. */
  10781. function all(promises) {
  10782. var deferred = defer(),
  10783. counter = 0,
  10784. results = isArray(promises) ? [] : {};
  10785. forEach(promises, function(promise, key) {
  10786. counter++;
  10787. ref(promise).then(function(value) {
  10788. if (results.hasOwnProperty(key)) return;
  10789. results[key] = value;
  10790. if (!(--counter)) deferred.resolve(results);
  10791. }, function(reason) {
  10792. if (results.hasOwnProperty(key)) return;
  10793. deferred.reject(reason);
  10794. });
  10795. });
  10796. if (counter === 0) {
  10797. deferred.resolve(results);
  10798. }
  10799. return deferred.promise;
  10800. }
  10801. return {
  10802. defer: defer,
  10803. reject: reject,
  10804. when: when,
  10805. all: all
  10806. };
  10807. }
  10808. function $$RAFProvider(){ //rAF
  10809. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10810. var requestAnimationFrame = $window.requestAnimationFrame ||
  10811. $window.webkitRequestAnimationFrame ||
  10812. $window.mozRequestAnimationFrame;
  10813. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10814. $window.webkitCancelAnimationFrame ||
  10815. $window.mozCancelAnimationFrame ||
  10816. $window.webkitCancelRequestAnimationFrame;
  10817. var rafSupported = !!requestAnimationFrame;
  10818. var raf = rafSupported
  10819. ? function(fn) {
  10820. var id = requestAnimationFrame(fn);
  10821. return function() {
  10822. cancelAnimationFrame(id);
  10823. };
  10824. }
  10825. : function(fn) {
  10826. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10827. return function() {
  10828. $timeout.cancel(timer);
  10829. };
  10830. };
  10831. raf.supported = rafSupported;
  10832. return raf;
  10833. }];
  10834. }
  10835. /**
  10836. * DESIGN NOTES
  10837. *
  10838. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10839. *
  10840. * The typical use of scope is to watch the expressions, which most of the time return the same
  10841. * value as last time so we optimize the operation.
  10842. *
  10843. * Closures construction is expensive in terms of speed as well as memory:
  10844. * - No closures, instead use prototypical inheritance for API
  10845. * - Internal state needs to be stored on scope directly, which means that private state is
  10846. * exposed as $$____ properties
  10847. *
  10848. * Loop operations are optimized by using while(count--) { ... }
  10849. * - this means that in order to keep the same order of execution as addition we have to add
  10850. * items to the array at the beginning (unshift) instead of at the end (push)
  10851. *
  10852. * Child scopes are created and removed often
  10853. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10854. *
  10855. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10856. * implemented in the same way as watch. Watch requires return of initialization function which
  10857. * are expensive to construct.
  10858. */
  10859. /**
  10860. * @ngdoc provider
  10861. * @name $rootScopeProvider
  10862. * @description
  10863. *
  10864. * Provider for the $rootScope service.
  10865. */
  10866. /**
  10867. * @ngdoc method
  10868. * @name $rootScopeProvider#digestTtl
  10869. * @description
  10870. *
  10871. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10872. * assuming that the model is unstable.
  10873. *
  10874. * The current default is 10 iterations.
  10875. *
  10876. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10877. * several digest iterations. However if an application needs more than the default 10 digest
  10878. * iterations for its model to stabilize then you should investigate what is causing the model to
  10879. * continuously change during the digest.
  10880. *
  10881. * Increasing the TTL could have performance implications, so you should not change it without
  10882. * proper justification.
  10883. *
  10884. * @param {number} limit The number of digest iterations.
  10885. */
  10886. /**
  10887. * @ngdoc service
  10888. * @name $rootScope
  10889. * @description
  10890. *
  10891. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10892. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10893. * between the model and the view, via a mechanism for watching the model for changes.
  10894. * They also provide an event emission/broadcast and subscription facility. See the
  10895. * {@link guide/scope developer guide on scopes}.
  10896. */
  10897. function $RootScopeProvider(){
  10898. var TTL = 10;
  10899. var $rootScopeMinErr = minErr('$rootScope');
  10900. var lastDirtyWatch = null;
  10901. this.digestTtl = function(value) {
  10902. if (arguments.length) {
  10903. TTL = value;
  10904. }
  10905. return TTL;
  10906. };
  10907. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10908. function( $injector, $exceptionHandler, $parse, $browser) {
  10909. /**
  10910. * @ngdoc type
  10911. * @name $rootScope.Scope
  10912. *
  10913. * @description
  10914. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10915. * {@link auto.$injector $injector}. Child scopes are created using the
  10916. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10917. * compiled HTML template is executed.)
  10918. *
  10919. * Here is a simple scope snippet to show how you can interact with the scope.
  10920. * ```html
  10921. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10922. * ```
  10923. *
  10924. * # Inheritance
  10925. * A scope can inherit from a parent scope, as in this example:
  10926. * ```js
  10927. var parent = $rootScope;
  10928. var child = parent.$new();
  10929. parent.salutation = "Hello";
  10930. child.name = "World";
  10931. expect(child.salutation).toEqual('Hello');
  10932. child.salutation = "Welcome";
  10933. expect(child.salutation).toEqual('Welcome');
  10934. expect(parent.salutation).toEqual('Hello');
  10935. * ```
  10936. *
  10937. *
  10938. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10939. * provided for the current scope. Defaults to {@link ng}.
  10940. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10941. * append/override services provided by `providers`. This is handy
  10942. * when unit-testing and having the need to override a default
  10943. * service.
  10944. * @returns {Object} Newly created scope.
  10945. *
  10946. */
  10947. function Scope() {
  10948. this.$id = nextUid();
  10949. this.$$phase = this.$parent = this.$$watchers =
  10950. this.$$nextSibling = this.$$prevSibling =
  10951. this.$$childHead = this.$$childTail = null;
  10952. this['this'] = this.$root = this;
  10953. this.$$destroyed = false;
  10954. this.$$asyncQueue = [];
  10955. this.$$postDigestQueue = [];
  10956. this.$$listeners = {};
  10957. this.$$listenerCount = {};
  10958. this.$$isolateBindings = {};
  10959. }
  10960. /**
  10961. * @ngdoc property
  10962. * @name $rootScope.Scope#$id
  10963. *
  10964. * @description
  10965. * Unique scope ID (monotonically increasing) useful for debugging.
  10966. */
  10967. /**
  10968. * @ngdoc property
  10969. * @name $rootScope.Scope#$parent
  10970. *
  10971. * @description
  10972. * Reference to the parent scope.
  10973. */
  10974. /**
  10975. * @ngdoc property
  10976. * @name $rootScope.Scope#$root
  10977. *
  10978. * @description
  10979. * Reference to the root scope.
  10980. */
  10981. Scope.prototype = {
  10982. constructor: Scope,
  10983. /**
  10984. * @ngdoc method
  10985. * @name $rootScope.Scope#$new
  10986. * @kind function
  10987. *
  10988. * @description
  10989. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10990. *
  10991. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  10992. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10993. *
  10994. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10995. * desired for the scope and its child scopes to be permanently detached from the parent and
  10996. * thus stop participating in model change detection and listener notification by invoking.
  10997. *
  10998. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10999. * parent scope. The scope is isolated, as it can not see parent scope properties.
  11000. * When creating widgets, it is useful for the widget to not accidentally read parent
  11001. * state.
  11002. *
  11003. * @returns {Object} The newly created child scope.
  11004. *
  11005. */
  11006. $new: function(isolate) {
  11007. var ChildScope,
  11008. child;
  11009. if (isolate) {
  11010. child = new Scope();
  11011. child.$root = this.$root;
  11012. // ensure that there is just one async queue per $rootScope and its children
  11013. child.$$asyncQueue = this.$$asyncQueue;
  11014. child.$$postDigestQueue = this.$$postDigestQueue;
  11015. } else {
  11016. // Only create a child scope class if somebody asks for one,
  11017. // but cache it to allow the VM to optimize lookups.
  11018. if (!this.$$childScopeClass) {
  11019. this.$$childScopeClass = function() {
  11020. this.$$watchers = this.$$nextSibling =
  11021. this.$$childHead = this.$$childTail = null;
  11022. this.$$listeners = {};
  11023. this.$$listenerCount = {};
  11024. this.$id = nextUid();
  11025. this.$$childScopeClass = null;
  11026. };
  11027. this.$$childScopeClass.prototype = this;
  11028. }
  11029. child = new this.$$childScopeClass();
  11030. }
  11031. child['this'] = child;
  11032. child.$parent = this;
  11033. child.$$prevSibling = this.$$childTail;
  11034. if (this.$$childHead) {
  11035. this.$$childTail.$$nextSibling = child;
  11036. this.$$childTail = child;
  11037. } else {
  11038. this.$$childHead = this.$$childTail = child;
  11039. }
  11040. return child;
  11041. },
  11042. /**
  11043. * @ngdoc method
  11044. * @name $rootScope.Scope#$watch
  11045. * @kind function
  11046. *
  11047. * @description
  11048. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  11049. *
  11050. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  11051. * $digest()} and should return the value that will be watched. (Since
  11052. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  11053. * `watchExpression` can execute multiple times per
  11054. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  11055. * - The `listener` is called only when the value from the current `watchExpression` and the
  11056. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  11057. * see below). Inequality is determined according to reference inequality,
  11058. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  11059. * via the `!==` Javascript operator, unless `objectEquality == true`
  11060. * (see next point)
  11061. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  11062. * according to the {@link angular.equals} function. To save the value of the object for
  11063. * later comparison, the {@link angular.copy} function is used. This therefore means that
  11064. * watching complex objects will have adverse memory and performance implications.
  11065. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  11066. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  11067. * iteration limit is 10 to prevent an infinite loop deadlock.
  11068. *
  11069. *
  11070. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  11071. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  11072. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  11073. * change is detected, be prepared for multiple calls to your listener.)
  11074. *
  11075. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  11076. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  11077. * watcher. In rare cases, this is undesirable because the listener is called when the result
  11078. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  11079. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  11080. * listener was called due to initialization.
  11081. *
  11082. * The example below contains an illustration of using a function as your $watch listener
  11083. *
  11084. *
  11085. * # Example
  11086. * ```js
  11087. // let's assume that scope was dependency injected as the $rootScope
  11088. var scope = $rootScope;
  11089. scope.name = 'misko';
  11090. scope.counter = 0;
  11091. expect(scope.counter).toEqual(0);
  11092. scope.$watch('name', function(newValue, oldValue) {
  11093. scope.counter = scope.counter + 1;
  11094. });
  11095. expect(scope.counter).toEqual(0);
  11096. scope.$digest();
  11097. // the listener is always called during the first $digest loop after it was registered
  11098. expect(scope.counter).toEqual(1);
  11099. scope.$digest();
  11100. // but now it will not be called unless the value changes
  11101. expect(scope.counter).toEqual(1);
  11102. scope.name = 'adam';
  11103. scope.$digest();
  11104. expect(scope.counter).toEqual(2);
  11105. // Using a listener function
  11106. var food;
  11107. scope.foodCounter = 0;
  11108. expect(scope.foodCounter).toEqual(0);
  11109. scope.$watch(
  11110. // This is the listener function
  11111. function() { return food; },
  11112. // This is the change handler
  11113. function(newValue, oldValue) {
  11114. if ( newValue !== oldValue ) {
  11115. // Only increment the counter if the value changed
  11116. scope.foodCounter = scope.foodCounter + 1;
  11117. }
  11118. }
  11119. );
  11120. // No digest has been run so the counter will be zero
  11121. expect(scope.foodCounter).toEqual(0);
  11122. // Run the digest but since food has not changed count will still be zero
  11123. scope.$digest();
  11124. expect(scope.foodCounter).toEqual(0);
  11125. // Update food and run digest. Now the counter will increment
  11126. food = 'cheeseburger';
  11127. scope.$digest();
  11128. expect(scope.foodCounter).toEqual(1);
  11129. * ```
  11130. *
  11131. *
  11132. *
  11133. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  11134. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  11135. * a call to the `listener`.
  11136. *
  11137. * - `string`: Evaluated as {@link guide/expression expression}
  11138. * - `function(scope)`: called with current `scope` as a parameter.
  11139. * @param {(function()|string)=} listener Callback called whenever the return value of
  11140. * the `watchExpression` changes.
  11141. *
  11142. * - `string`: Evaluated as {@link guide/expression expression}
  11143. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  11144. * parameters.
  11145. *
  11146. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  11147. * comparing for reference equality.
  11148. * @returns {function()} Returns a deregistration function for this listener.
  11149. */
  11150. $watch: function(watchExp, listener, objectEquality) {
  11151. var scope = this,
  11152. get = compileToFn(watchExp, 'watch'),
  11153. array = scope.$$watchers,
  11154. watcher = {
  11155. fn: listener,
  11156. last: initWatchVal,
  11157. get: get,
  11158. exp: watchExp,
  11159. eq: !!objectEquality
  11160. };
  11161. lastDirtyWatch = null;
  11162. // in the case user pass string, we need to compile it, do we really need this ?
  11163. if (!isFunction(listener)) {
  11164. var listenFn = compileToFn(listener || noop, 'listener');
  11165. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  11166. }
  11167. if (typeof watchExp == 'string' && get.constant) {
  11168. var originalFn = watcher.fn;
  11169. watcher.fn = function(newVal, oldVal, scope) {
  11170. originalFn.call(this, newVal, oldVal, scope);
  11171. arrayRemove(array, watcher);
  11172. };
  11173. }
  11174. if (!array) {
  11175. array = scope.$$watchers = [];
  11176. }
  11177. // we use unshift since we use a while loop in $digest for speed.
  11178. // the while loop reads in reverse order.
  11179. array.unshift(watcher);
  11180. return function deregisterWatch() {
  11181. arrayRemove(array, watcher);
  11182. lastDirtyWatch = null;
  11183. };
  11184. },
  11185. /**
  11186. * @ngdoc method
  11187. * @name $rootScope.Scope#$watchCollection
  11188. * @kind function
  11189. *
  11190. * @description
  11191. * Shallow watches the properties of an object and fires whenever any of the properties change
  11192. * (for arrays, this implies watching the array items; for object maps, this implies watching
  11193. * the properties). If a change is detected, the `listener` callback is fired.
  11194. *
  11195. * - The `obj` collection is observed via standard $watch operation and is examined on every
  11196. * call to $digest() to see if any items have been added, removed, or moved.
  11197. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  11198. * adding, removing, and moving items belonging to an object or array.
  11199. *
  11200. *
  11201. * # Example
  11202. * ```js
  11203. $scope.names = ['igor', 'matias', 'misko', 'james'];
  11204. $scope.dataCount = 4;
  11205. $scope.$watchCollection('names', function(newNames, oldNames) {
  11206. $scope.dataCount = newNames.length;
  11207. });
  11208. expect($scope.dataCount).toEqual(4);
  11209. $scope.$digest();
  11210. //still at 4 ... no changes
  11211. expect($scope.dataCount).toEqual(4);
  11212. $scope.names.pop();
  11213. $scope.$digest();
  11214. //now there's been a change
  11215. expect($scope.dataCount).toEqual(3);
  11216. * ```
  11217. *
  11218. *
  11219. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  11220. * expression value should evaluate to an object or an array which is observed on each
  11221. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  11222. * collection will trigger a call to the `listener`.
  11223. *
  11224. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  11225. * when a change is detected.
  11226. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  11227. * - The `oldCollection` object is a copy of the former collection data.
  11228. * Due to performance considerations, the`oldCollection` value is computed only if the
  11229. * `listener` function declares two or more arguments.
  11230. * - The `scope` argument refers to the current scope.
  11231. *
  11232. * @returns {function()} Returns a de-registration function for this listener. When the
  11233. * de-registration function is executed, the internal watch operation is terminated.
  11234. */
  11235. $watchCollection: function(obj, listener) {
  11236. var self = this;
  11237. // the current value, updated on each dirty-check run
  11238. var newValue;
  11239. // a shallow copy of the newValue from the last dirty-check run,
  11240. // updated to match newValue during dirty-check run
  11241. var oldValue;
  11242. // a shallow copy of the newValue from when the last change happened
  11243. var veryOldValue;
  11244. // only track veryOldValue if the listener is asking for it
  11245. var trackVeryOldValue = (listener.length > 1);
  11246. var changeDetected = 0;
  11247. var objGetter = $parse(obj);
  11248. var internalArray = [];
  11249. var internalObject = {};
  11250. var initRun = true;
  11251. var oldLength = 0;
  11252. function $watchCollectionWatch() {
  11253. newValue = objGetter(self);
  11254. var newLength, key, bothNaN;
  11255. if (!isObject(newValue)) { // if primitive
  11256. if (oldValue !== newValue) {
  11257. oldValue = newValue;
  11258. changeDetected++;
  11259. }
  11260. } else if (isArrayLike(newValue)) {
  11261. if (oldValue !== internalArray) {
  11262. // we are transitioning from something which was not an array into array.
  11263. oldValue = internalArray;
  11264. oldLength = oldValue.length = 0;
  11265. changeDetected++;
  11266. }
  11267. newLength = newValue.length;
  11268. if (oldLength !== newLength) {
  11269. // if lengths do not match we need to trigger change notification
  11270. changeDetected++;
  11271. oldValue.length = oldLength = newLength;
  11272. }
  11273. // copy the items to oldValue and look for changes.
  11274. for (var i = 0; i < newLength; i++) {
  11275. bothNaN = (oldValue[i] !== oldValue[i]) &&
  11276. (newValue[i] !== newValue[i]);
  11277. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  11278. changeDetected++;
  11279. oldValue[i] = newValue[i];
  11280. }
  11281. }
  11282. } else {
  11283. if (oldValue !== internalObject) {
  11284. // we are transitioning from something which was not an object into object.
  11285. oldValue = internalObject = {};
  11286. oldLength = 0;
  11287. changeDetected++;
  11288. }
  11289. // copy the items to oldValue and look for changes.
  11290. newLength = 0;
  11291. for (key in newValue) {
  11292. if (newValue.hasOwnProperty(key)) {
  11293. newLength++;
  11294. if (oldValue.hasOwnProperty(key)) {
  11295. bothNaN = (oldValue[key] !== oldValue[key]) &&
  11296. (newValue[key] !== newValue[key]);
  11297. if (!bothNaN && (oldValue[key] !== newValue[key])) {
  11298. changeDetected++;
  11299. oldValue[key] = newValue[key];
  11300. }
  11301. } else {
  11302. oldLength++;
  11303. oldValue[key] = newValue[key];
  11304. changeDetected++;
  11305. }
  11306. }
  11307. }
  11308. if (oldLength > newLength) {
  11309. // we used to have more keys, need to find them and destroy them.
  11310. changeDetected++;
  11311. for(key in oldValue) {
  11312. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  11313. oldLength--;
  11314. delete oldValue[key];
  11315. }
  11316. }
  11317. }
  11318. }
  11319. return changeDetected;
  11320. }
  11321. function $watchCollectionAction() {
  11322. if (initRun) {
  11323. initRun = false;
  11324. listener(newValue, newValue, self);
  11325. } else {
  11326. listener(newValue, veryOldValue, self);
  11327. }
  11328. // make a copy for the next time a collection is changed
  11329. if (trackVeryOldValue) {
  11330. if (!isObject(newValue)) {
  11331. //primitive
  11332. veryOldValue = newValue;
  11333. } else if (isArrayLike(newValue)) {
  11334. veryOldValue = new Array(newValue.length);
  11335. for (var i = 0; i < newValue.length; i++) {
  11336. veryOldValue[i] = newValue[i];
  11337. }
  11338. } else { // if object
  11339. veryOldValue = {};
  11340. for (var key in newValue) {
  11341. if (hasOwnProperty.call(newValue, key)) {
  11342. veryOldValue[key] = newValue[key];
  11343. }
  11344. }
  11345. }
  11346. }
  11347. }
  11348. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  11349. },
  11350. /**
  11351. * @ngdoc method
  11352. * @name $rootScope.Scope#$digest
  11353. * @kind function
  11354. *
  11355. * @description
  11356. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  11357. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  11358. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  11359. * until no more listeners are firing. This means that it is possible to get into an infinite
  11360. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  11361. * iterations exceeds 10.
  11362. *
  11363. * Usually, you don't call `$digest()` directly in
  11364. * {@link ng.directive:ngController controllers} or in
  11365. * {@link ng.$compileProvider#directive directives}.
  11366. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  11367. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  11368. *
  11369. * If you want to be notified whenever `$digest()` is called,
  11370. * you can register a `watchExpression` function with
  11371. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  11372. *
  11373. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  11374. *
  11375. * # Example
  11376. * ```js
  11377. var scope = ...;
  11378. scope.name = 'misko';
  11379. scope.counter = 0;
  11380. expect(scope.counter).toEqual(0);
  11381. scope.$watch('name', function(newValue, oldValue) {
  11382. scope.counter = scope.counter + 1;
  11383. });
  11384. expect(scope.counter).toEqual(0);
  11385. scope.$digest();
  11386. // the listener is always called during the first $digest loop after it was registered
  11387. expect(scope.counter).toEqual(1);
  11388. scope.$digest();
  11389. // but now it will not be called unless the value changes
  11390. expect(scope.counter).toEqual(1);
  11391. scope.name = 'adam';
  11392. scope.$digest();
  11393. expect(scope.counter).toEqual(2);
  11394. * ```
  11395. *
  11396. */
  11397. $digest: function() {
  11398. var watch, value, last,
  11399. watchers,
  11400. asyncQueue = this.$$asyncQueue,
  11401. postDigestQueue = this.$$postDigestQueue,
  11402. length,
  11403. dirty, ttl = TTL,
  11404. next, current, target = this,
  11405. watchLog = [],
  11406. logIdx, logMsg, asyncTask;
  11407. beginPhase('$digest');
  11408. // Check for changes to browser url that happened in sync before the call to $digest
  11409. $browser.$$checkUrlChange();
  11410. lastDirtyWatch = null;
  11411. do { // "while dirty" loop
  11412. dirty = false;
  11413. current = target;
  11414. while(asyncQueue.length) {
  11415. try {
  11416. asyncTask = asyncQueue.shift();
  11417. asyncTask.scope.$eval(asyncTask.expression);
  11418. } catch (e) {
  11419. clearPhase();
  11420. $exceptionHandler(e);
  11421. }
  11422. lastDirtyWatch = null;
  11423. }
  11424. traverseScopesLoop:
  11425. do { // "traverse the scopes" loop
  11426. if ((watchers = current.$$watchers)) {
  11427. // process our watches
  11428. length = watchers.length;
  11429. while (length--) {
  11430. try {
  11431. watch = watchers[length];
  11432. // Most common watches are on primitives, in which case we can short
  11433. // circuit it with === operator, only when === fails do we use .equals
  11434. if (watch) {
  11435. if ((value = watch.get(current)) !== (last = watch.last) &&
  11436. !(watch.eq
  11437. ? equals(value, last)
  11438. : (typeof value === 'number' && typeof last === 'number'
  11439. && isNaN(value) && isNaN(last)))) {
  11440. dirty = true;
  11441. lastDirtyWatch = watch;
  11442. watch.last = watch.eq ? copy(value, null) : value;
  11443. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11444. if (ttl < 5) {
  11445. logIdx = 4 - ttl;
  11446. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11447. logMsg = (isFunction(watch.exp))
  11448. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11449. : watch.exp;
  11450. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11451. watchLog[logIdx].push(logMsg);
  11452. }
  11453. } else if (watch === lastDirtyWatch) {
  11454. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11455. // have already been tested.
  11456. dirty = false;
  11457. break traverseScopesLoop;
  11458. }
  11459. }
  11460. } catch (e) {
  11461. clearPhase();
  11462. $exceptionHandler(e);
  11463. }
  11464. }
  11465. }
  11466. // Insanity Warning: scope depth-first traversal
  11467. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11468. // this piece should be kept in sync with the traversal in $broadcast
  11469. if (!(next = (current.$$childHead ||
  11470. (current !== target && current.$$nextSibling)))) {
  11471. while(current !== target && !(next = current.$$nextSibling)) {
  11472. current = current.$parent;
  11473. }
  11474. }
  11475. } while ((current = next));
  11476. // `break traverseScopesLoop;` takes us to here
  11477. if((dirty || asyncQueue.length) && !(ttl--)) {
  11478. clearPhase();
  11479. throw $rootScopeMinErr('infdig',
  11480. '{0} $digest() iterations reached. Aborting!\n' +
  11481. 'Watchers fired in the last 5 iterations: {1}',
  11482. TTL, toJson(watchLog));
  11483. }
  11484. } while (dirty || asyncQueue.length);
  11485. clearPhase();
  11486. while(postDigestQueue.length) {
  11487. try {
  11488. postDigestQueue.shift()();
  11489. } catch (e) {
  11490. $exceptionHandler(e);
  11491. }
  11492. }
  11493. },
  11494. /**
  11495. * @ngdoc event
  11496. * @name $rootScope.Scope#$destroy
  11497. * @eventType broadcast on scope being destroyed
  11498. *
  11499. * @description
  11500. * Broadcasted when a scope and its children are being destroyed.
  11501. *
  11502. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11503. * clean up DOM bindings before an element is removed from the DOM.
  11504. */
  11505. /**
  11506. * @ngdoc method
  11507. * @name $rootScope.Scope#$destroy
  11508. * @kind function
  11509. *
  11510. * @description
  11511. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11512. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11513. * propagate to the current scope and its children. Removal also implies that the current
  11514. * scope is eligible for garbage collection.
  11515. *
  11516. * The `$destroy()` is usually used by directives such as
  11517. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11518. * unrolling of the loop.
  11519. *
  11520. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11521. * Application code can register a `$destroy` event handler that will give it a chance to
  11522. * perform any necessary cleanup.
  11523. *
  11524. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11525. * clean up DOM bindings before an element is removed from the DOM.
  11526. */
  11527. $destroy: function() {
  11528. // we can't destroy the root scope or a scope that has been already destroyed
  11529. if (this.$$destroyed) return;
  11530. var parent = this.$parent;
  11531. this.$broadcast('$destroy');
  11532. this.$$destroyed = true;
  11533. if (this === $rootScope) return;
  11534. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11535. // sever all the references to parent scopes (after this cleanup, the current scope should
  11536. // not be retained by any of our references and should be eligible for garbage collection)
  11537. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11538. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11539. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11540. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11541. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11542. // and inline caches.
  11543. //
  11544. // see:
  11545. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11546. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11547. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11548. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11549. this.$$childTail = this.$root = null;
  11550. // don't reset these to null in case some async task tries to register a listener/watch/task
  11551. this.$$listeners = {};
  11552. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11553. // prevent NPEs since these methods have references to properties we nulled out
  11554. this.$destroy = this.$digest = this.$apply = noop;
  11555. this.$on = this.$watch = function() { return noop; };
  11556. },
  11557. /**
  11558. * @ngdoc method
  11559. * @name $rootScope.Scope#$eval
  11560. * @kind function
  11561. *
  11562. * @description
  11563. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11564. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11565. * expressions.
  11566. *
  11567. * # Example
  11568. * ```js
  11569. var scope = ng.$rootScope.Scope();
  11570. scope.a = 1;
  11571. scope.b = 2;
  11572. expect(scope.$eval('a+b')).toEqual(3);
  11573. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11574. * ```
  11575. *
  11576. * @param {(string|function())=} expression An angular expression to be executed.
  11577. *
  11578. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11579. * - `function(scope)`: execute the function with the current `scope` parameter.
  11580. *
  11581. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11582. * @returns {*} The result of evaluating the expression.
  11583. */
  11584. $eval: function(expr, locals) {
  11585. return $parse(expr)(this, locals);
  11586. },
  11587. /**
  11588. * @ngdoc method
  11589. * @name $rootScope.Scope#$evalAsync
  11590. * @kind function
  11591. *
  11592. * @description
  11593. * Executes the expression on the current scope at a later point in time.
  11594. *
  11595. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11596. * that:
  11597. *
  11598. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11599. * rendering).
  11600. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11601. * `expression` execution.
  11602. *
  11603. * Any exceptions from the execution of the expression are forwarded to the
  11604. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11605. *
  11606. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11607. * will be scheduled. However, it is encouraged to always call code that changes the model
  11608. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11609. *
  11610. * @param {(string|function())=} expression An angular expression to be executed.
  11611. *
  11612. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11613. * - `function(scope)`: execute the function with the current `scope` parameter.
  11614. *
  11615. */
  11616. $evalAsync: function(expr) {
  11617. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11618. // task also schedule async auto-flush
  11619. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11620. $browser.defer(function() {
  11621. if ($rootScope.$$asyncQueue.length) {
  11622. $rootScope.$digest();
  11623. }
  11624. });
  11625. }
  11626. this.$$asyncQueue.push({scope: this, expression: expr});
  11627. },
  11628. $$postDigest : function(fn) {
  11629. this.$$postDigestQueue.push(fn);
  11630. },
  11631. /**
  11632. * @ngdoc method
  11633. * @name $rootScope.Scope#$apply
  11634. * @kind function
  11635. *
  11636. * @description
  11637. * `$apply()` is used to execute an expression in angular from outside of the angular
  11638. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11639. * Because we are calling into the angular framework we need to perform proper scope life
  11640. * cycle of {@link ng.$exceptionHandler exception handling},
  11641. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11642. *
  11643. * ## Life cycle
  11644. *
  11645. * # Pseudo-Code of `$apply()`
  11646. * ```js
  11647. function $apply(expr) {
  11648. try {
  11649. return $eval(expr);
  11650. } catch (e) {
  11651. $exceptionHandler(e);
  11652. } finally {
  11653. $root.$digest();
  11654. }
  11655. }
  11656. * ```
  11657. *
  11658. *
  11659. * Scope's `$apply()` method transitions through the following stages:
  11660. *
  11661. * 1. The {@link guide/expression expression} is executed using the
  11662. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11663. * 2. Any exceptions from the execution of the expression are forwarded to the
  11664. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11665. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11666. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11667. *
  11668. *
  11669. * @param {(string|function())=} exp An angular expression to be executed.
  11670. *
  11671. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11672. * - `function(scope)`: execute the function with current `scope` parameter.
  11673. *
  11674. * @returns {*} The result of evaluating the expression.
  11675. */
  11676. $apply: function(expr) {
  11677. try {
  11678. beginPhase('$apply');
  11679. return this.$eval(expr);
  11680. } catch (e) {
  11681. $exceptionHandler(e);
  11682. } finally {
  11683. clearPhase();
  11684. try {
  11685. $rootScope.$digest();
  11686. } catch (e) {
  11687. $exceptionHandler(e);
  11688. throw e;
  11689. }
  11690. }
  11691. },
  11692. /**
  11693. * @ngdoc method
  11694. * @name $rootScope.Scope#$on
  11695. * @kind function
  11696. *
  11697. * @description
  11698. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11699. * discussion of event life cycle.
  11700. *
  11701. * The event listener function format is: `function(event, args...)`. The `event` object
  11702. * passed into the listener has the following attributes:
  11703. *
  11704. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11705. * `$broadcast`-ed.
  11706. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11707. * - `name` - `{string}`: name of the event.
  11708. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11709. * further event propagation (available only for events that were `$emit`-ed).
  11710. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11711. * to true.
  11712. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11713. *
  11714. * @param {string} name Event name to listen on.
  11715. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11716. * @returns {function()} Returns a deregistration function for this listener.
  11717. */
  11718. $on: function(name, listener) {
  11719. var namedListeners = this.$$listeners[name];
  11720. if (!namedListeners) {
  11721. this.$$listeners[name] = namedListeners = [];
  11722. }
  11723. namedListeners.push(listener);
  11724. var current = this;
  11725. do {
  11726. if (!current.$$listenerCount[name]) {
  11727. current.$$listenerCount[name] = 0;
  11728. }
  11729. current.$$listenerCount[name]++;
  11730. } while ((current = current.$parent));
  11731. var self = this;
  11732. return function() {
  11733. var indexOfListener = indexOf(namedListeners, listener);
  11734. if (indexOfListener !== -1) {
  11735. namedListeners[indexOfListener] = null;
  11736. decrementListenerCount(self, 1, name);
  11737. }
  11738. };
  11739. },
  11740. /**
  11741. * @ngdoc method
  11742. * @name $rootScope.Scope#$emit
  11743. * @kind function
  11744. *
  11745. * @description
  11746. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11747. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11748. *
  11749. * The event life cycle starts at the scope on which `$emit` was called. All
  11750. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11751. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11752. * registered listeners along the way. The event will stop propagating if one of the listeners
  11753. * cancels it.
  11754. *
  11755. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11756. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11757. *
  11758. * @param {string} name Event name to emit.
  11759. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11760. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11761. */
  11762. $emit: function(name, args) {
  11763. var empty = [],
  11764. namedListeners,
  11765. scope = this,
  11766. stopPropagation = false,
  11767. event = {
  11768. name: name,
  11769. targetScope: scope,
  11770. stopPropagation: function() {stopPropagation = true;},
  11771. preventDefault: function() {
  11772. event.defaultPrevented = true;
  11773. },
  11774. defaultPrevented: false
  11775. },
  11776. listenerArgs = concat([event], arguments, 1),
  11777. i, length;
  11778. do {
  11779. namedListeners = scope.$$listeners[name] || empty;
  11780. event.currentScope = scope;
  11781. for (i=0, length=namedListeners.length; i<length; i++) {
  11782. // if listeners were deregistered, defragment the array
  11783. if (!namedListeners[i]) {
  11784. namedListeners.splice(i, 1);
  11785. i--;
  11786. length--;
  11787. continue;
  11788. }
  11789. try {
  11790. //allow all listeners attached to the current scope to run
  11791. namedListeners[i].apply(null, listenerArgs);
  11792. } catch (e) {
  11793. $exceptionHandler(e);
  11794. }
  11795. }
  11796. //if any listener on the current scope stops propagation, prevent bubbling
  11797. if (stopPropagation) return event;
  11798. //traverse upwards
  11799. scope = scope.$parent;
  11800. } while (scope);
  11801. return event;
  11802. },
  11803. /**
  11804. * @ngdoc method
  11805. * @name $rootScope.Scope#$broadcast
  11806. * @kind function
  11807. *
  11808. * @description
  11809. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11810. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11811. *
  11812. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11813. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11814. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11815. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11816. *
  11817. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11818. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11819. *
  11820. * @param {string} name Event name to broadcast.
  11821. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11822. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11823. */
  11824. $broadcast: function(name, args) {
  11825. var target = this,
  11826. current = target,
  11827. next = target,
  11828. event = {
  11829. name: name,
  11830. targetScope: target,
  11831. preventDefault: function() {
  11832. event.defaultPrevented = true;
  11833. },
  11834. defaultPrevented: false
  11835. },
  11836. listenerArgs = concat([event], arguments, 1),
  11837. listeners, i, length;
  11838. //down while you can, then up and next sibling or up and next sibling until back at root
  11839. while ((current = next)) {
  11840. event.currentScope = current;
  11841. listeners = current.$$listeners[name] || [];
  11842. for (i=0, length = listeners.length; i<length; i++) {
  11843. // if listeners were deregistered, defragment the array
  11844. if (!listeners[i]) {
  11845. listeners.splice(i, 1);
  11846. i--;
  11847. length--;
  11848. continue;
  11849. }
  11850. try {
  11851. listeners[i].apply(null, listenerArgs);
  11852. } catch(e) {
  11853. $exceptionHandler(e);
  11854. }
  11855. }
  11856. // Insanity Warning: scope depth-first traversal
  11857. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11858. // this piece should be kept in sync with the traversal in $digest
  11859. // (though it differs due to having the extra check for $$listenerCount)
  11860. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11861. (current !== target && current.$$nextSibling)))) {
  11862. while(current !== target && !(next = current.$$nextSibling)) {
  11863. current = current.$parent;
  11864. }
  11865. }
  11866. }
  11867. return event;
  11868. }
  11869. };
  11870. var $rootScope = new Scope();
  11871. return $rootScope;
  11872. function beginPhase(phase) {
  11873. if ($rootScope.$$phase) {
  11874. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11875. }
  11876. $rootScope.$$phase = phase;
  11877. }
  11878. function clearPhase() {
  11879. $rootScope.$$phase = null;
  11880. }
  11881. function compileToFn(exp, name) {
  11882. var fn = $parse(exp);
  11883. assertArgFn(fn, name);
  11884. return fn;
  11885. }
  11886. function decrementListenerCount(current, count, name) {
  11887. do {
  11888. current.$$listenerCount[name] -= count;
  11889. if (current.$$listenerCount[name] === 0) {
  11890. delete current.$$listenerCount[name];
  11891. }
  11892. } while ((current = current.$parent));
  11893. }
  11894. /**
  11895. * function used as an initial value for watchers.
  11896. * because it's unique we can easily tell it apart from other values
  11897. */
  11898. function initWatchVal() {}
  11899. }];
  11900. }
  11901. /**
  11902. * @ngdoc service
  11903. * @name $rootElement
  11904. *
  11905. * @description
  11906. * The root element of Angular application. This is either the element where {@link
  11907. * ng.directive:ngApp ngApp} was declared or the element passed into
  11908. * {@link angular.bootstrap}. The element represent the root element of application. It is also the
  11909. * location where the applications {@link auto.$injector $injector} service gets
  11910. * published, it can be retrieved using `$rootElement.injector()`.
  11911. */
  11912. // the implementation is in angular.bootstrap
  11913. /**
  11914. * @description
  11915. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11916. */
  11917. function $$SanitizeUriProvider() {
  11918. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11919. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file):|data:image\/)/;
  11920. /**
  11921. * @description
  11922. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11923. * urls during a[href] sanitization.
  11924. *
  11925. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11926. *
  11927. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11928. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11929. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11930. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11931. *
  11932. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11933. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11934. * chaining otherwise.
  11935. */
  11936. this.aHrefSanitizationWhitelist = function(regexp) {
  11937. if (isDefined(regexp)) {
  11938. aHrefSanitizationWhitelist = regexp;
  11939. return this;
  11940. }
  11941. return aHrefSanitizationWhitelist;
  11942. };
  11943. /**
  11944. * @description
  11945. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11946. * urls during img[src] sanitization.
  11947. *
  11948. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11949. *
  11950. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11951. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11952. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11953. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11954. *
  11955. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11956. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11957. * chaining otherwise.
  11958. */
  11959. this.imgSrcSanitizationWhitelist = function(regexp) {
  11960. if (isDefined(regexp)) {
  11961. imgSrcSanitizationWhitelist = regexp;
  11962. return this;
  11963. }
  11964. return imgSrcSanitizationWhitelist;
  11965. };
  11966. this.$get = function() {
  11967. return function sanitizeUri(uri, isImage) {
  11968. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11969. var normalizedVal;
  11970. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11971. if (!msie || msie >= 8 ) {
  11972. normalizedVal = urlResolve(uri).href;
  11973. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11974. return 'unsafe:'+normalizedVal;
  11975. }
  11976. }
  11977. return uri;
  11978. };
  11979. };
  11980. }
  11981. var $sceMinErr = minErr('$sce');
  11982. var SCE_CONTEXTS = {
  11983. HTML: 'html',
  11984. CSS: 'css',
  11985. URL: 'url',
  11986. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11987. // url. (e.g. ng-include, script src, templateUrl)
  11988. RESOURCE_URL: 'resourceUrl',
  11989. JS: 'js'
  11990. };
  11991. // Helper functions follow.
  11992. // Copied from:
  11993. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11994. // Prereq: s is a string.
  11995. function escapeForRegexp(s) {
  11996. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11997. replace(/\x08/g, '\\x08');
  11998. }
  11999. function adjustMatcher(matcher) {
  12000. if (matcher === 'self') {
  12001. return matcher;
  12002. } else if (isString(matcher)) {
  12003. // Strings match exactly except for 2 wildcards - '*' and '**'.
  12004. // '*' matches any character except those from the set ':/.?&'.
  12005. // '**' matches any character (like .* in a RegExp).
  12006. // More than 2 *'s raises an error as it's ill defined.
  12007. if (matcher.indexOf('***') > -1) {
  12008. throw $sceMinErr('iwcard',
  12009. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  12010. }
  12011. matcher = escapeForRegexp(matcher).
  12012. replace('\\*\\*', '.*').
  12013. replace('\\*', '[^:/.?&;]*');
  12014. return new RegExp('^' + matcher + '$');
  12015. } else if (isRegExp(matcher)) {
  12016. // The only other type of matcher allowed is a Regexp.
  12017. // Match entire URL / disallow partial matches.
  12018. // Flags are reset (i.e. no global, ignoreCase or multiline)
  12019. return new RegExp('^' + matcher.source + '$');
  12020. } else {
  12021. throw $sceMinErr('imatcher',
  12022. 'Matchers may only be "self", string patterns or RegExp objects');
  12023. }
  12024. }
  12025. function adjustMatchers(matchers) {
  12026. var adjustedMatchers = [];
  12027. if (isDefined(matchers)) {
  12028. forEach(matchers, function(matcher) {
  12029. adjustedMatchers.push(adjustMatcher(matcher));
  12030. });
  12031. }
  12032. return adjustedMatchers;
  12033. }
  12034. /**
  12035. * @ngdoc service
  12036. * @name $sceDelegate
  12037. * @kind function
  12038. *
  12039. * @description
  12040. *
  12041. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  12042. * Contextual Escaping (SCE)} services to AngularJS.
  12043. *
  12044. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  12045. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  12046. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  12047. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  12048. * work because `$sce` delegates to `$sceDelegate` for these operations.
  12049. *
  12050. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  12051. *
  12052. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  12053. * can override it completely to change the behavior of `$sce`, the common case would
  12054. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  12055. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  12056. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  12057. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  12058. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  12059. */
  12060. /**
  12061. * @ngdoc provider
  12062. * @name $sceDelegateProvider
  12063. * @description
  12064. *
  12065. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  12066. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  12067. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  12068. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  12069. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  12070. *
  12071. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  12072. * Strict Contextual Escaping (SCE)}.
  12073. *
  12074. * **Example**: Consider the following case. <a name="example"></a>
  12075. *
  12076. * - your app is hosted at url `http://myapp.example.com/`
  12077. * - but some of your templates are hosted on other domains you control such as
  12078. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  12079. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  12080. *
  12081. * Here is what a secure configuration for this scenario might look like:
  12082. *
  12083. * ```
  12084. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  12085. * $sceDelegateProvider.resourceUrlWhitelist([
  12086. * // Allow same origin resource loads.
  12087. * 'self',
  12088. * // Allow loading from our assets domain. Notice the difference between * and **.
  12089. * 'http://srv*.assets.example.com/**'
  12090. * ]);
  12091. *
  12092. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  12093. * $sceDelegateProvider.resourceUrlBlacklist([
  12094. * 'http://myapp.example.com/clickThru**'
  12095. * ]);
  12096. * });
  12097. * ```
  12098. */
  12099. function $SceDelegateProvider() {
  12100. this.SCE_CONTEXTS = SCE_CONTEXTS;
  12101. // Resource URLs can also be trusted by policy.
  12102. var resourceUrlWhitelist = ['self'],
  12103. resourceUrlBlacklist = [];
  12104. /**
  12105. * @ngdoc method
  12106. * @name $sceDelegateProvider#resourceUrlWhitelist
  12107. * @kind function
  12108. *
  12109. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  12110. * provided. This must be an array or null. A snapshot of this array is used so further
  12111. * changes to the array are ignored.
  12112. *
  12113. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12114. * allowed in this array.
  12115. *
  12116. * Note: **an empty whitelist array will block all URLs**!
  12117. *
  12118. * @return {Array} the currently set whitelist array.
  12119. *
  12120. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  12121. * same origin resource requests.
  12122. *
  12123. * @description
  12124. * Sets/Gets the whitelist of trusted resource URLs.
  12125. */
  12126. this.resourceUrlWhitelist = function (value) {
  12127. if (arguments.length) {
  12128. resourceUrlWhitelist = adjustMatchers(value);
  12129. }
  12130. return resourceUrlWhitelist;
  12131. };
  12132. /**
  12133. * @ngdoc method
  12134. * @name $sceDelegateProvider#resourceUrlBlacklist
  12135. * @kind function
  12136. *
  12137. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  12138. * provided. This must be an array or null. A snapshot of this array is used so further
  12139. * changes to the array are ignored.
  12140. *
  12141. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12142. * allowed in this array.
  12143. *
  12144. * The typical usage for the blacklist is to **block
  12145. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  12146. * these would otherwise be trusted but actually return content from the redirected domain.
  12147. *
  12148. * Finally, **the blacklist overrides the whitelist** and has the final say.
  12149. *
  12150. * @return {Array} the currently set blacklist array.
  12151. *
  12152. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  12153. * is no blacklist.)
  12154. *
  12155. * @description
  12156. * Sets/Gets the blacklist of trusted resource URLs.
  12157. */
  12158. this.resourceUrlBlacklist = function (value) {
  12159. if (arguments.length) {
  12160. resourceUrlBlacklist = adjustMatchers(value);
  12161. }
  12162. return resourceUrlBlacklist;
  12163. };
  12164. this.$get = ['$injector', function($injector) {
  12165. var htmlSanitizer = function htmlSanitizer(html) {
  12166. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12167. };
  12168. if ($injector.has('$sanitize')) {
  12169. htmlSanitizer = $injector.get('$sanitize');
  12170. }
  12171. function matchUrl(matcher, parsedUrl) {
  12172. if (matcher === 'self') {
  12173. return urlIsSameOrigin(parsedUrl);
  12174. } else {
  12175. // definitely a regex. See adjustMatchers()
  12176. return !!matcher.exec(parsedUrl.href);
  12177. }
  12178. }
  12179. function isResourceUrlAllowedByPolicy(url) {
  12180. var parsedUrl = urlResolve(url.toString());
  12181. var i, n, allowed = false;
  12182. // Ensure that at least one item from the whitelist allows this url.
  12183. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  12184. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  12185. allowed = true;
  12186. break;
  12187. }
  12188. }
  12189. if (allowed) {
  12190. // Ensure that no item from the blacklist blocked this url.
  12191. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  12192. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  12193. allowed = false;
  12194. break;
  12195. }
  12196. }
  12197. }
  12198. return allowed;
  12199. }
  12200. function generateHolderType(Base) {
  12201. var holderType = function TrustedValueHolderType(trustedValue) {
  12202. this.$$unwrapTrustedValue = function() {
  12203. return trustedValue;
  12204. };
  12205. };
  12206. if (Base) {
  12207. holderType.prototype = new Base();
  12208. }
  12209. holderType.prototype.valueOf = function sceValueOf() {
  12210. return this.$$unwrapTrustedValue();
  12211. };
  12212. holderType.prototype.toString = function sceToString() {
  12213. return this.$$unwrapTrustedValue().toString();
  12214. };
  12215. return holderType;
  12216. }
  12217. var trustedValueHolderBase = generateHolderType(),
  12218. byType = {};
  12219. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  12220. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  12221. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  12222. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  12223. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  12224. /**
  12225. * @ngdoc method
  12226. * @name $sceDelegate#trustAs
  12227. *
  12228. * @description
  12229. * Returns an object that is trusted by angular for use in specified strict
  12230. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  12231. * attribute interpolation, any dom event binding attribute interpolation
  12232. * such as for onclick, etc.) that uses the provided value.
  12233. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  12234. *
  12235. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12236. * resourceUrl, html, js and css.
  12237. * @param {*} value The value that that should be considered trusted/safe.
  12238. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12239. * where Angular expects a $sce.trustAs() return value.
  12240. */
  12241. function trustAs(type, trustedValue) {
  12242. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12243. if (!Constructor) {
  12244. throw $sceMinErr('icontext',
  12245. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  12246. type, trustedValue);
  12247. }
  12248. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  12249. return trustedValue;
  12250. }
  12251. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  12252. // mutable objects, we ensure here that the value passed in is actually a string.
  12253. if (typeof trustedValue !== 'string') {
  12254. throw $sceMinErr('itype',
  12255. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  12256. type);
  12257. }
  12258. return new Constructor(trustedValue);
  12259. }
  12260. /**
  12261. * @ngdoc method
  12262. * @name $sceDelegate#valueOf
  12263. *
  12264. * @description
  12265. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  12266. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  12267. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  12268. *
  12269. * If the passed parameter is not a value that had been returned by {@link
  12270. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  12271. *
  12272. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  12273. * call or anything else.
  12274. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  12275. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  12276. * `value` unchanged.
  12277. */
  12278. function valueOf(maybeTrusted) {
  12279. if (maybeTrusted instanceof trustedValueHolderBase) {
  12280. return maybeTrusted.$$unwrapTrustedValue();
  12281. } else {
  12282. return maybeTrusted;
  12283. }
  12284. }
  12285. /**
  12286. * @ngdoc method
  12287. * @name $sceDelegate#getTrusted
  12288. *
  12289. * @description
  12290. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  12291. * returns the originally supplied value if the queried context type is a supertype of the
  12292. * created type. If this condition isn't satisfied, throws an exception.
  12293. *
  12294. * @param {string} type The kind of context in which this value is to be used.
  12295. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  12296. * `$sceDelegate.trustAs`} call.
  12297. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  12298. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  12299. */
  12300. function getTrusted(type, maybeTrusted) {
  12301. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  12302. return maybeTrusted;
  12303. }
  12304. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12305. if (constructor && maybeTrusted instanceof constructor) {
  12306. return maybeTrusted.$$unwrapTrustedValue();
  12307. }
  12308. // If we get here, then we may only take one of two actions.
  12309. // 1. sanitize the value for the requested type, or
  12310. // 2. throw an exception.
  12311. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  12312. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  12313. return maybeTrusted;
  12314. } else {
  12315. throw $sceMinErr('insecurl',
  12316. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  12317. maybeTrusted.toString());
  12318. }
  12319. } else if (type === SCE_CONTEXTS.HTML) {
  12320. return htmlSanitizer(maybeTrusted);
  12321. }
  12322. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12323. }
  12324. return { trustAs: trustAs,
  12325. getTrusted: getTrusted,
  12326. valueOf: valueOf };
  12327. }];
  12328. }
  12329. /**
  12330. * @ngdoc provider
  12331. * @name $sceProvider
  12332. * @description
  12333. *
  12334. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  12335. * - enable/disable Strict Contextual Escaping (SCE) in a module
  12336. * - override the default implementation with a custom delegate
  12337. *
  12338. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  12339. */
  12340. /* jshint maxlen: false*/
  12341. /**
  12342. * @ngdoc service
  12343. * @name $sce
  12344. * @kind function
  12345. *
  12346. * @description
  12347. *
  12348. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  12349. *
  12350. * # Strict Contextual Escaping
  12351. *
  12352. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  12353. * contexts to result in a value that is marked as safe to use for that context. One example of
  12354. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  12355. * to these contexts as privileged or SCE contexts.
  12356. *
  12357. * As of version 1.2, Angular ships with SCE enabled by default.
  12358. *
  12359. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  12360. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  12361. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  12362. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  12363. * to the top of your HTML document.
  12364. *
  12365. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  12366. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  12367. *
  12368. * Here's an example of a binding in a privileged context:
  12369. *
  12370. * ```
  12371. * <input ng-model="userHtml">
  12372. * <div ng-bind-html="userHtml"></div>
  12373. * ```
  12374. *
  12375. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  12376. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  12377. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  12378. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  12379. * security vulnerabilities.)
  12380. *
  12381. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  12382. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  12383. *
  12384. * How would you ensure that every place that used these types of bindings was bound to a value that
  12385. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  12386. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  12387. * properties/fields and forgot to update the binding to the sanitized value?
  12388. *
  12389. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  12390. * determine that something explicitly says it's safe to use a value for binding in that
  12391. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  12392. * for those values that you can easily tell are safe - because they were received from your server,
  12393. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  12394. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  12395. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  12396. *
  12397. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  12398. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  12399. * obtain values that will be accepted by SCE / privileged contexts.
  12400. *
  12401. *
  12402. * ## How does it work?
  12403. *
  12404. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  12405. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  12406. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  12407. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  12408. *
  12409. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  12410. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  12411. * simplified):
  12412. *
  12413. * ```
  12414. * var ngBindHtmlDirective = ['$sce', function($sce) {
  12415. * return function(scope, element, attr) {
  12416. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  12417. * element.html(value || '');
  12418. * });
  12419. * };
  12420. * }];
  12421. * ```
  12422. *
  12423. * ## Impact on loading templates
  12424. *
  12425. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12426. * `templateUrl`'s specified by {@link guide/directive directives}.
  12427. *
  12428. * By default, Angular only loads templates from the same domain and protocol as the application
  12429. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12430. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12431. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12432. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12433. *
  12434. * *Please note*:
  12435. * The browser's
  12436. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12437. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12438. * policy apply in addition to this and may further restrict whether the template is successfully
  12439. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12440. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12441. * browsers.
  12442. *
  12443. * ## This feels like too much overhead for the developer?
  12444. *
  12445. * It's important to remember that SCE only applies to interpolation expressions.
  12446. *
  12447. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12448. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12449. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12450. *
  12451. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12452. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12453. *
  12454. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12455. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12456. * It blocks loading templates from other domains or loading templates over http from an https
  12457. * served document. You can change these by setting your own custom {@link
  12458. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12459. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12460. *
  12461. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12462. * application that's secure and can be audited to verify that with much more ease than bolting
  12463. * security onto an application later.
  12464. *
  12465. * <a name="contexts"></a>
  12466. * ## What trusted context types are supported?
  12467. *
  12468. * | Context | Notes |
  12469. * |---------------------|----------------|
  12470. * | `$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. |
  12471. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12472. * | `$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. |
  12473. * | `$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. |
  12474. * | `$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. |
  12475. *
  12476. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12477. *
  12478. * Each element in these arrays must be one of the following:
  12479. *
  12480. * - **'self'**
  12481. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12482. * domain** as the application document using the **same protocol**.
  12483. * - **String** (except the special value `'self'`)
  12484. * - The string is matched against the full *normalized / absolute URL* of the resource
  12485. * being tested (substring matches are not good enough.)
  12486. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12487. * match themselves.
  12488. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12489. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12490. * in a whitelist.
  12491. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12492. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12493. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12494. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  12495. * http://foo.example.com/templates/**).
  12496. * - **RegExp** (*see caveat below*)
  12497. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12498. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12499. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12500. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12501. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12502. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12503. * is highly recommended to use the string patterns and only fall back to regular expressions
  12504. * if they as a last resort.
  12505. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12506. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12507. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12508. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12509. * - If you are generating your JavaScript from some other templating engine (not
  12510. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12511. * remember to escape your regular expression (and be aware that you might need more than
  12512. * one level of escaping depending on your templating engine and the way you interpolated
  12513. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12514. * enough before coding your own. e.g. Ruby has
  12515. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12516. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12517. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12518. * Closure library's [goog.string.regExpEscape(s)](
  12519. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12520. *
  12521. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12522. *
  12523. * ## Show me an example using SCE.
  12524. *
  12525. * <example module="mySceApp" deps="angular-sanitize.js">
  12526. * <file name="index.html">
  12527. * <div ng-controller="myAppController as myCtrl">
  12528. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12529. * <b>User comments</b><br>
  12530. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12531. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12532. * exploit.
  12533. * <div class="well">
  12534. * <div ng-repeat="userComment in myCtrl.userComments">
  12535. * <b>{{userComment.name}}</b>:
  12536. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12537. * <br>
  12538. * </div>
  12539. * </div>
  12540. * </div>
  12541. * </file>
  12542. *
  12543. * <file name="script.js">
  12544. * var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12545. *
  12546. * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12547. * var self = this;
  12548. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12549. * self.userComments = userComments;
  12550. * });
  12551. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12552. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12553. * 'sanitization.&quot;">Hover over this text.</span>');
  12554. * });
  12555. * </file>
  12556. *
  12557. * <file name="test_data.json">
  12558. * [
  12559. * { "name": "Alice",
  12560. * "htmlComment":
  12561. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12562. * },
  12563. * { "name": "Bob",
  12564. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12565. * }
  12566. * ]
  12567. * </file>
  12568. *
  12569. * <file name="protractor.js" type="protractor">
  12570. * describe('SCE doc demo', function() {
  12571. * it('should sanitize untrusted values', function() {
  12572. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  12573. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12574. * });
  12575. *
  12576. * it('should NOT sanitize explicitly trusted values', function() {
  12577. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12578. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12579. * 'sanitization.&quot;">Hover over this text.</span>');
  12580. * });
  12581. * });
  12582. * </file>
  12583. * </example>
  12584. *
  12585. *
  12586. *
  12587. * ## Can I disable SCE completely?
  12588. *
  12589. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12590. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12591. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12592. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12593. * you're migrating them a module at a time.
  12594. *
  12595. * That said, here's how you can completely disable SCE:
  12596. *
  12597. * ```
  12598. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12599. * // Completely disable SCE. For demonstration purposes only!
  12600. * // Do not use in new projects.
  12601. * $sceProvider.enabled(false);
  12602. * });
  12603. * ```
  12604. *
  12605. */
  12606. /* jshint maxlen: 100 */
  12607. function $SceProvider() {
  12608. var enabled = true;
  12609. /**
  12610. * @ngdoc method
  12611. * @name $sceProvider#enabled
  12612. * @kind function
  12613. *
  12614. * @param {boolean=} value If provided, then enables/disables SCE.
  12615. * @return {boolean} true if SCE is enabled, false otherwise.
  12616. *
  12617. * @description
  12618. * Enables/disables SCE and returns the current value.
  12619. */
  12620. this.enabled = function (value) {
  12621. if (arguments.length) {
  12622. enabled = !!value;
  12623. }
  12624. return enabled;
  12625. };
  12626. /* Design notes on the default implementation for SCE.
  12627. *
  12628. * The API contract for the SCE delegate
  12629. * -------------------------------------
  12630. * The SCE delegate object must provide the following 3 methods:
  12631. *
  12632. * - trustAs(contextEnum, value)
  12633. * This method is used to tell the SCE service that the provided value is OK to use in the
  12634. * contexts specified by contextEnum. It must return an object that will be accepted by
  12635. * getTrusted() for a compatible contextEnum and return this value.
  12636. *
  12637. * - valueOf(value)
  12638. * For values that were not produced by trustAs(), return them as is. For values that were
  12639. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12640. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12641. * such a value.
  12642. *
  12643. * - getTrusted(contextEnum, value)
  12644. * This function should return the a value that is safe to use in the context specified by
  12645. * contextEnum or throw and exception otherwise.
  12646. *
  12647. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12648. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12649. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12650. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12651. * return the same object passed in if it was found in the registry under a compatible context or
  12652. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12653. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12654. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12655. *
  12656. *
  12657. * A note on the inheritance model for SCE contexts
  12658. * ------------------------------------------------
  12659. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12660. * is purely an implementation details.
  12661. *
  12662. * The contract is simply this:
  12663. *
  12664. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12665. * will also succeed.
  12666. *
  12667. * Inheritance happens to capture this in a natural way. In some future, we
  12668. * may not use inheritance anymore. That is OK because no code outside of
  12669. * sce.js and sceSpecs.js would need to be aware of this detail.
  12670. */
  12671. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12672. $parse, $sniffer, $sceDelegate) {
  12673. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12674. // the "expression(javascript expression)" syntax which is insecure.
  12675. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12676. throw $sceMinErr('iequirks',
  12677. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12678. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12679. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12680. }
  12681. var sce = shallowCopy(SCE_CONTEXTS);
  12682. /**
  12683. * @ngdoc method
  12684. * @name $sce#isEnabled
  12685. * @kind function
  12686. *
  12687. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12688. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12689. *
  12690. * @description
  12691. * Returns a boolean indicating if SCE is enabled.
  12692. */
  12693. sce.isEnabled = function () {
  12694. return enabled;
  12695. };
  12696. sce.trustAs = $sceDelegate.trustAs;
  12697. sce.getTrusted = $sceDelegate.getTrusted;
  12698. sce.valueOf = $sceDelegate.valueOf;
  12699. if (!enabled) {
  12700. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12701. sce.valueOf = identity;
  12702. }
  12703. /**
  12704. * @ngdoc method
  12705. * @name $sce#parseAs
  12706. *
  12707. * @description
  12708. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12709. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12710. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12711. * *result*)}
  12712. *
  12713. * @param {string} type The kind of SCE context in which this result will be used.
  12714. * @param {string} expression String expression to compile.
  12715. * @returns {function(context, locals)} a function which represents the compiled expression:
  12716. *
  12717. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12718. * are evaluated against (typically a scope object).
  12719. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12720. * `context`.
  12721. */
  12722. sce.parseAs = function sceParseAs(type, expr) {
  12723. var parsed = $parse(expr);
  12724. if (parsed.literal && parsed.constant) {
  12725. return parsed;
  12726. } else {
  12727. return function sceParseAsTrusted(self, locals) {
  12728. return sce.getTrusted(type, parsed(self, locals));
  12729. };
  12730. }
  12731. };
  12732. /**
  12733. * @ngdoc method
  12734. * @name $sce#trustAs
  12735. *
  12736. * @description
  12737. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12738. * returns an object that is trusted by angular for use in specified strict contextual
  12739. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12740. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12741. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12742. * escaping.
  12743. *
  12744. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12745. * resource_url, html, js and css.
  12746. * @param {*} value The value that that should be considered trusted/safe.
  12747. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12748. * where Angular expects a $sce.trustAs() return value.
  12749. */
  12750. /**
  12751. * @ngdoc method
  12752. * @name $sce#trustAsHtml
  12753. *
  12754. * @description
  12755. * Shorthand method. `$sce.trustAsHtml(value)` →
  12756. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12757. *
  12758. * @param {*} value The value to trustAs.
  12759. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12760. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12761. * only accept expressions that are either literal constants or are the
  12762. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12763. */
  12764. /**
  12765. * @ngdoc method
  12766. * @name $sce#trustAsUrl
  12767. *
  12768. * @description
  12769. * Shorthand method. `$sce.trustAsUrl(value)` →
  12770. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12771. *
  12772. * @param {*} value The value to trustAs.
  12773. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12774. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12775. * only accept expressions that are either literal constants or are the
  12776. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12777. */
  12778. /**
  12779. * @ngdoc method
  12780. * @name $sce#trustAsResourceUrl
  12781. *
  12782. * @description
  12783. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12784. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12785. *
  12786. * @param {*} value The value to trustAs.
  12787. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12788. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12789. * only accept expressions that are either literal constants or are the return
  12790. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12791. */
  12792. /**
  12793. * @ngdoc method
  12794. * @name $sce#trustAsJs
  12795. *
  12796. * @description
  12797. * Shorthand method. `$sce.trustAsJs(value)` →
  12798. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12799. *
  12800. * @param {*} value The value to trustAs.
  12801. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12802. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12803. * only accept expressions that are either literal constants or are the
  12804. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12805. */
  12806. /**
  12807. * @ngdoc method
  12808. * @name $sce#getTrusted
  12809. *
  12810. * @description
  12811. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12812. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12813. * originally supplied value if the queried context type is a supertype of the created type.
  12814. * If this condition isn't satisfied, throws an exception.
  12815. *
  12816. * @param {string} type The kind of context in which this value is to be used.
  12817. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12818. * call.
  12819. * @returns {*} The value the was originally provided to
  12820. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12821. * Otherwise, throws an exception.
  12822. */
  12823. /**
  12824. * @ngdoc method
  12825. * @name $sce#getTrustedHtml
  12826. *
  12827. * @description
  12828. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12829. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12830. *
  12831. * @param {*} value The value to pass to `$sce.getTrusted`.
  12832. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12833. */
  12834. /**
  12835. * @ngdoc method
  12836. * @name $sce#getTrustedCss
  12837. *
  12838. * @description
  12839. * Shorthand method. `$sce.getTrustedCss(value)` →
  12840. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12841. *
  12842. * @param {*} value The value to pass to `$sce.getTrusted`.
  12843. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12844. */
  12845. /**
  12846. * @ngdoc method
  12847. * @name $sce#getTrustedUrl
  12848. *
  12849. * @description
  12850. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12851. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12852. *
  12853. * @param {*} value The value to pass to `$sce.getTrusted`.
  12854. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12855. */
  12856. /**
  12857. * @ngdoc method
  12858. * @name $sce#getTrustedResourceUrl
  12859. *
  12860. * @description
  12861. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12862. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12863. *
  12864. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12865. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12866. */
  12867. /**
  12868. * @ngdoc method
  12869. * @name $sce#getTrustedJs
  12870. *
  12871. * @description
  12872. * Shorthand method. `$sce.getTrustedJs(value)` →
  12873. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12874. *
  12875. * @param {*} value The value to pass to `$sce.getTrusted`.
  12876. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12877. */
  12878. /**
  12879. * @ngdoc method
  12880. * @name $sce#parseAsHtml
  12881. *
  12882. * @description
  12883. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12884. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12885. *
  12886. * @param {string} expression String expression to compile.
  12887. * @returns {function(context, locals)} a function which represents the compiled expression:
  12888. *
  12889. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12890. * are evaluated against (typically a scope object).
  12891. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12892. * `context`.
  12893. */
  12894. /**
  12895. * @ngdoc method
  12896. * @name $sce#parseAsCss
  12897. *
  12898. * @description
  12899. * Shorthand method. `$sce.parseAsCss(value)` →
  12900. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12901. *
  12902. * @param {string} expression String expression to compile.
  12903. * @returns {function(context, locals)} a function which represents the compiled expression:
  12904. *
  12905. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12906. * are evaluated against (typically a scope object).
  12907. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12908. * `context`.
  12909. */
  12910. /**
  12911. * @ngdoc method
  12912. * @name $sce#parseAsUrl
  12913. *
  12914. * @description
  12915. * Shorthand method. `$sce.parseAsUrl(value)` →
  12916. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12917. *
  12918. * @param {string} expression String expression to compile.
  12919. * @returns {function(context, locals)} a function which represents the compiled expression:
  12920. *
  12921. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12922. * are evaluated against (typically a scope object).
  12923. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12924. * `context`.
  12925. */
  12926. /**
  12927. * @ngdoc method
  12928. * @name $sce#parseAsResourceUrl
  12929. *
  12930. * @description
  12931. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12932. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12933. *
  12934. * @param {string} expression String expression to compile.
  12935. * @returns {function(context, locals)} a function which represents the compiled expression:
  12936. *
  12937. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12938. * are evaluated against (typically a scope object).
  12939. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12940. * `context`.
  12941. */
  12942. /**
  12943. * @ngdoc method
  12944. * @name $sce#parseAsJs
  12945. *
  12946. * @description
  12947. * Shorthand method. `$sce.parseAsJs(value)` →
  12948. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12949. *
  12950. * @param {string} expression String expression to compile.
  12951. * @returns {function(context, locals)} a function which represents the compiled expression:
  12952. *
  12953. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12954. * are evaluated against (typically a scope object).
  12955. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12956. * `context`.
  12957. */
  12958. // Shorthand delegations.
  12959. var parse = sce.parseAs,
  12960. getTrusted = sce.getTrusted,
  12961. trustAs = sce.trustAs;
  12962. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12963. var lName = lowercase(name);
  12964. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12965. return parse(enumValue, expr);
  12966. };
  12967. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12968. return getTrusted(enumValue, value);
  12969. };
  12970. sce[camelCase("trust_as_" + lName)] = function (value) {
  12971. return trustAs(enumValue, value);
  12972. };
  12973. });
  12974. return sce;
  12975. }];
  12976. }
  12977. /**
  12978. * !!! This is an undocumented "private" service !!!
  12979. *
  12980. * @name $sniffer
  12981. * @requires $window
  12982. * @requires $document
  12983. *
  12984. * @property {boolean} history Does the browser support html5 history api ?
  12985. * @property {boolean} hashchange Does the browser support hashchange event ?
  12986. * @property {boolean} transitions Does the browser support CSS transition events ?
  12987. * @property {boolean} animations Does the browser support CSS animation events ?
  12988. *
  12989. * @description
  12990. * This is very simple implementation of testing browser's features.
  12991. */
  12992. function $SnifferProvider() {
  12993. this.$get = ['$window', '$document', function($window, $document) {
  12994. var eventSupport = {},
  12995. android =
  12996. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12997. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12998. document = $document[0] || {},
  12999. documentMode = document.documentMode,
  13000. vendorPrefix,
  13001. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  13002. bodyStyle = document.body && document.body.style,
  13003. transitions = false,
  13004. animations = false,
  13005. match;
  13006. if (bodyStyle) {
  13007. for(var prop in bodyStyle) {
  13008. if(match = vendorRegex.exec(prop)) {
  13009. vendorPrefix = match[0];
  13010. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  13011. break;
  13012. }
  13013. }
  13014. if(!vendorPrefix) {
  13015. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  13016. }
  13017. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  13018. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  13019. if (android && (!transitions||!animations)) {
  13020. transitions = isString(document.body.style.webkitTransition);
  13021. animations = isString(document.body.style.webkitAnimation);
  13022. }
  13023. }
  13024. return {
  13025. // Android has history.pushState, but it does not update location correctly
  13026. // so let's not use the history API at all.
  13027. // http://code.google.com/p/android/issues/detail?id=17471
  13028. // https://github.com/angular/angular.js/issues/904
  13029. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  13030. // so let's not use the history API also
  13031. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  13032. // jshint -W018
  13033. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  13034. // jshint +W018
  13035. hashchange: 'onhashchange' in $window &&
  13036. // IE8 compatible mode lies
  13037. (!documentMode || documentMode > 7),
  13038. hasEvent: function(event) {
  13039. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  13040. // it. In particular the event is not fired when backspace or delete key are pressed or
  13041. // when cut operation is performed.
  13042. if (event == 'input' && msie == 9) return false;
  13043. if (isUndefined(eventSupport[event])) {
  13044. var divElm = document.createElement('div');
  13045. eventSupport[event] = 'on' + event in divElm;
  13046. }
  13047. return eventSupport[event];
  13048. },
  13049. csp: csp(),
  13050. vendorPrefix: vendorPrefix,
  13051. transitions : transitions,
  13052. animations : animations,
  13053. android: android,
  13054. msie : msie,
  13055. msieDocumentMode: documentMode
  13056. };
  13057. }];
  13058. }
  13059. function $TimeoutProvider() {
  13060. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  13061. function($rootScope, $browser, $q, $exceptionHandler) {
  13062. var deferreds = {};
  13063. /**
  13064. * @ngdoc service
  13065. * @name $timeout
  13066. *
  13067. * @description
  13068. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  13069. * block and delegates any exceptions to
  13070. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13071. *
  13072. * The return value of registering a timeout function is a promise, which will be resolved when
  13073. * the timeout is reached and the timeout function is executed.
  13074. *
  13075. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  13076. *
  13077. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  13078. * synchronously flush the queue of deferred functions.
  13079. *
  13080. * @param {function()} fn A function, whose execution should be delayed.
  13081. * @param {number=} [delay=0] Delay in milliseconds.
  13082. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  13083. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  13084. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  13085. * promise will be resolved with is the return value of the `fn` function.
  13086. *
  13087. */
  13088. function timeout(fn, delay, invokeApply) {
  13089. var deferred = $q.defer(),
  13090. promise = deferred.promise,
  13091. skipApply = (isDefined(invokeApply) && !invokeApply),
  13092. timeoutId;
  13093. timeoutId = $browser.defer(function() {
  13094. try {
  13095. deferred.resolve(fn());
  13096. } catch(e) {
  13097. deferred.reject(e);
  13098. $exceptionHandler(e);
  13099. }
  13100. finally {
  13101. delete deferreds[promise.$$timeoutId];
  13102. }
  13103. if (!skipApply) $rootScope.$apply();
  13104. }, delay);
  13105. promise.$$timeoutId = timeoutId;
  13106. deferreds[timeoutId] = deferred;
  13107. return promise;
  13108. }
  13109. /**
  13110. * @ngdoc method
  13111. * @name $timeout#cancel
  13112. *
  13113. * @description
  13114. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  13115. * resolved with a rejection.
  13116. *
  13117. * @param {Promise=} promise Promise returned by the `$timeout` function.
  13118. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  13119. * canceled.
  13120. */
  13121. timeout.cancel = function(promise) {
  13122. if (promise && promise.$$timeoutId in deferreds) {
  13123. deferreds[promise.$$timeoutId].reject('canceled');
  13124. delete deferreds[promise.$$timeoutId];
  13125. return $browser.defer.cancel(promise.$$timeoutId);
  13126. }
  13127. return false;
  13128. };
  13129. return timeout;
  13130. }];
  13131. }
  13132. // NOTE: The usage of window and document instead of $window and $document here is
  13133. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  13134. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  13135. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  13136. // doesn't know about mocked locations and resolves URLs to the real document - which is
  13137. // exactly the behavior needed here. There is little value is mocking these out for this
  13138. // service.
  13139. var urlParsingNode = document.createElement("a");
  13140. var originUrl = urlResolve(window.location.href, true);
  13141. /**
  13142. *
  13143. * Implementation Notes for non-IE browsers
  13144. * ----------------------------------------
  13145. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  13146. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  13147. * URL will be resolved into an absolute URL in the context of the application document.
  13148. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  13149. * properties are all populated to reflect the normalized URL. This approach has wide
  13150. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  13151. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13152. *
  13153. * Implementation Notes for IE
  13154. * ---------------------------
  13155. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  13156. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  13157. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  13158. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  13159. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  13160. * properties such as protocol, hostname, port, etc.
  13161. *
  13162. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  13163. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  13164. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  13165. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  13166. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  13167. * method and IE < 8 is unsupported.
  13168. *
  13169. * References:
  13170. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  13171. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13172. * http://url.spec.whatwg.org/#urlutils
  13173. * https://github.com/angular/angular.js/pull/2902
  13174. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  13175. *
  13176. * @kind function
  13177. * @param {string} url The URL to be parsed.
  13178. * @description Normalizes and parses a URL.
  13179. * @returns {object} Returns the normalized URL as a dictionary.
  13180. *
  13181. * | member name | Description |
  13182. * |---------------|----------------|
  13183. * | href | A normalized version of the provided URL if it was not an absolute URL |
  13184. * | protocol | The protocol including the trailing colon |
  13185. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  13186. * | search | The search params, minus the question mark |
  13187. * | hash | The hash string, minus the hash symbol
  13188. * | hostname | The hostname
  13189. * | port | The port, without ":"
  13190. * | pathname | The pathname, beginning with "/"
  13191. *
  13192. */
  13193. function urlResolve(url, base) {
  13194. var href = url;
  13195. if (msie) {
  13196. // Normalize before parse. Refer Implementation Notes on why this is
  13197. // done in two steps on IE.
  13198. urlParsingNode.setAttribute("href", href);
  13199. href = urlParsingNode.href;
  13200. }
  13201. urlParsingNode.setAttribute('href', href);
  13202. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  13203. return {
  13204. href: urlParsingNode.href,
  13205. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  13206. host: urlParsingNode.host,
  13207. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  13208. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  13209. hostname: urlParsingNode.hostname,
  13210. port: urlParsingNode.port,
  13211. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  13212. ? urlParsingNode.pathname
  13213. : '/' + urlParsingNode.pathname
  13214. };
  13215. }
  13216. /**
  13217. * Parse a request URL and determine whether this is a same-origin request as the application document.
  13218. *
  13219. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  13220. * or a parsed URL object.
  13221. * @returns {boolean} Whether the request is for the same origin as the application document.
  13222. */
  13223. function urlIsSameOrigin(requestUrl) {
  13224. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  13225. return (parsed.protocol === originUrl.protocol &&
  13226. parsed.host === originUrl.host);
  13227. }
  13228. /**
  13229. * @ngdoc service
  13230. * @name $window
  13231. *
  13232. * @description
  13233. * A reference to the browser's `window` object. While `window`
  13234. * is globally available in JavaScript, it causes testability problems, because
  13235. * it is a global variable. In angular we always refer to it through the
  13236. * `$window` service, so it may be overridden, removed or mocked for testing.
  13237. *
  13238. * Expressions, like the one defined for the `ngClick` directive in the example
  13239. * below, are evaluated with respect to the current scope. Therefore, there is
  13240. * no risk of inadvertently coding in a dependency on a global value in such an
  13241. * expression.
  13242. *
  13243. * @example
  13244. <example module="windowExample">
  13245. <file name="index.html">
  13246. <script>
  13247. angular.module('windowExample', [])
  13248. .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
  13249. $scope.greeting = 'Hello, World!';
  13250. $scope.doGreeting = function(greeting) {
  13251. $window.alert(greeting);
  13252. };
  13253. }]);
  13254. </script>
  13255. <div ng-controller="ExampleController">
  13256. <input type="text" ng-model="greeting" />
  13257. <button ng-click="doGreeting(greeting)">ALERT</button>
  13258. </div>
  13259. </file>
  13260. <file name="protractor.js" type="protractor">
  13261. it('should display the greeting in the input box', function() {
  13262. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  13263. // If we click the button it will block the test runner
  13264. // element(':button').click();
  13265. });
  13266. </file>
  13267. </example>
  13268. */
  13269. function $WindowProvider(){
  13270. this.$get = valueFn(window);
  13271. }
  13272. /* global currencyFilter: true,
  13273. dateFilter: true,
  13274. filterFilter: true,
  13275. jsonFilter: true,
  13276. limitToFilter: true,
  13277. lowercaseFilter: true,
  13278. numberFilter: true,
  13279. orderByFilter: true,
  13280. uppercaseFilter: true,
  13281. */
  13282. /**
  13283. * @ngdoc provider
  13284. * @name $filterProvider
  13285. * @description
  13286. *
  13287. * Filters are just functions which transform input to an output. However filters need to be
  13288. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  13289. * annotated with dependencies and is responsible for creating a filter function.
  13290. *
  13291. * ```js
  13292. * // Filter registration
  13293. * function MyModule($provide, $filterProvider) {
  13294. * // create a service to demonstrate injection (not always needed)
  13295. * $provide.value('greet', function(name){
  13296. * return 'Hello ' + name + '!';
  13297. * });
  13298. *
  13299. * // register a filter factory which uses the
  13300. * // greet service to demonstrate DI.
  13301. * $filterProvider.register('greet', function(greet){
  13302. * // return the filter function which uses the greet service
  13303. * // to generate salutation
  13304. * return function(text) {
  13305. * // filters need to be forgiving so check input validity
  13306. * return text && greet(text) || text;
  13307. * };
  13308. * });
  13309. * }
  13310. * ```
  13311. *
  13312. * The filter function is registered with the `$injector` under the filter name suffix with
  13313. * `Filter`.
  13314. *
  13315. * ```js
  13316. * it('should be the same instance', inject(
  13317. * function($filterProvider) {
  13318. * $filterProvider.register('reverse', function(){
  13319. * return ...;
  13320. * });
  13321. * },
  13322. * function($filter, reverseFilter) {
  13323. * expect($filter('reverse')).toBe(reverseFilter);
  13324. * });
  13325. * ```
  13326. *
  13327. *
  13328. * For more information about how angular filters work, and how to create your own filters, see
  13329. * {@link guide/filter Filters} in the Angular Developer Guide.
  13330. */
  13331. /**
  13332. * @ngdoc service
  13333. * @name $filter
  13334. * @kind function
  13335. * @description
  13336. * Filters are used for formatting data displayed to the user.
  13337. *
  13338. * The general syntax in templates is as follows:
  13339. *
  13340. * {{ expression [| filter_name[:parameter_value] ... ] }}
  13341. *
  13342. * @param {String} name Name of the filter function to retrieve
  13343. * @return {Function} the filter function
  13344. * @example
  13345. <example name="$filter" module="filterExample">
  13346. <file name="index.html">
  13347. <div ng-controller="MainCtrl">
  13348. <h3>{{ originalText }}</h3>
  13349. <h3>{{ filteredText }}</h3>
  13350. </div>
  13351. </file>
  13352. <file name="script.js">
  13353. angular.module('filterExample', [])
  13354. .controller('MainCtrl', function($scope, $filter) {
  13355. $scope.originalText = 'hello';
  13356. $scope.filteredText = $filter('uppercase')($scope.originalText);
  13357. });
  13358. </file>
  13359. </example>
  13360. */
  13361. $FilterProvider.$inject = ['$provide'];
  13362. function $FilterProvider($provide) {
  13363. var suffix = 'Filter';
  13364. /**
  13365. * @ngdoc method
  13366. * @name $filterProvider#register
  13367. * @param {string|Object} name Name of the filter function, or an object map of filters where
  13368. * the keys are the filter names and the values are the filter factories.
  13369. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  13370. * of the registered filter instances.
  13371. */
  13372. function register(name, factory) {
  13373. if(isObject(name)) {
  13374. var filters = {};
  13375. forEach(name, function(filter, key) {
  13376. filters[key] = register(key, filter);
  13377. });
  13378. return filters;
  13379. } else {
  13380. return $provide.factory(name + suffix, factory);
  13381. }
  13382. }
  13383. this.register = register;
  13384. this.$get = ['$injector', function($injector) {
  13385. return function(name) {
  13386. return $injector.get(name + suffix);
  13387. };
  13388. }];
  13389. ////////////////////////////////////////
  13390. /* global
  13391. currencyFilter: false,
  13392. dateFilter: false,
  13393. filterFilter: false,
  13394. jsonFilter: false,
  13395. limitToFilter: false,
  13396. lowercaseFilter: false,
  13397. numberFilter: false,
  13398. orderByFilter: false,
  13399. uppercaseFilter: false,
  13400. */
  13401. register('currency', currencyFilter);
  13402. register('date', dateFilter);
  13403. register('filter', filterFilter);
  13404. register('json', jsonFilter);
  13405. register('limitTo', limitToFilter);
  13406. register('lowercase', lowercaseFilter);
  13407. register('number', numberFilter);
  13408. register('orderBy', orderByFilter);
  13409. register('uppercase', uppercaseFilter);
  13410. }
  13411. /**
  13412. * @ngdoc filter
  13413. * @name filter
  13414. * @kind function
  13415. *
  13416. * @description
  13417. * Selects a subset of items from `array` and returns it as a new array.
  13418. *
  13419. * @param {Array} array The source array.
  13420. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  13421. * `array`.
  13422. *
  13423. * Can be one of:
  13424. *
  13425. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  13426. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  13427. * will be returned. The predicate can be negated by prefixing the string with `!`.
  13428. *
  13429. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  13430. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  13431. * which have property `name` containing "M" and property `phone` containing "1". A special
  13432. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  13433. * property of the object. That's equivalent to the simple substring match with a `string`
  13434. * as described above. The predicate can be negated by prefixing the string with `!`.
  13435. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  13436. * not containing "M".
  13437. *
  13438. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  13439. * called for each element of `array`. The final result is an array of those elements that
  13440. * the predicate returned true for.
  13441. *
  13442. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  13443. * determining if the expected value (from the filter expression) and actual value (from
  13444. * the object in the array) should be considered a match.
  13445. *
  13446. * Can be one of:
  13447. *
  13448. * - `function(actual, expected)`:
  13449. * The function will be given the object value and the predicate value to compare and
  13450. * should return true if the item should be included in filtered result.
  13451. *
  13452. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13453. * this is essentially strict comparison of expected and actual.
  13454. *
  13455. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13456. * insensitive way.
  13457. *
  13458. * @example
  13459. <example>
  13460. <file name="index.html">
  13461. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13462. {name:'Mary', phone:'800-BIG-MARY'},
  13463. {name:'Mike', phone:'555-4321'},
  13464. {name:'Adam', phone:'555-5678'},
  13465. {name:'Julie', phone:'555-8765'},
  13466. {name:'Juliette', phone:'555-5678'}]"></div>
  13467. Search: <input ng-model="searchText">
  13468. <table id="searchTextResults">
  13469. <tr><th>Name</th><th>Phone</th></tr>
  13470. <tr ng-repeat="friend in friends | filter:searchText">
  13471. <td>{{friend.name}}</td>
  13472. <td>{{friend.phone}}</td>
  13473. </tr>
  13474. </table>
  13475. <hr>
  13476. Any: <input ng-model="search.$"> <br>
  13477. Name only <input ng-model="search.name"><br>
  13478. Phone only <input ng-model="search.phone"><br>
  13479. Equality <input type="checkbox" ng-model="strict"><br>
  13480. <table id="searchObjResults">
  13481. <tr><th>Name</th><th>Phone</th></tr>
  13482. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13483. <td>{{friendObj.name}}</td>
  13484. <td>{{friendObj.phone}}</td>
  13485. </tr>
  13486. </table>
  13487. </file>
  13488. <file name="protractor.js" type="protractor">
  13489. var expectFriendNames = function(expectedNames, key) {
  13490. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13491. arr.forEach(function(wd, i) {
  13492. expect(wd.getText()).toMatch(expectedNames[i]);
  13493. });
  13494. });
  13495. };
  13496. it('should search across all fields when filtering with a string', function() {
  13497. var searchText = element(by.model('searchText'));
  13498. searchText.clear();
  13499. searchText.sendKeys('m');
  13500. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13501. searchText.clear();
  13502. searchText.sendKeys('76');
  13503. expectFriendNames(['John', 'Julie'], 'friend');
  13504. });
  13505. it('should search in specific fields when filtering with a predicate object', function() {
  13506. var searchAny = element(by.model('search.$'));
  13507. searchAny.clear();
  13508. searchAny.sendKeys('i');
  13509. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13510. });
  13511. it('should use a equal comparison when comparator is true', function() {
  13512. var searchName = element(by.model('search.name'));
  13513. var strict = element(by.model('strict'));
  13514. searchName.clear();
  13515. searchName.sendKeys('Julie');
  13516. strict.click();
  13517. expectFriendNames(['Julie'], 'friendObj');
  13518. });
  13519. </file>
  13520. </example>
  13521. */
  13522. function filterFilter() {
  13523. return function(array, expression, comparator) {
  13524. if (!isArray(array)) return array;
  13525. var comparatorType = typeof(comparator),
  13526. predicates = [];
  13527. predicates.check = function(value) {
  13528. for (var j = 0; j < predicates.length; j++) {
  13529. if(!predicates[j](value)) {
  13530. return false;
  13531. }
  13532. }
  13533. return true;
  13534. };
  13535. if (comparatorType !== 'function') {
  13536. if (comparatorType === 'boolean' && comparator) {
  13537. comparator = function(obj, text) {
  13538. return angular.equals(obj, text);
  13539. };
  13540. } else {
  13541. comparator = function(obj, text) {
  13542. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13543. for (var objKey in obj) {
  13544. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13545. comparator(obj[objKey], text[objKey])) {
  13546. return true;
  13547. }
  13548. }
  13549. return false;
  13550. }
  13551. text = (''+text).toLowerCase();
  13552. return (''+obj).toLowerCase().indexOf(text) > -1;
  13553. };
  13554. }
  13555. }
  13556. var search = function(obj, text){
  13557. if (typeof text === 'string' && text.charAt(0) === '!') {
  13558. return !search(obj, text.substr(1));
  13559. }
  13560. switch (typeof obj) {
  13561. case 'boolean':
  13562. case 'number':
  13563. case 'string':
  13564. return comparator(obj, text);
  13565. case 'object':
  13566. switch (typeof text) {
  13567. case 'object':
  13568. return comparator(obj, text);
  13569. default:
  13570. for ( var objKey in obj) {
  13571. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13572. return true;
  13573. }
  13574. }
  13575. break;
  13576. }
  13577. return false;
  13578. case 'array':
  13579. for ( var i = 0; i < obj.length; i++) {
  13580. if (search(obj[i], text)) {
  13581. return true;
  13582. }
  13583. }
  13584. return false;
  13585. default:
  13586. return false;
  13587. }
  13588. };
  13589. switch (typeof expression) {
  13590. case 'boolean':
  13591. case 'number':
  13592. case 'string':
  13593. // Set up expression object and fall through
  13594. expression = {$:expression};
  13595. // jshint -W086
  13596. case 'object':
  13597. // jshint +W086
  13598. for (var key in expression) {
  13599. (function(path) {
  13600. if (typeof expression[path] === 'undefined') return;
  13601. predicates.push(function(value) {
  13602. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13603. });
  13604. })(key);
  13605. }
  13606. break;
  13607. case 'function':
  13608. predicates.push(expression);
  13609. break;
  13610. default:
  13611. return array;
  13612. }
  13613. var filtered = [];
  13614. for ( var j = 0; j < array.length; j++) {
  13615. var value = array[j];
  13616. if (predicates.check(value)) {
  13617. filtered.push(value);
  13618. }
  13619. }
  13620. return filtered;
  13621. };
  13622. }
  13623. /**
  13624. * @ngdoc filter
  13625. * @name currency
  13626. * @kind function
  13627. *
  13628. * @description
  13629. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13630. * symbol for current locale is used.
  13631. *
  13632. * @param {number} amount Input to filter.
  13633. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13634. * @returns {string} Formatted number.
  13635. *
  13636. *
  13637. * @example
  13638. <example module="currencyExample">
  13639. <file name="index.html">
  13640. <script>
  13641. angular.module('currencyExample', [])
  13642. .controller('ExampleController', ['$scope', function($scope) {
  13643. $scope.amount = 1234.56;
  13644. }]);
  13645. </script>
  13646. <div ng-controller="ExampleController">
  13647. <input type="number" ng-model="amount"> <br>
  13648. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13649. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13650. </div>
  13651. </file>
  13652. <file name="protractor.js" type="protractor">
  13653. it('should init with 1234.56', function() {
  13654. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13655. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13656. });
  13657. it('should update', function() {
  13658. if (browser.params.browser == 'safari') {
  13659. // Safari does not understand the minus key. See
  13660. // https://github.com/angular/protractor/issues/481
  13661. return;
  13662. }
  13663. element(by.model('amount')).clear();
  13664. element(by.model('amount')).sendKeys('-1234');
  13665. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13666. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13667. });
  13668. </file>
  13669. </example>
  13670. */
  13671. currencyFilter.$inject = ['$locale'];
  13672. function currencyFilter($locale) {
  13673. var formats = $locale.NUMBER_FORMATS;
  13674. return function(amount, currencySymbol){
  13675. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13676. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13677. replace(/\u00A4/g, currencySymbol);
  13678. };
  13679. }
  13680. /**
  13681. * @ngdoc filter
  13682. * @name number
  13683. * @kind function
  13684. *
  13685. * @description
  13686. * Formats a number as text.
  13687. *
  13688. * If the input is not a number an empty string is returned.
  13689. *
  13690. * @param {number|string} number Number to format.
  13691. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13692. * If this is not provided then the fraction size is computed from the current locale's number
  13693. * formatting pattern. In the case of the default locale, it will be 3.
  13694. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13695. *
  13696. * @example
  13697. <example module="numberFilterExample">
  13698. <file name="index.html">
  13699. <script>
  13700. angular.module('numberFilterExample', [])
  13701. .controller('ExampleController', ['$scope', function($scope) {
  13702. $scope.val = 1234.56789;
  13703. }]);
  13704. </script>
  13705. <div ng-controller="ExampleController">
  13706. Enter number: <input ng-model='val'><br>
  13707. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13708. No fractions: <span>{{val | number:0}}</span><br>
  13709. Negative number: <span>{{-val | number:4}}</span>
  13710. </div>
  13711. </file>
  13712. <file name="protractor.js" type="protractor">
  13713. it('should format numbers', function() {
  13714. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13715. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13716. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13717. });
  13718. it('should update', function() {
  13719. element(by.model('val')).clear();
  13720. element(by.model('val')).sendKeys('3374.333');
  13721. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13722. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13723. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13724. });
  13725. </file>
  13726. </example>
  13727. */
  13728. numberFilter.$inject = ['$locale'];
  13729. function numberFilter($locale) {
  13730. var formats = $locale.NUMBER_FORMATS;
  13731. return function(number, fractionSize) {
  13732. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13733. fractionSize);
  13734. };
  13735. }
  13736. var DECIMAL_SEP = '.';
  13737. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13738. if (number == null || !isFinite(number) || isObject(number)) return '';
  13739. var isNegative = number < 0;
  13740. number = Math.abs(number);
  13741. var numStr = number + '',
  13742. formatedText = '',
  13743. parts = [];
  13744. var hasExponent = false;
  13745. if (numStr.indexOf('e') !== -1) {
  13746. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13747. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13748. numStr = '0';
  13749. number = 0;
  13750. } else {
  13751. formatedText = numStr;
  13752. hasExponent = true;
  13753. }
  13754. }
  13755. if (!hasExponent) {
  13756. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13757. // determine fractionSize if it is not specified
  13758. if (isUndefined(fractionSize)) {
  13759. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13760. }
  13761. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  13762. // inspired by:
  13763. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  13764. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  13765. if (number === 0) {
  13766. isNegative = false;
  13767. }
  13768. var fraction = ('' + number).split(DECIMAL_SEP);
  13769. var whole = fraction[0];
  13770. fraction = fraction[1] || '';
  13771. var i, pos = 0,
  13772. lgroup = pattern.lgSize,
  13773. group = pattern.gSize;
  13774. if (whole.length >= (lgroup + group)) {
  13775. pos = whole.length - lgroup;
  13776. for (i = 0; i < pos; i++) {
  13777. if ((pos - i)%group === 0 && i !== 0) {
  13778. formatedText += groupSep;
  13779. }
  13780. formatedText += whole.charAt(i);
  13781. }
  13782. }
  13783. for (i = pos; i < whole.length; i++) {
  13784. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13785. formatedText += groupSep;
  13786. }
  13787. formatedText += whole.charAt(i);
  13788. }
  13789. // format fraction part.
  13790. while(fraction.length < fractionSize) {
  13791. fraction += '0';
  13792. }
  13793. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13794. } else {
  13795. if (fractionSize > 0 && number > -1 && number < 1) {
  13796. formatedText = number.toFixed(fractionSize);
  13797. }
  13798. }
  13799. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13800. parts.push(formatedText);
  13801. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13802. return parts.join('');
  13803. }
  13804. function padNumber(num, digits, trim) {
  13805. var neg = '';
  13806. if (num < 0) {
  13807. neg = '-';
  13808. num = -num;
  13809. }
  13810. num = '' + num;
  13811. while(num.length < digits) num = '0' + num;
  13812. if (trim)
  13813. num = num.substr(num.length - digits);
  13814. return neg + num;
  13815. }
  13816. function dateGetter(name, size, offset, trim) {
  13817. offset = offset || 0;
  13818. return function(date) {
  13819. var value = date['get' + name]();
  13820. if (offset > 0 || value > -offset)
  13821. value += offset;
  13822. if (value === 0 && offset == -12 ) value = 12;
  13823. return padNumber(value, size, trim);
  13824. };
  13825. }
  13826. function dateStrGetter(name, shortForm) {
  13827. return function(date, formats) {
  13828. var value = date['get' + name]();
  13829. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13830. return formats[get][value];
  13831. };
  13832. }
  13833. function timeZoneGetter(date) {
  13834. var zone = -1 * date.getTimezoneOffset();
  13835. var paddedZone = (zone >= 0) ? "+" : "";
  13836. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13837. padNumber(Math.abs(zone % 60), 2);
  13838. return paddedZone;
  13839. }
  13840. function ampmGetter(date, formats) {
  13841. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13842. }
  13843. var DATE_FORMATS = {
  13844. yyyy: dateGetter('FullYear', 4),
  13845. yy: dateGetter('FullYear', 2, 0, true),
  13846. y: dateGetter('FullYear', 1),
  13847. MMMM: dateStrGetter('Month'),
  13848. MMM: dateStrGetter('Month', true),
  13849. MM: dateGetter('Month', 2, 1),
  13850. M: dateGetter('Month', 1, 1),
  13851. dd: dateGetter('Date', 2),
  13852. d: dateGetter('Date', 1),
  13853. HH: dateGetter('Hours', 2),
  13854. H: dateGetter('Hours', 1),
  13855. hh: dateGetter('Hours', 2, -12),
  13856. h: dateGetter('Hours', 1, -12),
  13857. mm: dateGetter('Minutes', 2),
  13858. m: dateGetter('Minutes', 1),
  13859. ss: dateGetter('Seconds', 2),
  13860. s: dateGetter('Seconds', 1),
  13861. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13862. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13863. sss: dateGetter('Milliseconds', 3),
  13864. EEEE: dateStrGetter('Day'),
  13865. EEE: dateStrGetter('Day', true),
  13866. a: ampmGetter,
  13867. Z: timeZoneGetter
  13868. };
  13869. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13870. NUMBER_STRING = /^\-?\d+$/;
  13871. /**
  13872. * @ngdoc filter
  13873. * @name date
  13874. * @kind function
  13875. *
  13876. * @description
  13877. * Formats `date` to a string based on the requested `format`.
  13878. *
  13879. * `format` string can be composed of the following elements:
  13880. *
  13881. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13882. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13883. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13884. * * `'MMMM'`: Month in year (January-December)
  13885. * * `'MMM'`: Month in year (Jan-Dec)
  13886. * * `'MM'`: Month in year, padded (01-12)
  13887. * * `'M'`: Month in year (1-12)
  13888. * * `'dd'`: Day in month, padded (01-31)
  13889. * * `'d'`: Day in month (1-31)
  13890. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13891. * * `'EEE'`: Day in Week, (Sun-Sat)
  13892. * * `'HH'`: Hour in day, padded (00-23)
  13893. * * `'H'`: Hour in day (0-23)
  13894. * * `'hh'`: Hour in am/pm, padded (01-12)
  13895. * * `'h'`: Hour in am/pm, (1-12)
  13896. * * `'mm'`: Minute in hour, padded (00-59)
  13897. * * `'m'`: Minute in hour (0-59)
  13898. * * `'ss'`: Second in minute, padded (00-59)
  13899. * * `'s'`: Second in minute (0-59)
  13900. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13901. * * `'a'`: am/pm marker
  13902. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13903. *
  13904. * `format` string can also be one of the following predefined
  13905. * {@link guide/i18n localizable formats}:
  13906. *
  13907. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13908. * (e.g. Sep 3, 2010 12:05:08 pm)
  13909. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13910. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13911. * (e.g. Friday, September 3, 2010)
  13912. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13913. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13914. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13915. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13916. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13917. *
  13918. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  13919. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  13920. * (e.g. `"h 'o''clock'"`).
  13921. *
  13922. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13923. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  13924. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13925. * specified in the string input, the time is considered to be in the local timezone.
  13926. * @param {string=} format Formatting rules (see Description). If not specified,
  13927. * `mediumDate` is used.
  13928. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13929. *
  13930. * @example
  13931. <example>
  13932. <file name="index.html">
  13933. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13934. <span>{{1288323623006 | date:'medium'}}</span><br>
  13935. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13936. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13937. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13938. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13939. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  13940. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  13941. </file>
  13942. <file name="protractor.js" type="protractor">
  13943. it('should format date', function() {
  13944. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13945. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13946. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13947. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13948. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13949. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13950. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  13951. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  13952. });
  13953. </file>
  13954. </example>
  13955. */
  13956. dateFilter.$inject = ['$locale'];
  13957. function dateFilter($locale) {
  13958. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13959. // 1 2 3 4 5 6 7 8 9 10 11
  13960. function jsonStringToDate(string) {
  13961. var match;
  13962. if (match = string.match(R_ISO8601_STR)) {
  13963. var date = new Date(0),
  13964. tzHour = 0,
  13965. tzMin = 0,
  13966. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13967. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13968. if (match[9]) {
  13969. tzHour = int(match[9] + match[10]);
  13970. tzMin = int(match[9] + match[11]);
  13971. }
  13972. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13973. var h = int(match[4]||0) - tzHour;
  13974. var m = int(match[5]||0) - tzMin;
  13975. var s = int(match[6]||0);
  13976. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13977. timeSetter.call(date, h, m, s, ms);
  13978. return date;
  13979. }
  13980. return string;
  13981. }
  13982. return function(date, format) {
  13983. var text = '',
  13984. parts = [],
  13985. fn, match;
  13986. format = format || 'mediumDate';
  13987. format = $locale.DATETIME_FORMATS[format] || format;
  13988. if (isString(date)) {
  13989. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  13990. }
  13991. if (isNumber(date)) {
  13992. date = new Date(date);
  13993. }
  13994. if (!isDate(date)) {
  13995. return date;
  13996. }
  13997. while(format) {
  13998. match = DATE_FORMATS_SPLIT.exec(format);
  13999. if (match) {
  14000. parts = concat(parts, match, 1);
  14001. format = parts.pop();
  14002. } else {
  14003. parts.push(format);
  14004. format = null;
  14005. }
  14006. }
  14007. forEach(parts, function(value){
  14008. fn = DATE_FORMATS[value];
  14009. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  14010. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  14011. });
  14012. return text;
  14013. };
  14014. }
  14015. /**
  14016. * @ngdoc filter
  14017. * @name json
  14018. * @kind function
  14019. *
  14020. * @description
  14021. * Allows you to convert a JavaScript object into JSON string.
  14022. *
  14023. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  14024. * the binding is automatically converted to JSON.
  14025. *
  14026. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  14027. * @returns {string} JSON string.
  14028. *
  14029. *
  14030. * @example
  14031. <example>
  14032. <file name="index.html">
  14033. <pre>{{ {'name':'value'} | json }}</pre>
  14034. </file>
  14035. <file name="protractor.js" type="protractor">
  14036. it('should jsonify filtered objects', function() {
  14037. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  14038. });
  14039. </file>
  14040. </example>
  14041. *
  14042. */
  14043. function jsonFilter() {
  14044. return function(object) {
  14045. return toJson(object, true);
  14046. };
  14047. }
  14048. /**
  14049. * @ngdoc filter
  14050. * @name lowercase
  14051. * @kind function
  14052. * @description
  14053. * Converts string to lowercase.
  14054. * @see angular.lowercase
  14055. */
  14056. var lowercaseFilter = valueFn(lowercase);
  14057. /**
  14058. * @ngdoc filter
  14059. * @name uppercase
  14060. * @kind function
  14061. * @description
  14062. * Converts string to uppercase.
  14063. * @see angular.uppercase
  14064. */
  14065. var uppercaseFilter = valueFn(uppercase);
  14066. /**
  14067. * @ngdoc filter
  14068. * @name limitTo
  14069. * @kind function
  14070. *
  14071. * @description
  14072. * Creates a new array or string containing only a specified number of elements. The elements
  14073. * are taken from either the beginning or the end of the source array or string, as specified by
  14074. * the value and sign (positive or negative) of `limit`.
  14075. *
  14076. * @param {Array|string} input Source array or string to be limited.
  14077. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  14078. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  14079. * If the number is negative, `limit` number of items from the end of the source array/string
  14080. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  14081. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  14082. * had less than `limit` elements.
  14083. *
  14084. * @example
  14085. <example module="limitToExample">
  14086. <file name="index.html">
  14087. <script>
  14088. angular.module('limitToExample', [])
  14089. .controller('ExampleController', ['$scope', function($scope) {
  14090. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  14091. $scope.letters = "abcdefghi";
  14092. $scope.numLimit = 3;
  14093. $scope.letterLimit = 3;
  14094. }]);
  14095. </script>
  14096. <div ng-controller="ExampleController">
  14097. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  14098. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  14099. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  14100. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  14101. </div>
  14102. </file>
  14103. <file name="protractor.js" type="protractor">
  14104. var numLimitInput = element(by.model('numLimit'));
  14105. var letterLimitInput = element(by.model('letterLimit'));
  14106. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  14107. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  14108. it('should limit the number array to first three items', function() {
  14109. expect(numLimitInput.getAttribute('value')).toBe('3');
  14110. expect(letterLimitInput.getAttribute('value')).toBe('3');
  14111. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  14112. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  14113. });
  14114. // There is a bug in safari and protractor that doesn't like the minus key
  14115. // it('should update the output when -3 is entered', function() {
  14116. // numLimitInput.clear();
  14117. // numLimitInput.sendKeys('-3');
  14118. // letterLimitInput.clear();
  14119. // letterLimitInput.sendKeys('-3');
  14120. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  14121. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  14122. // });
  14123. it('should not exceed the maximum size of input array', function() {
  14124. numLimitInput.clear();
  14125. numLimitInput.sendKeys('100');
  14126. letterLimitInput.clear();
  14127. letterLimitInput.sendKeys('100');
  14128. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  14129. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  14130. });
  14131. </file>
  14132. </example>
  14133. */
  14134. function limitToFilter(){
  14135. return function(input, limit) {
  14136. if (!isArray(input) && !isString(input)) return input;
  14137. if (Math.abs(Number(limit)) === Infinity) {
  14138. limit = Number(limit);
  14139. } else {
  14140. limit = int(limit);
  14141. }
  14142. //NaN check on limit
  14143. if (limit) {
  14144. return limit > 0 ? input.slice(0, limit) : input.slice(limit);
  14145. } else {
  14146. return isString(input) ? "" : [];
  14147. }
  14148. };
  14149. }
  14150. /**
  14151. * @ngdoc filter
  14152. * @name orderBy
  14153. * @kind function
  14154. *
  14155. * @description
  14156. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  14157. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  14158. * correctly, make sure they are actually being saved as numbers and not strings.
  14159. *
  14160. * @param {Array} array The array to sort.
  14161. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  14162. * used by the comparator to determine the order of elements.
  14163. *
  14164. * Can be one of:
  14165. *
  14166. * - `function`: Getter function. The result of this function will be sorted using the
  14167. * `<`, `=`, `>` operator.
  14168. * - `string`: An Angular expression. The result of this expression is used to compare elements
  14169. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  14170. * 3 first characters of a property called `name`). The result of a constant expression
  14171. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  14172. * to sort object by the value of their `special name` property). An expression can be
  14173. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  14174. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  14175. * element itself is used to compare where sorting.
  14176. * - `Array`: An array of function or string predicates. The first predicate in the array
  14177. * is used for sorting, but when two items are equivalent, the next predicate is used.
  14178. *
  14179. * If the predicate is missing or empty then it defaults to `'+'`.
  14180. *
  14181. * @param {boolean=} reverse Reverse the order of the array.
  14182. * @returns {Array} Sorted copy of the source array.
  14183. *
  14184. * @example
  14185. <example module="orderByExample">
  14186. <file name="index.html">
  14187. <script>
  14188. angular.module('orderByExample', [])
  14189. .controller('ExampleController', ['$scope', function($scope) {
  14190. $scope.friends =
  14191. [{name:'John', phone:'555-1212', age:10},
  14192. {name:'Mary', phone:'555-9876', age:19},
  14193. {name:'Mike', phone:'555-4321', age:21},
  14194. {name:'Adam', phone:'555-5678', age:35},
  14195. {name:'Julie', phone:'555-8765', age:29}];
  14196. $scope.predicate = '-age';
  14197. }]);
  14198. </script>
  14199. <div ng-controller="ExampleController">
  14200. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  14201. <hr/>
  14202. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  14203. <table class="friend">
  14204. <tr>
  14205. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  14206. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  14207. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  14208. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  14209. </tr>
  14210. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  14211. <td>{{friend.name}}</td>
  14212. <td>{{friend.phone}}</td>
  14213. <td>{{friend.age}}</td>
  14214. </tr>
  14215. </table>
  14216. </div>
  14217. </file>
  14218. </example>
  14219. *
  14220. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  14221. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  14222. * desired parameters.
  14223. *
  14224. * Example:
  14225. *
  14226. * @example
  14227. <example module="orderByExample">
  14228. <file name="index.html">
  14229. <div ng-controller="ExampleController">
  14230. <table class="friend">
  14231. <tr>
  14232. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  14233. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  14234. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  14235. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  14236. </tr>
  14237. <tr ng-repeat="friend in friends">
  14238. <td>{{friend.name}}</td>
  14239. <td>{{friend.phone}}</td>
  14240. <td>{{friend.age}}</td>
  14241. </tr>
  14242. </table>
  14243. </div>
  14244. </file>
  14245. <file name="script.js">
  14246. angular.module('orderByExample', [])
  14247. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  14248. var orderBy = $filter('orderBy');
  14249. $scope.friends = [
  14250. { name: 'John', phone: '555-1212', age: 10 },
  14251. { name: 'Mary', phone: '555-9876', age: 19 },
  14252. { name: 'Mike', phone: '555-4321', age: 21 },
  14253. { name: 'Adam', phone: '555-5678', age: 35 },
  14254. { name: 'Julie', phone: '555-8765', age: 29 }
  14255. ];
  14256. $scope.order = function(predicate, reverse) {
  14257. $scope.friends = orderBy($scope.friends, predicate, reverse);
  14258. };
  14259. $scope.order('-age',false);
  14260. }]);
  14261. </file>
  14262. </example>
  14263. */
  14264. orderByFilter.$inject = ['$parse'];
  14265. function orderByFilter($parse){
  14266. return function(array, sortPredicate, reverseOrder) {
  14267. if (!(isArrayLike(array))) return array;
  14268. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  14269. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  14270. sortPredicate = map(sortPredicate, function(predicate){
  14271. var descending = false, get = predicate || identity;
  14272. if (isString(predicate)) {
  14273. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  14274. descending = predicate.charAt(0) == '-';
  14275. predicate = predicate.substring(1);
  14276. }
  14277. if ( predicate === '' ) {
  14278. // Effectively no predicate was passed so we compare identity
  14279. return reverseComparator(function(a,b) {
  14280. return compare(a, b);
  14281. }, descending);
  14282. }
  14283. get = $parse(predicate);
  14284. if (get.constant) {
  14285. var key = get();
  14286. return reverseComparator(function(a,b) {
  14287. return compare(a[key], b[key]);
  14288. }, descending);
  14289. }
  14290. }
  14291. return reverseComparator(function(a,b){
  14292. return compare(get(a),get(b));
  14293. }, descending);
  14294. });
  14295. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  14296. function comparator(o1, o2){
  14297. for ( var i = 0; i < sortPredicate.length; i++) {
  14298. var comp = sortPredicate[i](o1, o2);
  14299. if (comp !== 0) return comp;
  14300. }
  14301. return 0;
  14302. }
  14303. function reverseComparator(comp, descending) {
  14304. return toBoolean(descending)
  14305. ? function(a,b){return comp(b,a);}
  14306. : comp;
  14307. }
  14308. function compare(v1, v2){
  14309. var t1 = typeof v1;
  14310. var t2 = typeof v2;
  14311. if (t1 == t2) {
  14312. if (isDate(v1) && isDate(v2)) {
  14313. v1 = v1.valueOf();
  14314. v2 = v2.valueOf();
  14315. }
  14316. if (t1 == "string") {
  14317. v1 = v1.toLowerCase();
  14318. v2 = v2.toLowerCase();
  14319. }
  14320. if (v1 === v2) return 0;
  14321. return v1 < v2 ? -1 : 1;
  14322. } else {
  14323. return t1 < t2 ? -1 : 1;
  14324. }
  14325. }
  14326. };
  14327. }
  14328. function ngDirective(directive) {
  14329. if (isFunction(directive)) {
  14330. directive = {
  14331. link: directive
  14332. };
  14333. }
  14334. directive.restrict = directive.restrict || 'AC';
  14335. return valueFn(directive);
  14336. }
  14337. /**
  14338. * @ngdoc directive
  14339. * @name a
  14340. * @restrict E
  14341. *
  14342. * @description
  14343. * Modifies the default behavior of the html A tag so that the default action is prevented when
  14344. * the href attribute is empty.
  14345. *
  14346. * This change permits the easy creation of action links with the `ngClick` directive
  14347. * without changing the location or causing page reloads, e.g.:
  14348. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  14349. */
  14350. var htmlAnchorDirective = valueFn({
  14351. restrict: 'E',
  14352. compile: function(element, attr) {
  14353. if (msie <= 8) {
  14354. // turn <a href ng-click="..">link</a> into a stylable link in IE
  14355. // but only if it doesn't have name attribute, in which case it's an anchor
  14356. if (!attr.href && !attr.name) {
  14357. attr.$set('href', '');
  14358. }
  14359. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  14360. // to new attribute content if attribute is updated with value containing @ and element also
  14361. // contains value with @
  14362. // see issue #1949
  14363. element.append(document.createComment('IE fix'));
  14364. }
  14365. if (!attr.href && !attr.xlinkHref && !attr.name) {
  14366. return function(scope, element) {
  14367. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  14368. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  14369. 'xlink:href' : 'href';
  14370. element.on('click', function(event){
  14371. // if we have no href url, then don't navigate anywhere.
  14372. if (!element.attr(href)) {
  14373. event.preventDefault();
  14374. }
  14375. });
  14376. };
  14377. }
  14378. }
  14379. });
  14380. /**
  14381. * @ngdoc directive
  14382. * @name ngHref
  14383. * @restrict A
  14384. * @priority 99
  14385. *
  14386. * @description
  14387. * Using Angular markup like `{{hash}}` in an href attribute will
  14388. * make the link go to the wrong URL if the user clicks it before
  14389. * Angular has a chance to replace the `{{hash}}` markup with its
  14390. * value. Until Angular replaces the markup the link will be broken
  14391. * and will most likely return a 404 error. The `ngHref` directive
  14392. * solves this problem.
  14393. *
  14394. * The wrong way to write it:
  14395. * ```html
  14396. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  14397. * ```
  14398. *
  14399. * The correct way to write it:
  14400. * ```html
  14401. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  14402. * ```
  14403. *
  14404. * @element A
  14405. * @param {template} ngHref any string which can contain `{{}}` markup.
  14406. *
  14407. * @example
  14408. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  14409. * in links and their different behaviors:
  14410. <example>
  14411. <file name="index.html">
  14412. <input ng-model="value" /><br />
  14413. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  14414. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  14415. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  14416. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  14417. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  14418. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  14419. </file>
  14420. <file name="protractor.js" type="protractor">
  14421. it('should execute ng-click but not reload when href without value', function() {
  14422. element(by.id('link-1')).click();
  14423. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  14424. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  14425. });
  14426. it('should execute ng-click but not reload when href empty string', function() {
  14427. element(by.id('link-2')).click();
  14428. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  14429. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  14430. });
  14431. it('should execute ng-click and change url when ng-href specified', function() {
  14432. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  14433. element(by.id('link-3')).click();
  14434. // At this point, we navigate away from an Angular page, so we need
  14435. // to use browser.driver to get the base webdriver.
  14436. browser.wait(function() {
  14437. return browser.driver.getCurrentUrl().then(function(url) {
  14438. return url.match(/\/123$/);
  14439. });
  14440. }, 5000, 'page should navigate to /123');
  14441. });
  14442. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  14443. element(by.id('link-4')).click();
  14444. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  14445. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  14446. });
  14447. it('should execute ng-click but not reload when no href but name specified', function() {
  14448. element(by.id('link-5')).click();
  14449. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  14450. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  14451. });
  14452. it('should only change url when only ng-href', function() {
  14453. element(by.model('value')).clear();
  14454. element(by.model('value')).sendKeys('6');
  14455. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  14456. element(by.id('link-6')).click();
  14457. // At this point, we navigate away from an Angular page, so we need
  14458. // to use browser.driver to get the base webdriver.
  14459. browser.wait(function() {
  14460. return browser.driver.getCurrentUrl().then(function(url) {
  14461. return url.match(/\/6$/);
  14462. });
  14463. }, 5000, 'page should navigate to /6');
  14464. });
  14465. </file>
  14466. </example>
  14467. */
  14468. /**
  14469. * @ngdoc directive
  14470. * @name ngSrc
  14471. * @restrict A
  14472. * @priority 99
  14473. *
  14474. * @description
  14475. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  14476. * work right: The browser will fetch from the URL with the literal
  14477. * text `{{hash}}` until Angular replaces the expression inside
  14478. * `{{hash}}`. The `ngSrc` directive solves this problem.
  14479. *
  14480. * The buggy way to write it:
  14481. * ```html
  14482. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  14483. * ```
  14484. *
  14485. * The correct way to write it:
  14486. * ```html
  14487. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  14488. * ```
  14489. *
  14490. * @element IMG
  14491. * @param {template} ngSrc any string which can contain `{{}}` markup.
  14492. */
  14493. /**
  14494. * @ngdoc directive
  14495. * @name ngSrcset
  14496. * @restrict A
  14497. * @priority 99
  14498. *
  14499. * @description
  14500. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14501. * work right: The browser will fetch from the URL with the literal
  14502. * text `{{hash}}` until Angular replaces the expression inside
  14503. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14504. *
  14505. * The buggy way to write it:
  14506. * ```html
  14507. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14508. * ```
  14509. *
  14510. * The correct way to write it:
  14511. * ```html
  14512. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14513. * ```
  14514. *
  14515. * @element IMG
  14516. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14517. */
  14518. /**
  14519. * @ngdoc directive
  14520. * @name ngDisabled
  14521. * @restrict A
  14522. * @priority 100
  14523. *
  14524. * @description
  14525. *
  14526. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14527. * ```html
  14528. * <div ng-init="scope = { isDisabled: false }">
  14529. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14530. * </div>
  14531. * ```
  14532. *
  14533. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14534. * such as disabled. (Their presence means true and their absence means false.)
  14535. * If we put an Angular interpolation expression into such an attribute then the
  14536. * binding information would be lost when the browser removes the attribute.
  14537. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14538. * This complementary directive is not removed by the browser and so provides
  14539. * a permanent reliable place to store the binding information.
  14540. *
  14541. * @example
  14542. <example>
  14543. <file name="index.html">
  14544. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14545. <button ng-model="button" ng-disabled="checked">Button</button>
  14546. </file>
  14547. <file name="protractor.js" type="protractor">
  14548. it('should toggle button', function() {
  14549. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14550. element(by.model('checked')).click();
  14551. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14552. });
  14553. </file>
  14554. </example>
  14555. *
  14556. * @element INPUT
  14557. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14558. * then special attribute "disabled" will be set on the element
  14559. */
  14560. /**
  14561. * @ngdoc directive
  14562. * @name ngChecked
  14563. * @restrict A
  14564. * @priority 100
  14565. *
  14566. * @description
  14567. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14568. * such as checked. (Their presence means true and their absence means false.)
  14569. * If we put an Angular interpolation expression into such an attribute then the
  14570. * binding information would be lost when the browser removes the attribute.
  14571. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14572. * This complementary directive is not removed by the browser and so provides
  14573. * a permanent reliable place to store the binding information.
  14574. * @example
  14575. <example>
  14576. <file name="index.html">
  14577. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14578. <input id="checkSlave" type="checkbox" ng-checked="master">
  14579. </file>
  14580. <file name="protractor.js" type="protractor">
  14581. it('should check both checkBoxes', function() {
  14582. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14583. element(by.model('master')).click();
  14584. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14585. });
  14586. </file>
  14587. </example>
  14588. *
  14589. * @element INPUT
  14590. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14591. * then special attribute "checked" will be set on the element
  14592. */
  14593. /**
  14594. * @ngdoc directive
  14595. * @name ngReadonly
  14596. * @restrict A
  14597. * @priority 100
  14598. *
  14599. * @description
  14600. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14601. * such as readonly. (Their presence means true and their absence means false.)
  14602. * If we put an Angular interpolation expression into such an attribute then the
  14603. * binding information would be lost when the browser removes the attribute.
  14604. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14605. * This complementary directive is not removed by the browser and so provides
  14606. * a permanent reliable place to store the binding information.
  14607. * @example
  14608. <example>
  14609. <file name="index.html">
  14610. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14611. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14612. </file>
  14613. <file name="protractor.js" type="protractor">
  14614. it('should toggle readonly attr', function() {
  14615. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14616. element(by.model('checked')).click();
  14617. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14618. });
  14619. </file>
  14620. </example>
  14621. *
  14622. * @element INPUT
  14623. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14624. * then special attribute "readonly" will be set on the element
  14625. */
  14626. /**
  14627. * @ngdoc directive
  14628. * @name ngSelected
  14629. * @restrict A
  14630. * @priority 100
  14631. *
  14632. * @description
  14633. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14634. * such as selected. (Their presence means true and their absence means false.)
  14635. * If we put an Angular interpolation expression into such an attribute then the
  14636. * binding information would be lost when the browser removes the attribute.
  14637. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14638. * This complementary directive is not removed by the browser and so provides
  14639. * a permanent reliable place to store the binding information.
  14640. *
  14641. * @example
  14642. <example>
  14643. <file name="index.html">
  14644. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14645. <select>
  14646. <option>Hello!</option>
  14647. <option id="greet" ng-selected="selected">Greetings!</option>
  14648. </select>
  14649. </file>
  14650. <file name="protractor.js" type="protractor">
  14651. it('should select Greetings!', function() {
  14652. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14653. element(by.model('selected')).click();
  14654. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14655. });
  14656. </file>
  14657. </example>
  14658. *
  14659. * @element OPTION
  14660. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14661. * then special attribute "selected" will be set on the element
  14662. */
  14663. /**
  14664. * @ngdoc directive
  14665. * @name ngOpen
  14666. * @restrict A
  14667. * @priority 100
  14668. *
  14669. * @description
  14670. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14671. * such as open. (Their presence means true and their absence means false.)
  14672. * If we put an Angular interpolation expression into such an attribute then the
  14673. * binding information would be lost when the browser removes the attribute.
  14674. * The `ngOpen` directive solves this problem for the `open` attribute.
  14675. * This complementary directive is not removed by the browser and so provides
  14676. * a permanent reliable place to store the binding information.
  14677. * @example
  14678. <example>
  14679. <file name="index.html">
  14680. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14681. <details id="details" ng-open="open">
  14682. <summary>Show/Hide me</summary>
  14683. </details>
  14684. </file>
  14685. <file name="protractor.js" type="protractor">
  14686. it('should toggle open', function() {
  14687. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14688. element(by.model('open')).click();
  14689. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14690. });
  14691. </file>
  14692. </example>
  14693. *
  14694. * @element DETAILS
  14695. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14696. * then special attribute "open" will be set on the element
  14697. */
  14698. var ngAttributeAliasDirectives = {};
  14699. // boolean attrs are evaluated
  14700. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14701. // binding to multiple is not supported
  14702. if (propName == "multiple") return;
  14703. var normalized = directiveNormalize('ng-' + attrName);
  14704. ngAttributeAliasDirectives[normalized] = function() {
  14705. return {
  14706. priority: 100,
  14707. link: function(scope, element, attr) {
  14708. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14709. attr.$set(attrName, !!value);
  14710. });
  14711. }
  14712. };
  14713. };
  14714. });
  14715. // ng-src, ng-srcset, ng-href are interpolated
  14716. forEach(['src', 'srcset', 'href'], function(attrName) {
  14717. var normalized = directiveNormalize('ng-' + attrName);
  14718. ngAttributeAliasDirectives[normalized] = function() {
  14719. return {
  14720. priority: 99, // it needs to run after the attributes are interpolated
  14721. link: function(scope, element, attr) {
  14722. var propName = attrName,
  14723. name = attrName;
  14724. if (attrName === 'href' &&
  14725. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14726. name = 'xlinkHref';
  14727. attr.$attr[name] = 'xlink:href';
  14728. propName = null;
  14729. }
  14730. attr.$observe(normalized, function(value) {
  14731. if (!value) {
  14732. if (attrName === 'href') {
  14733. attr.$set(name, null);
  14734. }
  14735. return;
  14736. }
  14737. attr.$set(name, value);
  14738. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14739. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14740. // to set the property as well to achieve the desired effect.
  14741. // we use attr[attrName] value since $set can sanitize the url.
  14742. if (msie && propName) element.prop(propName, attr[name]);
  14743. });
  14744. }
  14745. };
  14746. };
  14747. });
  14748. /* global -nullFormCtrl */
  14749. var nullFormCtrl = {
  14750. $addControl: noop,
  14751. $removeControl: noop,
  14752. $setValidity: noop,
  14753. $setDirty: noop,
  14754. $setPristine: noop
  14755. };
  14756. /**
  14757. * @ngdoc type
  14758. * @name form.FormController
  14759. *
  14760. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14761. * @property {boolean} $dirty True if user has already interacted with the form.
  14762. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14763. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14764. *
  14765. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14766. * forms, where:
  14767. *
  14768. * - keys are validation tokens (error names),
  14769. * - values are arrays of controls or forms that are invalid for given error name.
  14770. *
  14771. *
  14772. * Built-in validation tokens:
  14773. *
  14774. * - `email`
  14775. * - `max`
  14776. * - `maxlength`
  14777. * - `min`
  14778. * - `minlength`
  14779. * - `number`
  14780. * - `pattern`
  14781. * - `required`
  14782. * - `url`
  14783. *
  14784. * @description
  14785. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  14786. * such as being valid/invalid or dirty/pristine.
  14787. *
  14788. * Each {@link ng.directive:form form} directive creates an instance
  14789. * of `FormController`.
  14790. *
  14791. */
  14792. //asks for $scope to fool the BC controller module
  14793. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14794. function FormController(element, attrs, $scope, $animate) {
  14795. var form = this,
  14796. parentForm = element.parent().controller('form') || nullFormCtrl,
  14797. invalidCount = 0, // used to easily determine if we are valid
  14798. errors = form.$error = {},
  14799. controls = [];
  14800. // init state
  14801. form.$name = attrs.name || attrs.ngForm;
  14802. form.$dirty = false;
  14803. form.$pristine = true;
  14804. form.$valid = true;
  14805. form.$invalid = false;
  14806. parentForm.$addControl(form);
  14807. // Setup initial state of the control
  14808. element.addClass(PRISTINE_CLASS);
  14809. toggleValidCss(true);
  14810. // convenience method for easy toggling of classes
  14811. function toggleValidCss(isValid, validationErrorKey) {
  14812. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14813. $animate.setClass(element,
  14814. (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey,
  14815. (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14816. }
  14817. /**
  14818. * @ngdoc method
  14819. * @name form.FormController#$addControl
  14820. *
  14821. * @description
  14822. * Register a control with the form.
  14823. *
  14824. * Input elements using ngModelController do this automatically when they are linked.
  14825. */
  14826. form.$addControl = function(control) {
  14827. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14828. // and not added to the scope. Now we throw an error.
  14829. assertNotHasOwnProperty(control.$name, 'input');
  14830. controls.push(control);
  14831. if (control.$name) {
  14832. form[control.$name] = control;
  14833. }
  14834. };
  14835. /**
  14836. * @ngdoc method
  14837. * @name form.FormController#$removeControl
  14838. *
  14839. * @description
  14840. * Deregister a control from the form.
  14841. *
  14842. * Input elements using ngModelController do this automatically when they are destroyed.
  14843. */
  14844. form.$removeControl = function(control) {
  14845. if (control.$name && form[control.$name] === control) {
  14846. delete form[control.$name];
  14847. }
  14848. forEach(errors, function(queue, validationToken) {
  14849. form.$setValidity(validationToken, true, control);
  14850. });
  14851. arrayRemove(controls, control);
  14852. };
  14853. /**
  14854. * @ngdoc method
  14855. * @name form.FormController#$setValidity
  14856. *
  14857. * @description
  14858. * Sets the validity of a form control.
  14859. *
  14860. * This method will also propagate to parent forms.
  14861. */
  14862. form.$setValidity = function(validationToken, isValid, control) {
  14863. var queue = errors[validationToken];
  14864. if (isValid) {
  14865. if (queue) {
  14866. arrayRemove(queue, control);
  14867. if (!queue.length) {
  14868. invalidCount--;
  14869. if (!invalidCount) {
  14870. toggleValidCss(isValid);
  14871. form.$valid = true;
  14872. form.$invalid = false;
  14873. }
  14874. errors[validationToken] = false;
  14875. toggleValidCss(true, validationToken);
  14876. parentForm.$setValidity(validationToken, true, form);
  14877. }
  14878. }
  14879. } else {
  14880. if (!invalidCount) {
  14881. toggleValidCss(isValid);
  14882. }
  14883. if (queue) {
  14884. if (includes(queue, control)) return;
  14885. } else {
  14886. errors[validationToken] = queue = [];
  14887. invalidCount++;
  14888. toggleValidCss(false, validationToken);
  14889. parentForm.$setValidity(validationToken, false, form);
  14890. }
  14891. queue.push(control);
  14892. form.$valid = false;
  14893. form.$invalid = true;
  14894. }
  14895. };
  14896. /**
  14897. * @ngdoc method
  14898. * @name form.FormController#$setDirty
  14899. *
  14900. * @description
  14901. * Sets the form to a dirty state.
  14902. *
  14903. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14904. * state (ng-dirty class). This method will also propagate to parent forms.
  14905. */
  14906. form.$setDirty = function() {
  14907. $animate.removeClass(element, PRISTINE_CLASS);
  14908. $animate.addClass(element, DIRTY_CLASS);
  14909. form.$dirty = true;
  14910. form.$pristine = false;
  14911. parentForm.$setDirty();
  14912. };
  14913. /**
  14914. * @ngdoc method
  14915. * @name form.FormController#$setPristine
  14916. *
  14917. * @description
  14918. * Sets the form to its pristine state.
  14919. *
  14920. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14921. * state (ng-pristine class). This method will also propagate to all the controls contained
  14922. * in this form.
  14923. *
  14924. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14925. * saving or resetting it.
  14926. */
  14927. form.$setPristine = function () {
  14928. $animate.removeClass(element, DIRTY_CLASS);
  14929. $animate.addClass(element, PRISTINE_CLASS);
  14930. form.$dirty = false;
  14931. form.$pristine = true;
  14932. forEach(controls, function(control) {
  14933. control.$setPristine();
  14934. });
  14935. };
  14936. }
  14937. /**
  14938. * @ngdoc directive
  14939. * @name ngForm
  14940. * @restrict EAC
  14941. *
  14942. * @description
  14943. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14944. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14945. * sub-group of controls needs to be determined.
  14946. *
  14947. * Note: the purpose of `ngForm` is to group controls,
  14948. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14949. * (e.g. posting to the server, ...).
  14950. *
  14951. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14952. * related scope, under this name.
  14953. *
  14954. */
  14955. /**
  14956. * @ngdoc directive
  14957. * @name form
  14958. * @restrict E
  14959. *
  14960. * @description
  14961. * Directive that instantiates
  14962. * {@link form.FormController FormController}.
  14963. *
  14964. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14965. * this name.
  14966. *
  14967. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14968. *
  14969. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14970. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14971. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14972. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14973. * using Angular validation directives in forms that are dynamically generated using the
  14974. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14975. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14976. * `ngForm` directive and nest these in an outer `form` element.
  14977. *
  14978. *
  14979. * # CSS classes
  14980. * - `ng-valid` is set if the form is valid.
  14981. * - `ng-invalid` is set if the form is invalid.
  14982. * - `ng-pristine` is set if the form is pristine.
  14983. * - `ng-dirty` is set if the form is dirty.
  14984. *
  14985. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14986. *
  14987. *
  14988. * # Submitting a form and preventing the default action
  14989. *
  14990. * Since the role of forms in client-side Angular applications is different than in classical
  14991. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14992. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14993. * to handle the form submission in an application-specific way.
  14994. *
  14995. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14996. * `<form>` element has an `action` attribute specified.
  14997. *
  14998. * You can use one of the following two ways to specify what javascript method should be called when
  14999. * a form is submitted:
  15000. *
  15001. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  15002. * - {@link ng.directive:ngClick ngClick} directive on the first
  15003. * button or input field of type submit (input[type=submit])
  15004. *
  15005. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  15006. * or {@link ng.directive:ngClick ngClick} directives.
  15007. * This is because of the following form submission rules in the HTML specification:
  15008. *
  15009. * - If a form has only one input field then hitting enter in this field triggers form submit
  15010. * (`ngSubmit`)
  15011. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  15012. * doesn't trigger submit
  15013. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  15014. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  15015. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  15016. *
  15017. *
  15018. * ## Animation Hooks
  15019. *
  15020. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  15021. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  15022. * other validations that are performed within the form. Animations in ngForm are similar to how
  15023. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  15024. * as JS animations.
  15025. *
  15026. * The following example shows a simple way to utilize CSS transitions to style a form element
  15027. * that has been rendered as invalid after it has been validated:
  15028. *
  15029. * <pre>
  15030. * //be sure to include ngAnimate as a module to hook into more
  15031. * //advanced animations
  15032. * .my-form {
  15033. * transition:0.5s linear all;
  15034. * background: white;
  15035. * }
  15036. * .my-form.ng-invalid {
  15037. * background: red;
  15038. * color:white;
  15039. * }
  15040. * </pre>
  15041. *
  15042. * @example
  15043. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  15044. <file name="index.html">
  15045. <script>
  15046. angular.module('formExample', [])
  15047. .controller('FormController', ['$scope', function($scope) {
  15048. $scope.userType = 'guest';
  15049. }]);
  15050. </script>
  15051. <style>
  15052. .my-form {
  15053. -webkit-transition:all linear 0.5s;
  15054. transition:all linear 0.5s;
  15055. background: transparent;
  15056. }
  15057. .my-form.ng-invalid {
  15058. background: red;
  15059. }
  15060. </style>
  15061. <form name="myForm" ng-controller="FormController" class="my-form">
  15062. userType: <input name="input" ng-model="userType" required>
  15063. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  15064. <tt>userType = {{userType}}</tt><br>
  15065. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  15066. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  15067. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15068. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15069. </form>
  15070. </file>
  15071. <file name="protractor.js" type="protractor">
  15072. it('should initialize to model', function() {
  15073. var userType = element(by.binding('userType'));
  15074. var valid = element(by.binding('myForm.input.$valid'));
  15075. expect(userType.getText()).toContain('guest');
  15076. expect(valid.getText()).toContain('true');
  15077. });
  15078. it('should be invalid if empty', function() {
  15079. var userType = element(by.binding('userType'));
  15080. var valid = element(by.binding('myForm.input.$valid'));
  15081. var userInput = element(by.model('userType'));
  15082. userInput.clear();
  15083. userInput.sendKeys('');
  15084. expect(userType.getText()).toEqual('userType =');
  15085. expect(valid.getText()).toContain('false');
  15086. });
  15087. </file>
  15088. </example>
  15089. *
  15090. * @param {string=} name Name of the form. If specified, the form controller will be published into
  15091. * related scope, under this name.
  15092. */
  15093. var formDirectiveFactory = function(isNgForm) {
  15094. return ['$timeout', function($timeout) {
  15095. var formDirective = {
  15096. name: 'form',
  15097. restrict: isNgForm ? 'EAC' : 'E',
  15098. controller: FormController,
  15099. compile: function() {
  15100. return {
  15101. pre: function(scope, formElement, attr, controller) {
  15102. if (!attr.action) {
  15103. // we can't use jq events because if a form is destroyed during submission the default
  15104. // action is not prevented. see #1238
  15105. //
  15106. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  15107. // page reload if the form was destroyed by submission of the form via a click handler
  15108. // on a button in the form. Looks like an IE9 specific bug.
  15109. var preventDefaultListener = function(event) {
  15110. event.preventDefault
  15111. ? event.preventDefault()
  15112. : event.returnValue = false; // IE
  15113. };
  15114. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15115. // unregister the preventDefault listener so that we don't not leak memory but in a
  15116. // way that will achieve the prevention of the default action.
  15117. formElement.on('$destroy', function() {
  15118. $timeout(function() {
  15119. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15120. }, 0, false);
  15121. });
  15122. }
  15123. var parentFormCtrl = formElement.parent().controller('form'),
  15124. alias = attr.name || attr.ngForm;
  15125. if (alias) {
  15126. setter(scope, alias, controller, alias);
  15127. }
  15128. if (parentFormCtrl) {
  15129. formElement.on('$destroy', function() {
  15130. parentFormCtrl.$removeControl(controller);
  15131. if (alias) {
  15132. setter(scope, alias, undefined, alias);
  15133. }
  15134. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  15135. });
  15136. }
  15137. }
  15138. };
  15139. }
  15140. };
  15141. return formDirective;
  15142. }];
  15143. };
  15144. var formDirective = formDirectiveFactory();
  15145. var ngFormDirective = formDirectiveFactory(true);
  15146. /* global VALID_CLASS: true,
  15147. INVALID_CLASS: true,
  15148. PRISTINE_CLASS: true,
  15149. DIRTY_CLASS: true
  15150. */
  15151. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  15152. 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;
  15153. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  15154. var inputType = {
  15155. /**
  15156. * @ngdoc input
  15157. * @name input[text]
  15158. *
  15159. * @description
  15160. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  15161. *
  15162. * *NOTE* Not every feature offered is available for all input types.
  15163. *
  15164. * @param {string} ngModel Assignable angular expression to data-bind to.
  15165. * @param {string=} name Property name of the form under which the control is published.
  15166. * @param {string=} required Adds `required` validation error key if the value is not entered.
  15167. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15168. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15169. * `required` when you want to data-bind to the `required` attribute.
  15170. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15171. * minlength.
  15172. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15173. * maxlength.
  15174. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15175. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15176. * patterns defined as scope expressions.
  15177. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15178. * interaction with the input element.
  15179. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15180. * This parameter is ignored for input[type=password] controls, which will never trim the
  15181. * input.
  15182. *
  15183. * @example
  15184. <example name="text-input-directive" module="textInputExample">
  15185. <file name="index.html">
  15186. <script>
  15187. angular.module('textInputExample', [])
  15188. .controller('ExampleController', ['$scope', function($scope) {
  15189. $scope.text = 'guest';
  15190. $scope.word = /^\s*\w*\s*$/;
  15191. }]);
  15192. </script>
  15193. <form name="myForm" ng-controller="ExampleController">
  15194. Single word: <input type="text" name="input" ng-model="text"
  15195. ng-pattern="word" required ng-trim="false">
  15196. <span class="error" ng-show="myForm.input.$error.required">
  15197. Required!</span>
  15198. <span class="error" ng-show="myForm.input.$error.pattern">
  15199. Single word only!</span>
  15200. <tt>text = {{text}}</tt><br/>
  15201. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15202. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15203. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15204. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15205. </form>
  15206. </file>
  15207. <file name="protractor.js" type="protractor">
  15208. var text = element(by.binding('text'));
  15209. var valid = element(by.binding('myForm.input.$valid'));
  15210. var input = element(by.model('text'));
  15211. it('should initialize to model', function() {
  15212. expect(text.getText()).toContain('guest');
  15213. expect(valid.getText()).toContain('true');
  15214. });
  15215. it('should be invalid if empty', function() {
  15216. input.clear();
  15217. input.sendKeys('');
  15218. expect(text.getText()).toEqual('text =');
  15219. expect(valid.getText()).toContain('false');
  15220. });
  15221. it('should be invalid if multi word', function() {
  15222. input.clear();
  15223. input.sendKeys('hello world');
  15224. expect(valid.getText()).toContain('false');
  15225. });
  15226. </file>
  15227. </example>
  15228. */
  15229. 'text': textInputType,
  15230. /**
  15231. * @ngdoc input
  15232. * @name input[number]
  15233. *
  15234. * @description
  15235. * Text input with number validation and transformation. Sets the `number` validation
  15236. * error if not a valid number.
  15237. *
  15238. * @param {string} ngModel Assignable angular expression to data-bind to.
  15239. * @param {string=} name Property name of the form under which the control is published.
  15240. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  15241. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  15242. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15243. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15244. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15245. * `required` when you want to data-bind to the `required` attribute.
  15246. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15247. * minlength.
  15248. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15249. * maxlength.
  15250. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15251. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15252. * patterns defined as scope expressions.
  15253. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15254. * interaction with the input element.
  15255. *
  15256. * @example
  15257. <example name="number-input-directive" module="numberExample">
  15258. <file name="index.html">
  15259. <script>
  15260. angular.module('numberExample', [])
  15261. .controller('ExampleController', ['$scope', function($scope) {
  15262. $scope.value = 12;
  15263. }]);
  15264. </script>
  15265. <form name="myForm" ng-controller="ExampleController">
  15266. Number: <input type="number" name="input" ng-model="value"
  15267. min="0" max="99" required>
  15268. <span class="error" ng-show="myForm.input.$error.required">
  15269. Required!</span>
  15270. <span class="error" ng-show="myForm.input.$error.number">
  15271. Not valid number!</span>
  15272. <tt>value = {{value}}</tt><br/>
  15273. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15274. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15275. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15276. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15277. </form>
  15278. </file>
  15279. <file name="protractor.js" type="protractor">
  15280. var value = element(by.binding('value'));
  15281. var valid = element(by.binding('myForm.input.$valid'));
  15282. var input = element(by.model('value'));
  15283. it('should initialize to model', function() {
  15284. expect(value.getText()).toContain('12');
  15285. expect(valid.getText()).toContain('true');
  15286. });
  15287. it('should be invalid if empty', function() {
  15288. input.clear();
  15289. input.sendKeys('');
  15290. expect(value.getText()).toEqual('value =');
  15291. expect(valid.getText()).toContain('false');
  15292. });
  15293. it('should be invalid if over max', function() {
  15294. input.clear();
  15295. input.sendKeys('123');
  15296. expect(value.getText()).toEqual('value =');
  15297. expect(valid.getText()).toContain('false');
  15298. });
  15299. </file>
  15300. </example>
  15301. */
  15302. 'number': numberInputType,
  15303. /**
  15304. * @ngdoc input
  15305. * @name input[url]
  15306. *
  15307. * @description
  15308. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  15309. * valid URL.
  15310. *
  15311. * @param {string} ngModel Assignable angular expression to data-bind to.
  15312. * @param {string=} name Property name of the form under which the control is published.
  15313. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15314. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15315. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15316. * `required` when you want to data-bind to the `required` attribute.
  15317. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15318. * minlength.
  15319. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15320. * maxlength.
  15321. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15322. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15323. * patterns defined as scope expressions.
  15324. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15325. * interaction with the input element.
  15326. *
  15327. * @example
  15328. <example name="url-input-directive" module="urlExample">
  15329. <file name="index.html">
  15330. <script>
  15331. angular.module('urlExample', [])
  15332. .controller('ExampleController', ['$scope', function($scope) {
  15333. $scope.text = 'http://google.com';
  15334. }]);
  15335. </script>
  15336. <form name="myForm" ng-controller="ExampleController">
  15337. URL: <input type="url" name="input" ng-model="text" required>
  15338. <span class="error" ng-show="myForm.input.$error.required">
  15339. Required!</span>
  15340. <span class="error" ng-show="myForm.input.$error.url">
  15341. Not valid url!</span>
  15342. <tt>text = {{text}}</tt><br/>
  15343. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15344. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15345. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15346. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15347. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  15348. </form>
  15349. </file>
  15350. <file name="protractor.js" type="protractor">
  15351. var text = element(by.binding('text'));
  15352. var valid = element(by.binding('myForm.input.$valid'));
  15353. var input = element(by.model('text'));
  15354. it('should initialize to model', function() {
  15355. expect(text.getText()).toContain('http://google.com');
  15356. expect(valid.getText()).toContain('true');
  15357. });
  15358. it('should be invalid if empty', function() {
  15359. input.clear();
  15360. input.sendKeys('');
  15361. expect(text.getText()).toEqual('text =');
  15362. expect(valid.getText()).toContain('false');
  15363. });
  15364. it('should be invalid if not url', function() {
  15365. input.clear();
  15366. input.sendKeys('box');
  15367. expect(valid.getText()).toContain('false');
  15368. });
  15369. </file>
  15370. </example>
  15371. */
  15372. 'url': urlInputType,
  15373. /**
  15374. * @ngdoc input
  15375. * @name input[email]
  15376. *
  15377. * @description
  15378. * Text input with email validation. Sets the `email` validation error key if not a valid email
  15379. * address.
  15380. *
  15381. * @param {string} ngModel Assignable angular expression to data-bind to.
  15382. * @param {string=} name Property name of the form under which the control is published.
  15383. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15384. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15385. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15386. * `required` when you want to data-bind to the `required` attribute.
  15387. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15388. * minlength.
  15389. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15390. * maxlength.
  15391. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15392. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15393. * patterns defined as scope expressions.
  15394. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15395. * interaction with the input element.
  15396. *
  15397. * @example
  15398. <example name="email-input-directive" module="emailExample">
  15399. <file name="index.html">
  15400. <script>
  15401. angular.module('emailExample', [])
  15402. .controller('ExampleController', ['$scope', function($scope) {
  15403. $scope.text = 'me@example.com';
  15404. }]);
  15405. </script>
  15406. <form name="myForm" ng-controller="ExampleController">
  15407. Email: <input type="email" name="input" ng-model="text" required>
  15408. <span class="error" ng-show="myForm.input.$error.required">
  15409. Required!</span>
  15410. <span class="error" ng-show="myForm.input.$error.email">
  15411. Not valid email!</span>
  15412. <tt>text = {{text}}</tt><br/>
  15413. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15414. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15415. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15416. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15417. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  15418. </form>
  15419. </file>
  15420. <file name="protractor.js" type="protractor">
  15421. var text = element(by.binding('text'));
  15422. var valid = element(by.binding('myForm.input.$valid'));
  15423. var input = element(by.model('text'));
  15424. it('should initialize to model', function() {
  15425. expect(text.getText()).toContain('me@example.com');
  15426. expect(valid.getText()).toContain('true');
  15427. });
  15428. it('should be invalid if empty', function() {
  15429. input.clear();
  15430. input.sendKeys('');
  15431. expect(text.getText()).toEqual('text =');
  15432. expect(valid.getText()).toContain('false');
  15433. });
  15434. it('should be invalid if not email', function() {
  15435. input.clear();
  15436. input.sendKeys('xxx');
  15437. expect(valid.getText()).toContain('false');
  15438. });
  15439. </file>
  15440. </example>
  15441. */
  15442. 'email': emailInputType,
  15443. /**
  15444. * @ngdoc input
  15445. * @name input[radio]
  15446. *
  15447. * @description
  15448. * HTML radio button.
  15449. *
  15450. * @param {string} ngModel Assignable angular expression to data-bind to.
  15451. * @param {string} value The value to which the expression should be set when selected.
  15452. * @param {string=} name Property name of the form under which the control is published.
  15453. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15454. * interaction with the input element.
  15455. * @param {string} ngValue Angular expression which sets the value to which the expression should
  15456. * be set when selected.
  15457. *
  15458. * @example
  15459. <example name="radio-input-directive" module="radioExample">
  15460. <file name="index.html">
  15461. <script>
  15462. angular.module('radioExample', [])
  15463. .controller('ExampleController', ['$scope', function($scope) {
  15464. $scope.color = 'blue';
  15465. $scope.specialValue = {
  15466. "id": "12345",
  15467. "value": "green"
  15468. };
  15469. }]);
  15470. </script>
  15471. <form name="myForm" ng-controller="ExampleController">
  15472. <input type="radio" ng-model="color" value="red"> Red <br/>
  15473. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  15474. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  15475. <tt>color = {{color | json}}</tt><br/>
  15476. </form>
  15477. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  15478. </file>
  15479. <file name="protractor.js" type="protractor">
  15480. it('should change state', function() {
  15481. var color = element(by.binding('color'));
  15482. expect(color.getText()).toContain('blue');
  15483. element.all(by.model('color')).get(0).click();
  15484. expect(color.getText()).toContain('red');
  15485. });
  15486. </file>
  15487. </example>
  15488. */
  15489. 'radio': radioInputType,
  15490. /**
  15491. * @ngdoc input
  15492. * @name input[checkbox]
  15493. *
  15494. * @description
  15495. * HTML checkbox.
  15496. *
  15497. * @param {string} ngModel Assignable angular expression to data-bind to.
  15498. * @param {string=} name Property name of the form under which the control is published.
  15499. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  15500. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  15501. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15502. * interaction with the input element.
  15503. *
  15504. * @example
  15505. <example name="checkbox-input-directive" module="checkboxExample">
  15506. <file name="index.html">
  15507. <script>
  15508. angular.module('checkboxExample', [])
  15509. .controller('ExampleController', ['$scope', function($scope) {
  15510. $scope.value1 = true;
  15511. $scope.value2 = 'YES'
  15512. }]);
  15513. </script>
  15514. <form name="myForm" ng-controller="ExampleController">
  15515. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15516. Value2: <input type="checkbox" ng-model="value2"
  15517. ng-true-value="YES" ng-false-value="NO"> <br/>
  15518. <tt>value1 = {{value1}}</tt><br/>
  15519. <tt>value2 = {{value2}}</tt><br/>
  15520. </form>
  15521. </file>
  15522. <file name="protractor.js" type="protractor">
  15523. it('should change state', function() {
  15524. var value1 = element(by.binding('value1'));
  15525. var value2 = element(by.binding('value2'));
  15526. expect(value1.getText()).toContain('true');
  15527. expect(value2.getText()).toContain('YES');
  15528. element(by.model('value1')).click();
  15529. element(by.model('value2')).click();
  15530. expect(value1.getText()).toContain('false');
  15531. expect(value2.getText()).toContain('NO');
  15532. });
  15533. </file>
  15534. </example>
  15535. */
  15536. 'checkbox': checkboxInputType,
  15537. 'hidden': noop,
  15538. 'button': noop,
  15539. 'submit': noop,
  15540. 'reset': noop,
  15541. 'file': noop
  15542. };
  15543. // A helper function to call $setValidity and return the value / undefined,
  15544. // a pattern that is repeated a lot in the input validation logic.
  15545. function validate(ctrl, validatorName, validity, value){
  15546. ctrl.$setValidity(validatorName, validity);
  15547. return validity ? value : undefined;
  15548. }
  15549. function testFlags(validity, flags) {
  15550. var i, flag;
  15551. if (flags) {
  15552. for (i=0; i<flags.length; ++i) {
  15553. flag = flags[i];
  15554. if (validity[flag]) {
  15555. return true;
  15556. }
  15557. }
  15558. }
  15559. return false;
  15560. }
  15561. // Pass validity so that behaviour can be mocked easier.
  15562. function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
  15563. if (isObject(validity)) {
  15564. ctrl.$$hasNativeValidators = true;
  15565. var validator = function(value) {
  15566. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15567. // perform the required validation)
  15568. if (!ctrl.$error[validatorName] &&
  15569. !testFlags(validity, ignoreFlags) &&
  15570. testFlags(validity, badFlags)) {
  15571. ctrl.$setValidity(validatorName, false);
  15572. return;
  15573. }
  15574. return value;
  15575. };
  15576. ctrl.$parsers.push(validator);
  15577. }
  15578. }
  15579. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15580. var validity = element.prop(VALIDITY_STATE_PROPERTY);
  15581. var placeholder = element[0].placeholder, noevent = {};
  15582. var type = lowercase(element[0].type);
  15583. ctrl.$$validityState = validity;
  15584. // In composition mode, users are still inputing intermediate text buffer,
  15585. // hold the listener until composition is done.
  15586. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15587. if (!$sniffer.android) {
  15588. var composing = false;
  15589. element.on('compositionstart', function(data) {
  15590. composing = true;
  15591. });
  15592. element.on('compositionend', function() {
  15593. composing = false;
  15594. listener();
  15595. });
  15596. }
  15597. var listener = function(ev) {
  15598. if (composing) return;
  15599. var value = element.val();
  15600. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  15601. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  15602. // IE also sends input events for other non-input-related things, (such as focusing on a
  15603. // form control), so this change is not entirely enough to solve this.
  15604. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  15605. placeholder = element[0].placeholder;
  15606. return;
  15607. }
  15608. // By default we will trim the value
  15609. // If the attribute ng-trim exists we will avoid trimming
  15610. // If input type is 'password', the value is never trimmed
  15611. if (type !== 'password' && (toBoolean(attr.ngTrim || 'T'))) {
  15612. value = trim(value);
  15613. }
  15614. // If a control is suffering from bad input, browsers discard its value, so it may be
  15615. // necessary to revalidate even if the control's value is the same empty value twice in
  15616. // a row.
  15617. var revalidate = validity && ctrl.$$hasNativeValidators;
  15618. if (ctrl.$viewValue !== value || (value === '' && revalidate)) {
  15619. if (scope.$root.$$phase) {
  15620. ctrl.$setViewValue(value);
  15621. } else {
  15622. scope.$apply(function() {
  15623. ctrl.$setViewValue(value);
  15624. });
  15625. }
  15626. }
  15627. };
  15628. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15629. // input event on backspace, delete or cut
  15630. if ($sniffer.hasEvent('input')) {
  15631. element.on('input', listener);
  15632. } else {
  15633. var timeout;
  15634. var deferListener = function() {
  15635. if (!timeout) {
  15636. timeout = $browser.defer(function() {
  15637. listener();
  15638. timeout = null;
  15639. });
  15640. }
  15641. };
  15642. element.on('keydown', function(event) {
  15643. var key = event.keyCode;
  15644. // ignore
  15645. // command modifiers arrows
  15646. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15647. deferListener();
  15648. });
  15649. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15650. if ($sniffer.hasEvent('paste')) {
  15651. element.on('paste cut', deferListener);
  15652. }
  15653. }
  15654. // if user paste into input using mouse on older browser
  15655. // or form autocomplete on newer browser, we need "change" event to catch it
  15656. element.on('change', listener);
  15657. ctrl.$render = function() {
  15658. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15659. };
  15660. // pattern validator
  15661. var pattern = attr.ngPattern,
  15662. patternValidator,
  15663. match;
  15664. if (pattern) {
  15665. var validateRegex = function(regexp, value) {
  15666. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15667. };
  15668. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15669. if (match) {
  15670. pattern = new RegExp(match[1], match[2]);
  15671. patternValidator = function(value) {
  15672. return validateRegex(pattern, value);
  15673. };
  15674. } else {
  15675. patternValidator = function(value) {
  15676. var patternObj = scope.$eval(pattern);
  15677. if (!patternObj || !patternObj.test) {
  15678. throw minErr('ngPattern')('noregexp',
  15679. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15680. patternObj, startingTag(element));
  15681. }
  15682. return validateRegex(patternObj, value);
  15683. };
  15684. }
  15685. ctrl.$formatters.push(patternValidator);
  15686. ctrl.$parsers.push(patternValidator);
  15687. }
  15688. // min length validator
  15689. if (attr.ngMinlength) {
  15690. var minlength = int(attr.ngMinlength);
  15691. var minLengthValidator = function(value) {
  15692. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15693. };
  15694. ctrl.$parsers.push(minLengthValidator);
  15695. ctrl.$formatters.push(minLengthValidator);
  15696. }
  15697. // max length validator
  15698. if (attr.ngMaxlength) {
  15699. var maxlength = int(attr.ngMaxlength);
  15700. var maxLengthValidator = function(value) {
  15701. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15702. };
  15703. ctrl.$parsers.push(maxLengthValidator);
  15704. ctrl.$formatters.push(maxLengthValidator);
  15705. }
  15706. }
  15707. var numberBadFlags = ['badInput'];
  15708. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15709. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15710. ctrl.$parsers.push(function(value) {
  15711. var empty = ctrl.$isEmpty(value);
  15712. if (empty || NUMBER_REGEXP.test(value)) {
  15713. ctrl.$setValidity('number', true);
  15714. return value === '' ? null : (empty ? value : parseFloat(value));
  15715. } else {
  15716. ctrl.$setValidity('number', false);
  15717. return undefined;
  15718. }
  15719. });
  15720. addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
  15721. ctrl.$formatters.push(function(value) {
  15722. return ctrl.$isEmpty(value) ? '' : '' + value;
  15723. });
  15724. if (attr.min) {
  15725. var minValidator = function(value) {
  15726. var min = parseFloat(attr.min);
  15727. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15728. };
  15729. ctrl.$parsers.push(minValidator);
  15730. ctrl.$formatters.push(minValidator);
  15731. }
  15732. if (attr.max) {
  15733. var maxValidator = function(value) {
  15734. var max = parseFloat(attr.max);
  15735. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15736. };
  15737. ctrl.$parsers.push(maxValidator);
  15738. ctrl.$formatters.push(maxValidator);
  15739. }
  15740. ctrl.$formatters.push(function(value) {
  15741. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15742. });
  15743. }
  15744. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15745. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15746. var urlValidator = function(value) {
  15747. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15748. };
  15749. ctrl.$formatters.push(urlValidator);
  15750. ctrl.$parsers.push(urlValidator);
  15751. }
  15752. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15753. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15754. var emailValidator = function(value) {
  15755. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15756. };
  15757. ctrl.$formatters.push(emailValidator);
  15758. ctrl.$parsers.push(emailValidator);
  15759. }
  15760. function radioInputType(scope, element, attr, ctrl) {
  15761. // make the name unique, if not defined
  15762. if (isUndefined(attr.name)) {
  15763. element.attr('name', nextUid());
  15764. }
  15765. element.on('click', function() {
  15766. if (element[0].checked) {
  15767. scope.$apply(function() {
  15768. ctrl.$setViewValue(attr.value);
  15769. });
  15770. }
  15771. });
  15772. ctrl.$render = function() {
  15773. var value = attr.value;
  15774. element[0].checked = (value == ctrl.$viewValue);
  15775. };
  15776. attr.$observe('value', ctrl.$render);
  15777. }
  15778. function checkboxInputType(scope, element, attr, ctrl) {
  15779. var trueValue = attr.ngTrueValue,
  15780. falseValue = attr.ngFalseValue;
  15781. if (!isString(trueValue)) trueValue = true;
  15782. if (!isString(falseValue)) falseValue = false;
  15783. element.on('click', function() {
  15784. scope.$apply(function() {
  15785. ctrl.$setViewValue(element[0].checked);
  15786. });
  15787. });
  15788. ctrl.$render = function() {
  15789. element[0].checked = ctrl.$viewValue;
  15790. };
  15791. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15792. ctrl.$isEmpty = function(value) {
  15793. return value !== trueValue;
  15794. };
  15795. ctrl.$formatters.push(function(value) {
  15796. return value === trueValue;
  15797. });
  15798. ctrl.$parsers.push(function(value) {
  15799. return value ? trueValue : falseValue;
  15800. });
  15801. }
  15802. /**
  15803. * @ngdoc directive
  15804. * @name textarea
  15805. * @restrict E
  15806. *
  15807. * @description
  15808. * HTML textarea element control with angular data-binding. The data-binding and validation
  15809. * properties of this element are exactly the same as those of the
  15810. * {@link ng.directive:input input element}.
  15811. *
  15812. * @param {string} ngModel Assignable angular expression to data-bind to.
  15813. * @param {string=} name Property name of the form under which the control is published.
  15814. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15815. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15816. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15817. * `required` when you want to data-bind to the `required` attribute.
  15818. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15819. * minlength.
  15820. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15821. * maxlength.
  15822. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15823. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15824. * patterns defined as scope expressions.
  15825. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15826. * interaction with the input element.
  15827. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15828. */
  15829. /**
  15830. * @ngdoc directive
  15831. * @name input
  15832. * @restrict E
  15833. *
  15834. * @description
  15835. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15836. * and polyfills the HTML5 validation behavior for older browsers.
  15837. *
  15838. * *NOTE* Not every feature offered is available for all input types.
  15839. *
  15840. * @param {string} ngModel Assignable angular expression to data-bind to.
  15841. * @param {string=} name Property name of the form under which the control is published.
  15842. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15843. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15844. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15845. * minlength.
  15846. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15847. * maxlength.
  15848. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15849. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15850. * patterns defined as scope expressions.
  15851. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15852. * interaction with the input element.
  15853. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15854. * This parameter is ignored for input[type=password] controls, which will never trim the
  15855. * input.
  15856. *
  15857. * @example
  15858. <example name="input-directive" module="inputExample">
  15859. <file name="index.html">
  15860. <script>
  15861. angular.module('inputExample', [])
  15862. .controller('ExampleController', ['$scope', function($scope) {
  15863. $scope.user = {name: 'guest', last: 'visitor'};
  15864. }]);
  15865. </script>
  15866. <div ng-controller="ExampleController">
  15867. <form name="myForm">
  15868. User name: <input type="text" name="userName" ng-model="user.name" required>
  15869. <span class="error" ng-show="myForm.userName.$error.required">
  15870. Required!</span><br>
  15871. Last name: <input type="text" name="lastName" ng-model="user.last"
  15872. ng-minlength="3" ng-maxlength="10">
  15873. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15874. Too short!</span>
  15875. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15876. Too long!</span><br>
  15877. </form>
  15878. <hr>
  15879. <tt>user = {{user}}</tt><br/>
  15880. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15881. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15882. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15883. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15884. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15885. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15886. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15887. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15888. </div>
  15889. </file>
  15890. <file name="protractor.js" type="protractor">
  15891. var user = element(by.binding('{{user}}'));
  15892. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15893. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15894. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15895. var formValid = element(by.binding('myForm.$valid'));
  15896. var userNameInput = element(by.model('user.name'));
  15897. var userLastInput = element(by.model('user.last'));
  15898. it('should initialize to model', function() {
  15899. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15900. expect(userNameValid.getText()).toContain('true');
  15901. expect(formValid.getText()).toContain('true');
  15902. });
  15903. it('should be invalid if empty when required', function() {
  15904. userNameInput.clear();
  15905. userNameInput.sendKeys('');
  15906. expect(user.getText()).toContain('{"last":"visitor"}');
  15907. expect(userNameValid.getText()).toContain('false');
  15908. expect(formValid.getText()).toContain('false');
  15909. });
  15910. it('should be valid if empty when min length is set', function() {
  15911. userLastInput.clear();
  15912. userLastInput.sendKeys('');
  15913. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15914. expect(lastNameValid.getText()).toContain('true');
  15915. expect(formValid.getText()).toContain('true');
  15916. });
  15917. it('should be invalid if less than required min length', function() {
  15918. userLastInput.clear();
  15919. userLastInput.sendKeys('xx');
  15920. expect(user.getText()).toContain('{"name":"guest"}');
  15921. expect(lastNameValid.getText()).toContain('false');
  15922. expect(lastNameError.getText()).toContain('minlength');
  15923. expect(formValid.getText()).toContain('false');
  15924. });
  15925. it('should be invalid if longer than max length', function() {
  15926. userLastInput.clear();
  15927. userLastInput.sendKeys('some ridiculously long name');
  15928. expect(user.getText()).toContain('{"name":"guest"}');
  15929. expect(lastNameValid.getText()).toContain('false');
  15930. expect(lastNameError.getText()).toContain('maxlength');
  15931. expect(formValid.getText()).toContain('false');
  15932. });
  15933. </file>
  15934. </example>
  15935. */
  15936. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15937. return {
  15938. restrict: 'E',
  15939. require: '?ngModel',
  15940. link: function(scope, element, attr, ctrl) {
  15941. if (ctrl) {
  15942. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15943. $browser);
  15944. }
  15945. }
  15946. };
  15947. }];
  15948. var VALID_CLASS = 'ng-valid',
  15949. INVALID_CLASS = 'ng-invalid',
  15950. PRISTINE_CLASS = 'ng-pristine',
  15951. DIRTY_CLASS = 'ng-dirty';
  15952. /**
  15953. * @ngdoc type
  15954. * @name ngModel.NgModelController
  15955. *
  15956. * @property {string} $viewValue Actual string value in the view.
  15957. * @property {*} $modelValue The value in the model, that the control is bound to.
  15958. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15959. the control reads value from the DOM. Each function is called, in turn, passing the value
  15960. through to the next. The last return value is used to populate the model.
  15961. Used to sanitize / convert the value as well as validation. For validation,
  15962. the parsers should update the validity state using
  15963. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15964. and return `undefined` for invalid values.
  15965. *
  15966. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15967. the model value changes. Each function is called, in turn, passing the value through to the
  15968. next. Used to format / convert values for display in the control and validation.
  15969. * ```js
  15970. * function formatter(value) {
  15971. * if (value) {
  15972. * return value.toUpperCase();
  15973. * }
  15974. * }
  15975. * ngModel.$formatters.push(formatter);
  15976. * ```
  15977. *
  15978. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15979. * view value has changed. It is called with no arguments, and its return value is ignored.
  15980. * This can be used in place of additional $watches against the model value.
  15981. *
  15982. * @property {Object} $error An object hash with all errors as keys.
  15983. *
  15984. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15985. * @property {boolean} $dirty True if user has already interacted with the control.
  15986. * @property {boolean} $valid True if there is no error.
  15987. * @property {boolean} $invalid True if at least one error on the control.
  15988. *
  15989. * @description
  15990. *
  15991. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15992. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15993. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15994. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15995. * `NgModelController` for data-binding.
  15996. *
  15997. * ## Custom Control Example
  15998. * This example shows how to use `NgModelController` with a custom control to achieve
  15999. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  16000. * collaborate together to achieve the desired result.
  16001. *
  16002. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  16003. * contents be edited in place by the user. This will not work on older browsers.
  16004. *
  16005. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  16006. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  16007. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  16008. * that content using the `$sce` service.
  16009. *
  16010. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  16011. <file name="style.css">
  16012. [contenteditable] {
  16013. border: 1px solid black;
  16014. background-color: white;
  16015. min-height: 20px;
  16016. }
  16017. .ng-invalid {
  16018. border: 1px solid red;
  16019. }
  16020. </file>
  16021. <file name="script.js">
  16022. angular.module('customControl', ['ngSanitize']).
  16023. directive('contenteditable', ['$sce', function($sce) {
  16024. return {
  16025. restrict: 'A', // only activate on element attribute
  16026. require: '?ngModel', // get a hold of NgModelController
  16027. link: function(scope, element, attrs, ngModel) {
  16028. if(!ngModel) return; // do nothing if no ng-model
  16029. // Specify how UI should be updated
  16030. ngModel.$render = function() {
  16031. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  16032. };
  16033. // Listen for change events to enable binding
  16034. element.on('blur keyup change', function() {
  16035. scope.$evalAsync(read);
  16036. });
  16037. read(); // initialize
  16038. // Write data to the model
  16039. function read() {
  16040. var html = element.html();
  16041. // When we clear the content editable the browser leaves a <br> behind
  16042. // If strip-br attribute is provided then we strip this out
  16043. if( attrs.stripBr && html == '<br>' ) {
  16044. html = '';
  16045. }
  16046. ngModel.$setViewValue(html);
  16047. }
  16048. }
  16049. };
  16050. }]);
  16051. </file>
  16052. <file name="index.html">
  16053. <form name="myForm">
  16054. <div contenteditable
  16055. name="myWidget" ng-model="userContent"
  16056. strip-br="true"
  16057. required>Change me!</div>
  16058. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  16059. <hr>
  16060. <textarea ng-model="userContent"></textarea>
  16061. </form>
  16062. </file>
  16063. <file name="protractor.js" type="protractor">
  16064. it('should data-bind and become invalid', function() {
  16065. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  16066. // SafariDriver can't handle contenteditable
  16067. // and Firefox driver can't clear contenteditables very well
  16068. return;
  16069. }
  16070. var contentEditable = element(by.css('[contenteditable]'));
  16071. var content = 'Change me!';
  16072. expect(contentEditable.getText()).toEqual(content);
  16073. contentEditable.clear();
  16074. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  16075. expect(contentEditable.getText()).toEqual('');
  16076. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  16077. });
  16078. </file>
  16079. * </example>
  16080. *
  16081. *
  16082. */
  16083. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  16084. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  16085. this.$viewValue = Number.NaN;
  16086. this.$modelValue = Number.NaN;
  16087. this.$parsers = [];
  16088. this.$formatters = [];
  16089. this.$viewChangeListeners = [];
  16090. this.$pristine = true;
  16091. this.$dirty = false;
  16092. this.$valid = true;
  16093. this.$invalid = false;
  16094. this.$name = $attr.name;
  16095. var ngModelGet = $parse($attr.ngModel),
  16096. ngModelSet = ngModelGet.assign;
  16097. if (!ngModelSet) {
  16098. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  16099. $attr.ngModel, startingTag($element));
  16100. }
  16101. /**
  16102. * @ngdoc method
  16103. * @name ngModel.NgModelController#$render
  16104. *
  16105. * @description
  16106. * Called when the view needs to be updated. It is expected that the user of the ng-model
  16107. * directive will implement this method.
  16108. */
  16109. this.$render = noop;
  16110. /**
  16111. * @ngdoc method
  16112. * @name ngModel.NgModelController#$isEmpty
  16113. *
  16114. * @description
  16115. * This is called when we need to determine if the value of the input is empty.
  16116. *
  16117. * For instance, the required directive does this to work out if the input has data or not.
  16118. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  16119. *
  16120. * You can override this for input directives whose concept of being empty is different to the
  16121. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  16122. * implies empty.
  16123. *
  16124. * @param {*} value Reference to check.
  16125. * @returns {boolean} True if `value` is empty.
  16126. */
  16127. this.$isEmpty = function(value) {
  16128. return isUndefined(value) || value === '' || value === null || value !== value;
  16129. };
  16130. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  16131. invalidCount = 0, // used to easily determine if we are valid
  16132. $error = this.$error = {}; // keep invalid keys here
  16133. // Setup initial state of the control
  16134. $element.addClass(PRISTINE_CLASS);
  16135. toggleValidCss(true);
  16136. // convenience method for easy toggling of classes
  16137. function toggleValidCss(isValid, validationErrorKey) {
  16138. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  16139. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  16140. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  16141. }
  16142. /**
  16143. * @ngdoc method
  16144. * @name ngModel.NgModelController#$setValidity
  16145. *
  16146. * @description
  16147. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  16148. * does not notify form if given validator is already marked as invalid).
  16149. *
  16150. * This method should be called by validators - i.e. the parser or formatter functions.
  16151. *
  16152. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  16153. * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding.
  16154. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  16155. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  16156. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  16157. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  16158. */
  16159. this.$setValidity = function(validationErrorKey, isValid) {
  16160. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  16161. // jshint -W018
  16162. if ($error[validationErrorKey] === !isValid) return;
  16163. // jshint +W018
  16164. if (isValid) {
  16165. if ($error[validationErrorKey]) invalidCount--;
  16166. if (!invalidCount) {
  16167. toggleValidCss(true);
  16168. this.$valid = true;
  16169. this.$invalid = false;
  16170. }
  16171. } else {
  16172. toggleValidCss(false);
  16173. this.$invalid = true;
  16174. this.$valid = false;
  16175. invalidCount++;
  16176. }
  16177. $error[validationErrorKey] = !isValid;
  16178. toggleValidCss(isValid, validationErrorKey);
  16179. parentForm.$setValidity(validationErrorKey, isValid, this);
  16180. };
  16181. /**
  16182. * @ngdoc method
  16183. * @name ngModel.NgModelController#$setPristine
  16184. *
  16185. * @description
  16186. * Sets the control to its pristine state.
  16187. *
  16188. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  16189. * state (ng-pristine class).
  16190. */
  16191. this.$setPristine = function () {
  16192. this.$dirty = false;
  16193. this.$pristine = true;
  16194. $animate.removeClass($element, DIRTY_CLASS);
  16195. $animate.addClass($element, PRISTINE_CLASS);
  16196. };
  16197. /**
  16198. * @ngdoc method
  16199. * @name ngModel.NgModelController#$setViewValue
  16200. *
  16201. * @description
  16202. * Update the view value.
  16203. *
  16204. * This method should be called when the view value changes, typically from within a DOM event handler.
  16205. * For example {@link ng.directive:input input} and
  16206. * {@link ng.directive:select select} directives call it.
  16207. *
  16208. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  16209. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  16210. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  16211. *
  16212. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  16213. *
  16214. * Note that calling this function does not trigger a `$digest`.
  16215. *
  16216. * @param {string} value Value from the view.
  16217. */
  16218. this.$setViewValue = function(value) {
  16219. this.$viewValue = value;
  16220. // change to dirty
  16221. if (this.$pristine) {
  16222. this.$dirty = true;
  16223. this.$pristine = false;
  16224. $animate.removeClass($element, PRISTINE_CLASS);
  16225. $animate.addClass($element, DIRTY_CLASS);
  16226. parentForm.$setDirty();
  16227. }
  16228. forEach(this.$parsers, function(fn) {
  16229. value = fn(value);
  16230. });
  16231. if (this.$modelValue !== value) {
  16232. this.$modelValue = value;
  16233. ngModelSet($scope, value);
  16234. forEach(this.$viewChangeListeners, function(listener) {
  16235. try {
  16236. listener();
  16237. } catch(e) {
  16238. $exceptionHandler(e);
  16239. }
  16240. });
  16241. }
  16242. };
  16243. // model -> value
  16244. var ctrl = this;
  16245. $scope.$watch(function ngModelWatch() {
  16246. var value = ngModelGet($scope);
  16247. // if scope model value and ngModel value are out of sync
  16248. if (ctrl.$modelValue !== value) {
  16249. var formatters = ctrl.$formatters,
  16250. idx = formatters.length;
  16251. ctrl.$modelValue = value;
  16252. while(idx--) {
  16253. value = formatters[idx](value);
  16254. }
  16255. if (ctrl.$viewValue !== value) {
  16256. ctrl.$viewValue = value;
  16257. ctrl.$render();
  16258. }
  16259. }
  16260. return value;
  16261. });
  16262. }];
  16263. /**
  16264. * @ngdoc directive
  16265. * @name ngModel
  16266. *
  16267. * @element input
  16268. *
  16269. * @description
  16270. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  16271. * property on the scope using {@link ngModel.NgModelController NgModelController},
  16272. * which is created and exposed by this directive.
  16273. *
  16274. * `ngModel` is responsible for:
  16275. *
  16276. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  16277. * require.
  16278. * - Providing validation behavior (i.e. required, number, email, url).
  16279. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  16280. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  16281. * - Registering the control with its parent {@link ng.directive:form form}.
  16282. *
  16283. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  16284. * current scope. If the property doesn't already exist on this scope, it will be created
  16285. * implicitly and added to the scope.
  16286. *
  16287. * For best practices on using `ngModel`, see:
  16288. *
  16289. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  16290. *
  16291. * For basic examples, how to use `ngModel`, see:
  16292. *
  16293. * - {@link ng.directive:input input}
  16294. * - {@link input[text] text}
  16295. * - {@link input[checkbox] checkbox}
  16296. * - {@link input[radio] radio}
  16297. * - {@link input[number] number}
  16298. * - {@link input[email] email}
  16299. * - {@link input[url] url}
  16300. * - {@link ng.directive:select select}
  16301. * - {@link ng.directive:textarea textarea}
  16302. *
  16303. * # CSS classes
  16304. * The following CSS classes are added and removed on the associated input/select/textarea element
  16305. * depending on the validity of the model.
  16306. *
  16307. * - `ng-valid` is set if the model is valid.
  16308. * - `ng-invalid` is set if the model is invalid.
  16309. * - `ng-pristine` is set if the model is pristine.
  16310. * - `ng-dirty` is set if the model is dirty.
  16311. *
  16312. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16313. *
  16314. * ## Animation Hooks
  16315. *
  16316. * Animations within models are triggered when any of the associated CSS classes are added and removed
  16317. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  16318. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  16319. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  16320. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  16321. *
  16322. * The following example shows a simple way to utilize CSS transitions to style an input element
  16323. * that has been rendered as invalid after it has been validated:
  16324. *
  16325. * <pre>
  16326. * //be sure to include ngAnimate as a module to hook into more
  16327. * //advanced animations
  16328. * .my-input {
  16329. * transition:0.5s linear all;
  16330. * background: white;
  16331. * }
  16332. * .my-input.ng-invalid {
  16333. * background: red;
  16334. * color:white;
  16335. * }
  16336. * </pre>
  16337. *
  16338. * @example
  16339. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  16340. <file name="index.html">
  16341. <script>
  16342. angular.module('inputExample', [])
  16343. .controller('ExampleController', ['$scope', function($scope) {
  16344. $scope.val = '1';
  16345. }]);
  16346. </script>
  16347. <style>
  16348. .my-input {
  16349. -webkit-transition:all linear 0.5s;
  16350. transition:all linear 0.5s;
  16351. background: transparent;
  16352. }
  16353. .my-input.ng-invalid {
  16354. color:white;
  16355. background: red;
  16356. }
  16357. </style>
  16358. Update input to see transitions when valid/invalid.
  16359. Integer is a valid value.
  16360. <form name="testForm" ng-controller="ExampleController">
  16361. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  16362. </form>
  16363. </file>
  16364. * </example>
  16365. */
  16366. var ngModelDirective = function() {
  16367. return {
  16368. require: ['ngModel', '^?form'],
  16369. controller: NgModelController,
  16370. link: function(scope, element, attr, ctrls) {
  16371. // notify others, especially parent forms
  16372. var modelCtrl = ctrls[0],
  16373. formCtrl = ctrls[1] || nullFormCtrl;
  16374. formCtrl.$addControl(modelCtrl);
  16375. scope.$on('$destroy', function() {
  16376. formCtrl.$removeControl(modelCtrl);
  16377. });
  16378. }
  16379. };
  16380. };
  16381. /**
  16382. * @ngdoc directive
  16383. * @name ngChange
  16384. *
  16385. * @description
  16386. * Evaluate the given expression when the user changes the input.
  16387. * The expression is evaluated immediately, unlike the JavaScript onchange event
  16388. * which only triggers at the end of a change (usually, when the user leaves the
  16389. * form element or presses the return key).
  16390. * The expression is not evaluated when the value change is coming from the model.
  16391. *
  16392. * Note, this directive requires `ngModel` to be present.
  16393. *
  16394. * @element input
  16395. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  16396. * in input value.
  16397. *
  16398. * @example
  16399. * <example name="ngChange-directive" module="changeExample">
  16400. * <file name="index.html">
  16401. * <script>
  16402. * angular.module('changeExample', [])
  16403. * .controller('ExampleController', ['$scope', function($scope) {
  16404. * $scope.counter = 0;
  16405. * $scope.change = function() {
  16406. * $scope.counter++;
  16407. * };
  16408. * }]);
  16409. * </script>
  16410. * <div ng-controller="ExampleController">
  16411. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  16412. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  16413. * <label for="ng-change-example2">Confirmed</label><br />
  16414. * <tt>debug = {{confirmed}}</tt><br/>
  16415. * <tt>counter = {{counter}}</tt><br/>
  16416. * </div>
  16417. * </file>
  16418. * <file name="protractor.js" type="protractor">
  16419. * var counter = element(by.binding('counter'));
  16420. * var debug = element(by.binding('confirmed'));
  16421. *
  16422. * it('should evaluate the expression if changing from view', function() {
  16423. * expect(counter.getText()).toContain('0');
  16424. *
  16425. * element(by.id('ng-change-example1')).click();
  16426. *
  16427. * expect(counter.getText()).toContain('1');
  16428. * expect(debug.getText()).toContain('true');
  16429. * });
  16430. *
  16431. * it('should not evaluate the expression if changing from model', function() {
  16432. * element(by.id('ng-change-example2')).click();
  16433. * expect(counter.getText()).toContain('0');
  16434. * expect(debug.getText()).toContain('true');
  16435. * });
  16436. * </file>
  16437. * </example>
  16438. */
  16439. var ngChangeDirective = valueFn({
  16440. require: 'ngModel',
  16441. link: function(scope, element, attr, ctrl) {
  16442. ctrl.$viewChangeListeners.push(function() {
  16443. scope.$eval(attr.ngChange);
  16444. });
  16445. }
  16446. });
  16447. var requiredDirective = function() {
  16448. return {
  16449. require: '?ngModel',
  16450. link: function(scope, elm, attr, ctrl) {
  16451. if (!ctrl) return;
  16452. attr.required = true; // force truthy in case we are on non input element
  16453. var validator = function(value) {
  16454. if (attr.required && ctrl.$isEmpty(value)) {
  16455. ctrl.$setValidity('required', false);
  16456. return;
  16457. } else {
  16458. ctrl.$setValidity('required', true);
  16459. return value;
  16460. }
  16461. };
  16462. ctrl.$formatters.push(validator);
  16463. ctrl.$parsers.unshift(validator);
  16464. attr.$observe('required', function() {
  16465. validator(ctrl.$viewValue);
  16466. });
  16467. }
  16468. };
  16469. };
  16470. /**
  16471. * @ngdoc directive
  16472. * @name ngList
  16473. *
  16474. * @description
  16475. * Text input that converts between a delimited string and an array of strings. The delimiter
  16476. * can be a fixed string (by default a comma) or a regular expression.
  16477. *
  16478. * @element input
  16479. * @param {string=} ngList optional delimiter that should be used to split the value. If
  16480. * specified in form `/something/` then the value will be converted into a regular expression.
  16481. *
  16482. * @example
  16483. <example name="ngList-directive" module="listExample">
  16484. <file name="index.html">
  16485. <script>
  16486. angular.module('listExample', [])
  16487. .controller('ExampleController', ['$scope', function($scope) {
  16488. $scope.names = ['igor', 'misko', 'vojta'];
  16489. }]);
  16490. </script>
  16491. <form name="myForm" ng-controller="ExampleController">
  16492. List: <input name="namesInput" ng-model="names" ng-list required>
  16493. <span class="error" ng-show="myForm.namesInput.$error.required">
  16494. Required!</span>
  16495. <br>
  16496. <tt>names = {{names}}</tt><br/>
  16497. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  16498. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  16499. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16500. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16501. </form>
  16502. </file>
  16503. <file name="protractor.js" type="protractor">
  16504. var listInput = element(by.model('names'));
  16505. var names = element(by.binding('{{names}}'));
  16506. var valid = element(by.binding('myForm.namesInput.$valid'));
  16507. var error = element(by.css('span.error'));
  16508. it('should initialize to model', function() {
  16509. expect(names.getText()).toContain('["igor","misko","vojta"]');
  16510. expect(valid.getText()).toContain('true');
  16511. expect(error.getCssValue('display')).toBe('none');
  16512. });
  16513. it('should be invalid if empty', function() {
  16514. listInput.clear();
  16515. listInput.sendKeys('');
  16516. expect(names.getText()).toContain('');
  16517. expect(valid.getText()).toContain('false');
  16518. expect(error.getCssValue('display')).not.toBe('none'); });
  16519. </file>
  16520. </example>
  16521. */
  16522. var ngListDirective = function() {
  16523. return {
  16524. require: 'ngModel',
  16525. link: function(scope, element, attr, ctrl) {
  16526. var match = /\/(.*)\//.exec(attr.ngList),
  16527. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  16528. var parse = function(viewValue) {
  16529. // If the viewValue is invalid (say required but empty) it will be `undefined`
  16530. if (isUndefined(viewValue)) return;
  16531. var list = [];
  16532. if (viewValue) {
  16533. forEach(viewValue.split(separator), function(value) {
  16534. if (value) list.push(trim(value));
  16535. });
  16536. }
  16537. return list;
  16538. };
  16539. ctrl.$parsers.push(parse);
  16540. ctrl.$formatters.push(function(value) {
  16541. if (isArray(value)) {
  16542. return value.join(', ');
  16543. }
  16544. return undefined;
  16545. });
  16546. // Override the standard $isEmpty because an empty array means the input is empty.
  16547. ctrl.$isEmpty = function(value) {
  16548. return !value || !value.length;
  16549. };
  16550. }
  16551. };
  16552. };
  16553. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  16554. /**
  16555. * @ngdoc directive
  16556. * @name ngValue
  16557. *
  16558. * @description
  16559. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16560. * that when the element is selected, the `ngModel` of that element is set to the
  16561. * bound value.
  16562. *
  16563. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16564. * shown below.
  16565. *
  16566. * @element input
  16567. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16568. * of the `input` element
  16569. *
  16570. * @example
  16571. <example name="ngValue-directive" module="valueExample">
  16572. <file name="index.html">
  16573. <script>
  16574. angular.module('valueExample', [])
  16575. .controller('ExampleController', ['$scope', function($scope) {
  16576. $scope.names = ['pizza', 'unicorns', 'robots'];
  16577. $scope.my = { favorite: 'unicorns' };
  16578. }]);
  16579. </script>
  16580. <form ng-controller="ExampleController">
  16581. <h2>Which is your favorite?</h2>
  16582. <label ng-repeat="name in names" for="{{name}}">
  16583. {{name}}
  16584. <input type="radio"
  16585. ng-model="my.favorite"
  16586. ng-value="name"
  16587. id="{{name}}"
  16588. name="favorite">
  16589. </label>
  16590. <div>You chose {{my.favorite}}</div>
  16591. </form>
  16592. </file>
  16593. <file name="protractor.js" type="protractor">
  16594. var favorite = element(by.binding('my.favorite'));
  16595. it('should initialize to model', function() {
  16596. expect(favorite.getText()).toContain('unicorns');
  16597. });
  16598. it('should bind the values to the inputs', function() {
  16599. element.all(by.model('my.favorite')).get(0).click();
  16600. expect(favorite.getText()).toContain('pizza');
  16601. });
  16602. </file>
  16603. </example>
  16604. */
  16605. var ngValueDirective = function() {
  16606. return {
  16607. priority: 100,
  16608. compile: function(tpl, tplAttr) {
  16609. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16610. return function ngValueConstantLink(scope, elm, attr) {
  16611. attr.$set('value', scope.$eval(attr.ngValue));
  16612. };
  16613. } else {
  16614. return function ngValueLink(scope, elm, attr) {
  16615. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16616. attr.$set('value', value);
  16617. });
  16618. };
  16619. }
  16620. }
  16621. };
  16622. };
  16623. /**
  16624. * @ngdoc directive
  16625. * @name ngBind
  16626. * @restrict AC
  16627. *
  16628. * @description
  16629. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16630. * with the value of a given expression, and to update the text content when the value of that
  16631. * expression changes.
  16632. *
  16633. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16634. * `{{ expression }}` which is similar but less verbose.
  16635. *
  16636. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  16637. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16638. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16639. *
  16640. * An alternative solution to this problem would be using the
  16641. * {@link ng.directive:ngCloak ngCloak} directive.
  16642. *
  16643. *
  16644. * @element ANY
  16645. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16646. *
  16647. * @example
  16648. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16649. <example module="bindExample">
  16650. <file name="index.html">
  16651. <script>
  16652. angular.module('bindExample', [])
  16653. .controller('ExampleController', ['$scope', function($scope) {
  16654. $scope.name = 'Whirled';
  16655. }]);
  16656. </script>
  16657. <div ng-controller="ExampleController">
  16658. Enter name: <input type="text" ng-model="name"><br>
  16659. Hello <span ng-bind="name"></span>!
  16660. </div>
  16661. </file>
  16662. <file name="protractor.js" type="protractor">
  16663. it('should check ng-bind', function() {
  16664. var nameInput = element(by.model('name'));
  16665. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16666. nameInput.clear();
  16667. nameInput.sendKeys('world');
  16668. expect(element(by.binding('name')).getText()).toBe('world');
  16669. });
  16670. </file>
  16671. </example>
  16672. */
  16673. var ngBindDirective = ngDirective({
  16674. compile: function(templateElement) {
  16675. templateElement.addClass('ng-binding');
  16676. return function (scope, element, attr) {
  16677. element.data('$binding', attr.ngBind);
  16678. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16679. // We are purposefully using == here rather than === because we want to
  16680. // catch when value is "null or undefined"
  16681. // jshint -W041
  16682. element.text(value == undefined ? '' : value);
  16683. });
  16684. };
  16685. }
  16686. });
  16687. /**
  16688. * @ngdoc directive
  16689. * @name ngBindTemplate
  16690. *
  16691. * @description
  16692. * The `ngBindTemplate` directive specifies that the element
  16693. * text content should be replaced with the interpolation of the template
  16694. * in the `ngBindTemplate` attribute.
  16695. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16696. * expressions. This directive is needed since some HTML elements
  16697. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16698. *
  16699. * @element ANY
  16700. * @param {string} ngBindTemplate template of form
  16701. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16702. *
  16703. * @example
  16704. * Try it here: enter text in text box and watch the greeting change.
  16705. <example module="bindExample">
  16706. <file name="index.html">
  16707. <script>
  16708. angular.module('bindExample', [])
  16709. .controller('ExampleController', ['$scope', function ($scope) {
  16710. $scope.salutation = 'Hello';
  16711. $scope.name = 'World';
  16712. }]);
  16713. </script>
  16714. <div ng-controller="ExampleController">
  16715. Salutation: <input type="text" ng-model="salutation"><br>
  16716. Name: <input type="text" ng-model="name"><br>
  16717. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16718. </div>
  16719. </file>
  16720. <file name="protractor.js" type="protractor">
  16721. it('should check ng-bind', function() {
  16722. var salutationElem = element(by.binding('salutation'));
  16723. var salutationInput = element(by.model('salutation'));
  16724. var nameInput = element(by.model('name'));
  16725. expect(salutationElem.getText()).toBe('Hello World!');
  16726. salutationInput.clear();
  16727. salutationInput.sendKeys('Greetings');
  16728. nameInput.clear();
  16729. nameInput.sendKeys('user');
  16730. expect(salutationElem.getText()).toBe('Greetings user!');
  16731. });
  16732. </file>
  16733. </example>
  16734. */
  16735. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16736. return function(scope, element, attr) {
  16737. // TODO: move this to scenario runner
  16738. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16739. element.addClass('ng-binding').data('$binding', interpolateFn);
  16740. attr.$observe('ngBindTemplate', function(value) {
  16741. element.text(value);
  16742. });
  16743. };
  16744. }];
  16745. /**
  16746. * @ngdoc directive
  16747. * @name ngBindHtml
  16748. *
  16749. * @description
  16750. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16751. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16752. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16753. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16754. * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
  16755. * include "angular-sanitize.js" in your application.
  16756. *
  16757. * You may also bypass sanitization for values you know are safe. To do so, bind to
  16758. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16759. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16760. *
  16761. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16762. * will have an exception (instead of an exploit.)
  16763. *
  16764. * @element ANY
  16765. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16766. *
  16767. * @example
  16768. <example module="bindHtmlExample" deps="angular-sanitize.js">
  16769. <file name="index.html">
  16770. <div ng-controller="ExampleController">
  16771. <p ng-bind-html="myHTML"></p>
  16772. </div>
  16773. </file>
  16774. <file name="script.js">
  16775. angular.module('bindHtmlExample', ['ngSanitize'])
  16776. .controller('ExampleController', ['$scope', function($scope) {
  16777. $scope.myHTML =
  16778. 'I am an <code>HTML</code>string with ' +
  16779. '<a href="#">links!</a> and other <em>stuff</em>';
  16780. }]);
  16781. </file>
  16782. <file name="protractor.js" type="protractor">
  16783. it('should check ng-bind-html', function() {
  16784. expect(element(by.binding('myHTML')).getText()).toBe(
  16785. 'I am an HTMLstring with links! and other stuff');
  16786. });
  16787. </file>
  16788. </example>
  16789. */
  16790. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16791. return {
  16792. compile: function (tElement) {
  16793. tElement.addClass('ng-binding');
  16794. return function (scope, element, attr) {
  16795. element.data('$binding', attr.ngBindHtml);
  16796. var parsed = $parse(attr.ngBindHtml);
  16797. function getStringValue() {
  16798. return (parsed(scope) || '').toString();
  16799. }
  16800. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16801. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16802. });
  16803. };
  16804. }
  16805. };
  16806. }];
  16807. function classDirective(name, selector) {
  16808. name = 'ngClass' + name;
  16809. return ['$animate', function($animate) {
  16810. return {
  16811. restrict: 'AC',
  16812. link: function(scope, element, attr) {
  16813. var oldVal;
  16814. scope.$watch(attr[name], ngClassWatchAction, true);
  16815. attr.$observe('class', function(value) {
  16816. ngClassWatchAction(scope.$eval(attr[name]));
  16817. });
  16818. if (name !== 'ngClass') {
  16819. scope.$watch('$index', function($index, old$index) {
  16820. // jshint bitwise: false
  16821. var mod = $index & 1;
  16822. if (mod !== (old$index & 1)) {
  16823. var classes = arrayClasses(scope.$eval(attr[name]));
  16824. mod === selector ?
  16825. addClasses(classes) :
  16826. removeClasses(classes);
  16827. }
  16828. });
  16829. }
  16830. function addClasses(classes) {
  16831. var newClasses = digestClassCounts(classes, 1);
  16832. attr.$addClass(newClasses);
  16833. }
  16834. function removeClasses(classes) {
  16835. var newClasses = digestClassCounts(classes, -1);
  16836. attr.$removeClass(newClasses);
  16837. }
  16838. function digestClassCounts (classes, count) {
  16839. var classCounts = element.data('$classCounts') || {};
  16840. var classesToUpdate = [];
  16841. forEach(classes, function (className) {
  16842. if (count > 0 || classCounts[className]) {
  16843. classCounts[className] = (classCounts[className] || 0) + count;
  16844. if (classCounts[className] === +(count > 0)) {
  16845. classesToUpdate.push(className);
  16846. }
  16847. }
  16848. });
  16849. element.data('$classCounts', classCounts);
  16850. return classesToUpdate.join(' ');
  16851. }
  16852. function updateClasses (oldClasses, newClasses) {
  16853. var toAdd = arrayDifference(newClasses, oldClasses);
  16854. var toRemove = arrayDifference(oldClasses, newClasses);
  16855. toRemove = digestClassCounts(toRemove, -1);
  16856. toAdd = digestClassCounts(toAdd, 1);
  16857. if (toAdd.length === 0) {
  16858. $animate.removeClass(element, toRemove);
  16859. } else if (toRemove.length === 0) {
  16860. $animate.addClass(element, toAdd);
  16861. } else {
  16862. $animate.setClass(element, toAdd, toRemove);
  16863. }
  16864. }
  16865. function ngClassWatchAction(newVal) {
  16866. if (selector === true || scope.$index % 2 === selector) {
  16867. var newClasses = arrayClasses(newVal || []);
  16868. if (!oldVal) {
  16869. addClasses(newClasses);
  16870. } else if (!equals(newVal,oldVal)) {
  16871. var oldClasses = arrayClasses(oldVal);
  16872. updateClasses(oldClasses, newClasses);
  16873. }
  16874. }
  16875. oldVal = shallowCopy(newVal);
  16876. }
  16877. }
  16878. };
  16879. function arrayDifference(tokens1, tokens2) {
  16880. var values = [];
  16881. outer:
  16882. for(var i = 0; i < tokens1.length; i++) {
  16883. var token = tokens1[i];
  16884. for(var j = 0; j < tokens2.length; j++) {
  16885. if(token == tokens2[j]) continue outer;
  16886. }
  16887. values.push(token);
  16888. }
  16889. return values;
  16890. }
  16891. function arrayClasses (classVal) {
  16892. if (isArray(classVal)) {
  16893. return classVal;
  16894. } else if (isString(classVal)) {
  16895. return classVal.split(' ');
  16896. } else if (isObject(classVal)) {
  16897. var classes = [], i = 0;
  16898. forEach(classVal, function(v, k) {
  16899. if (v) {
  16900. classes = classes.concat(k.split(' '));
  16901. }
  16902. });
  16903. return classes;
  16904. }
  16905. return classVal;
  16906. }
  16907. }];
  16908. }
  16909. /**
  16910. * @ngdoc directive
  16911. * @name ngClass
  16912. * @restrict AC
  16913. *
  16914. * @description
  16915. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16916. * an expression that represents all classes to be added.
  16917. *
  16918. * The directive operates in three different ways, depending on which of three types the expression
  16919. * evaluates to:
  16920. *
  16921. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16922. * names.
  16923. *
  16924. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16925. * one or more space-delimited class names.
  16926. *
  16927. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16928. * object with a truthy value the corresponding key is used as a class name.
  16929. *
  16930. * The directive won't add duplicate classes if a particular class was already set.
  16931. *
  16932. * When the expression changes, the previously added classes are removed and only then the
  16933. * new classes are added.
  16934. *
  16935. * @animations
  16936. * add - happens just before the class is applied to the element
  16937. * remove - happens just before the class is removed from the element
  16938. *
  16939. * @element ANY
  16940. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16941. * of the evaluation can be a string representing space delimited class
  16942. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16943. * names of the properties whose values are truthy will be added as css classes to the
  16944. * element.
  16945. *
  16946. * @example Example that demonstrates basic bindings via ngClass directive.
  16947. <example>
  16948. <file name="index.html">
  16949. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16950. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16951. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16952. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16953. <hr>
  16954. <p ng-class="style">Using String Syntax</p>
  16955. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16956. <hr>
  16957. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16958. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16959. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16960. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16961. </file>
  16962. <file name="style.css">
  16963. .strike {
  16964. text-decoration: line-through;
  16965. }
  16966. .bold {
  16967. font-weight: bold;
  16968. }
  16969. .red {
  16970. color: red;
  16971. }
  16972. </file>
  16973. <file name="protractor.js" type="protractor">
  16974. var ps = element.all(by.css('p'));
  16975. it('should let you toggle the class', function() {
  16976. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16977. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16978. element(by.model('important')).click();
  16979. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16980. element(by.model('error')).click();
  16981. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16982. });
  16983. it('should let you toggle string example', function() {
  16984. expect(ps.get(1).getAttribute('class')).toBe('');
  16985. element(by.model('style')).clear();
  16986. element(by.model('style')).sendKeys('red');
  16987. expect(ps.get(1).getAttribute('class')).toBe('red');
  16988. });
  16989. it('array example should have 3 classes', function() {
  16990. expect(ps.last().getAttribute('class')).toBe('');
  16991. element(by.model('style1')).sendKeys('bold');
  16992. element(by.model('style2')).sendKeys('strike');
  16993. element(by.model('style3')).sendKeys('red');
  16994. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16995. });
  16996. </file>
  16997. </example>
  16998. ## Animations
  16999. The example below demonstrates how to perform animations using ngClass.
  17000. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17001. <file name="index.html">
  17002. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  17003. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  17004. <br>
  17005. <span class="base-class" ng-class="myVar">Sample Text</span>
  17006. </file>
  17007. <file name="style.css">
  17008. .base-class {
  17009. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17010. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17011. }
  17012. .base-class.my-class {
  17013. color: red;
  17014. font-size:3em;
  17015. }
  17016. </file>
  17017. <file name="protractor.js" type="protractor">
  17018. it('should check ng-class', function() {
  17019. expect(element(by.css('.base-class')).getAttribute('class')).not.
  17020. toMatch(/my-class/);
  17021. element(by.id('setbtn')).click();
  17022. expect(element(by.css('.base-class')).getAttribute('class')).
  17023. toMatch(/my-class/);
  17024. element(by.id('clearbtn')).click();
  17025. expect(element(by.css('.base-class')).getAttribute('class')).not.
  17026. toMatch(/my-class/);
  17027. });
  17028. </file>
  17029. </example>
  17030. ## ngClass and pre-existing CSS3 Transitions/Animations
  17031. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  17032. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  17033. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  17034. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  17035. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  17036. */
  17037. var ngClassDirective = classDirective('', true);
  17038. /**
  17039. * @ngdoc directive
  17040. * @name ngClassOdd
  17041. * @restrict AC
  17042. *
  17043. * @description
  17044. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  17045. * {@link ng.directive:ngClass ngClass}, except they work in
  17046. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  17047. *
  17048. * This directive can be applied only within the scope of an
  17049. * {@link ng.directive:ngRepeat ngRepeat}.
  17050. *
  17051. * @element ANY
  17052. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  17053. * of the evaluation can be a string representing space delimited class names or an array.
  17054. *
  17055. * @example
  17056. <example>
  17057. <file name="index.html">
  17058. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17059. <li ng-repeat="name in names">
  17060. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17061. {{name}}
  17062. </span>
  17063. </li>
  17064. </ol>
  17065. </file>
  17066. <file name="style.css">
  17067. .odd {
  17068. color: red;
  17069. }
  17070. .even {
  17071. color: blue;
  17072. }
  17073. </file>
  17074. <file name="protractor.js" type="protractor">
  17075. it('should check ng-class-odd and ng-class-even', function() {
  17076. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17077. toMatch(/odd/);
  17078. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17079. toMatch(/even/);
  17080. });
  17081. </file>
  17082. </example>
  17083. */
  17084. var ngClassOddDirective = classDirective('Odd', 0);
  17085. /**
  17086. * @ngdoc directive
  17087. * @name ngClassEven
  17088. * @restrict AC
  17089. *
  17090. * @description
  17091. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  17092. * {@link ng.directive:ngClass ngClass}, except they work in
  17093. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  17094. *
  17095. * This directive can be applied only within the scope of an
  17096. * {@link ng.directive:ngRepeat ngRepeat}.
  17097. *
  17098. * @element ANY
  17099. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  17100. * result of the evaluation can be a string representing space delimited class names or an array.
  17101. *
  17102. * @example
  17103. <example>
  17104. <file name="index.html">
  17105. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17106. <li ng-repeat="name in names">
  17107. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17108. {{name}} &nbsp; &nbsp; &nbsp;
  17109. </span>
  17110. </li>
  17111. </ol>
  17112. </file>
  17113. <file name="style.css">
  17114. .odd {
  17115. color: red;
  17116. }
  17117. .even {
  17118. color: blue;
  17119. }
  17120. </file>
  17121. <file name="protractor.js" type="protractor">
  17122. it('should check ng-class-odd and ng-class-even', function() {
  17123. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17124. toMatch(/odd/);
  17125. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17126. toMatch(/even/);
  17127. });
  17128. </file>
  17129. </example>
  17130. */
  17131. var ngClassEvenDirective = classDirective('Even', 1);
  17132. /**
  17133. * @ngdoc directive
  17134. * @name ngCloak
  17135. * @restrict AC
  17136. *
  17137. * @description
  17138. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  17139. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  17140. * directive to avoid the undesirable flicker effect caused by the html template display.
  17141. *
  17142. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  17143. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  17144. * of the browser view.
  17145. *
  17146. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  17147. * `angular.min.js`.
  17148. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17149. *
  17150. * ```css
  17151. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  17152. * display: none !important;
  17153. * }
  17154. * ```
  17155. *
  17156. * When this css rule is loaded by the browser, all html elements (including their children) that
  17157. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  17158. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  17159. * the compiled element visible.
  17160. *
  17161. * For the best result, the `angular.js` script must be loaded in the head section of the html
  17162. * document; alternatively, the css rule above must be included in the external stylesheet of the
  17163. * application.
  17164. *
  17165. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  17166. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  17167. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  17168. *
  17169. * @element ANY
  17170. *
  17171. * @example
  17172. <example>
  17173. <file name="index.html">
  17174. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  17175. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  17176. </file>
  17177. <file name="protractor.js" type="protractor">
  17178. it('should remove the template directive and css class', function() {
  17179. expect($('#template1').getAttribute('ng-cloak')).
  17180. toBeNull();
  17181. expect($('#template2').getAttribute('ng-cloak')).
  17182. toBeNull();
  17183. });
  17184. </file>
  17185. </example>
  17186. *
  17187. */
  17188. var ngCloakDirective = ngDirective({
  17189. compile: function(element, attr) {
  17190. attr.$set('ngCloak', undefined);
  17191. element.removeClass('ng-cloak');
  17192. }
  17193. });
  17194. /**
  17195. * @ngdoc directive
  17196. * @name ngController
  17197. *
  17198. * @description
  17199. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  17200. * supports the principles behind the Model-View-Controller design pattern.
  17201. *
  17202. * MVC components in angular:
  17203. *
  17204. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  17205. * are accessed through bindings.
  17206. * * View — The template (HTML with data bindings) that is rendered into the View.
  17207. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  17208. * logic behind the application to decorate the scope with functions and values
  17209. *
  17210. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  17211. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  17212. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  17213. * and executed twice.
  17214. *
  17215. * @element ANY
  17216. * @scope
  17217. * @priority 500
  17218. * @param {expression} ngController Name of a globally accessible constructor function or an
  17219. * {@link guide/expression expression} that on the current scope evaluates to a
  17220. * constructor function. The controller instance can be published into a scope property
  17221. * by specifying `as propertyName`.
  17222. *
  17223. * @example
  17224. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  17225. * greeting are methods declared on the controller (see source tab). These methods can
  17226. * easily be called from the angular markup. Any changes to the data are automatically reflected
  17227. * in the View without the need for a manual update.
  17228. *
  17229. * Two different declaration styles are included below:
  17230. *
  17231. * * one binds methods and properties directly onto the controller using `this`:
  17232. * `ng-controller="SettingsController1 as settings"`
  17233. * * one injects `$scope` into the controller:
  17234. * `ng-controller="SettingsController2"`
  17235. *
  17236. * The second option is more common in the Angular community, and is generally used in boilerplates
  17237. * and in this guide. However, there are advantages to binding properties directly to the controller
  17238. * and avoiding scope.
  17239. *
  17240. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  17241. * multiple controllers apply to an element.
  17242. * * If you are writing your controllers as classes you have easier access to the properties and
  17243. * methods, which will appear on the scope, from inside the controller code.
  17244. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  17245. * inheritance masking primitives.
  17246. *
  17247. * This example demonstrates the `controller as` syntax.
  17248. *
  17249. * <example name="ngControllerAs" module="controllerAsExample">
  17250. * <file name="index.html">
  17251. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  17252. * Name: <input type="text" ng-model="settings.name"/>
  17253. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  17254. * Contact:
  17255. * <ul>
  17256. * <li ng-repeat="contact in settings.contacts">
  17257. * <select ng-model="contact.type">
  17258. * <option>phone</option>
  17259. * <option>email</option>
  17260. * </select>
  17261. * <input type="text" ng-model="contact.value"/>
  17262. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  17263. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  17264. * </li>
  17265. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  17266. * </ul>
  17267. * </div>
  17268. * </file>
  17269. * <file name="app.js">
  17270. * angular.module('controllerAsExample', [])
  17271. * .controller('SettingsController1', SettingsController1);
  17272. *
  17273. * function SettingsController1() {
  17274. * this.name = "John Smith";
  17275. * this.contacts = [
  17276. * {type: 'phone', value: '408 555 1212'},
  17277. * {type: 'email', value: 'john.smith@example.org'} ];
  17278. * }
  17279. *
  17280. * SettingsController1.prototype.greet = function() {
  17281. * alert(this.name);
  17282. * };
  17283. *
  17284. * SettingsController1.prototype.addContact = function() {
  17285. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  17286. * };
  17287. *
  17288. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  17289. * var index = this.contacts.indexOf(contactToRemove);
  17290. * this.contacts.splice(index, 1);
  17291. * };
  17292. *
  17293. * SettingsController1.prototype.clearContact = function(contact) {
  17294. * contact.type = 'phone';
  17295. * contact.value = '';
  17296. * };
  17297. * </file>
  17298. * <file name="protractor.js" type="protractor">
  17299. * it('should check controller as', function() {
  17300. * var container = element(by.id('ctrl-as-exmpl'));
  17301. * expect(container.element(by.model('settings.name'))
  17302. * .getAttribute('value')).toBe('John Smith');
  17303. *
  17304. * var firstRepeat =
  17305. * container.element(by.repeater('contact in settings.contacts').row(0));
  17306. * var secondRepeat =
  17307. * container.element(by.repeater('contact in settings.contacts').row(1));
  17308. *
  17309. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17310. * .toBe('408 555 1212');
  17311. *
  17312. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17313. * .toBe('john.smith@example.org');
  17314. *
  17315. * firstRepeat.element(by.linkText('clear')).click();
  17316. *
  17317. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17318. * .toBe('');
  17319. *
  17320. * container.element(by.linkText('add')).click();
  17321. *
  17322. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  17323. * .element(by.model('contact.value'))
  17324. * .getAttribute('value'))
  17325. * .toBe('yourname@example.org');
  17326. * });
  17327. * </file>
  17328. * </example>
  17329. *
  17330. * This example demonstrates the "attach to `$scope`" style of controller.
  17331. *
  17332. * <example name="ngController" module="controllerExample">
  17333. * <file name="index.html">
  17334. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  17335. * Name: <input type="text" ng-model="name"/>
  17336. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  17337. * Contact:
  17338. * <ul>
  17339. * <li ng-repeat="contact in contacts">
  17340. * <select ng-model="contact.type">
  17341. * <option>phone</option>
  17342. * <option>email</option>
  17343. * </select>
  17344. * <input type="text" ng-model="contact.value"/>
  17345. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  17346. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  17347. * </li>
  17348. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  17349. * </ul>
  17350. * </div>
  17351. * </file>
  17352. * <file name="app.js">
  17353. * angular.module('controllerExample', [])
  17354. * .controller('SettingsController2', ['$scope', SettingsController2]);
  17355. *
  17356. * function SettingsController2($scope) {
  17357. * $scope.name = "John Smith";
  17358. * $scope.contacts = [
  17359. * {type:'phone', value:'408 555 1212'},
  17360. * {type:'email', value:'john.smith@example.org'} ];
  17361. *
  17362. * $scope.greet = function() {
  17363. * alert($scope.name);
  17364. * };
  17365. *
  17366. * $scope.addContact = function() {
  17367. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  17368. * };
  17369. *
  17370. * $scope.removeContact = function(contactToRemove) {
  17371. * var index = $scope.contacts.indexOf(contactToRemove);
  17372. * $scope.contacts.splice(index, 1);
  17373. * };
  17374. *
  17375. * $scope.clearContact = function(contact) {
  17376. * contact.type = 'phone';
  17377. * contact.value = '';
  17378. * };
  17379. * }
  17380. * </file>
  17381. * <file name="protractor.js" type="protractor">
  17382. * it('should check controller', function() {
  17383. * var container = element(by.id('ctrl-exmpl'));
  17384. *
  17385. * expect(container.element(by.model('name'))
  17386. * .getAttribute('value')).toBe('John Smith');
  17387. *
  17388. * var firstRepeat =
  17389. * container.element(by.repeater('contact in contacts').row(0));
  17390. * var secondRepeat =
  17391. * container.element(by.repeater('contact in contacts').row(1));
  17392. *
  17393. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17394. * .toBe('408 555 1212');
  17395. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17396. * .toBe('john.smith@example.org');
  17397. *
  17398. * firstRepeat.element(by.linkText('clear')).click();
  17399. *
  17400. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17401. * .toBe('');
  17402. *
  17403. * container.element(by.linkText('add')).click();
  17404. *
  17405. * expect(container.element(by.repeater('contact in contacts').row(2))
  17406. * .element(by.model('contact.value'))
  17407. * .getAttribute('value'))
  17408. * .toBe('yourname@example.org');
  17409. * });
  17410. * </file>
  17411. *</example>
  17412. */
  17413. var ngControllerDirective = [function() {
  17414. return {
  17415. scope: true,
  17416. controller: '@',
  17417. priority: 500
  17418. };
  17419. }];
  17420. /**
  17421. * @ngdoc directive
  17422. * @name ngCsp
  17423. *
  17424. * @element html
  17425. * @description
  17426. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  17427. *
  17428. * This is necessary when developing things like Google Chrome Extensions.
  17429. *
  17430. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  17431. * For Angular to be CSP compatible there are only two things that we need to do differently:
  17432. *
  17433. * - don't use `Function` constructor to generate optimized value getters
  17434. * - don't inject custom stylesheet into the document
  17435. *
  17436. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  17437. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  17438. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  17439. * be raised.
  17440. *
  17441. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  17442. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  17443. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  17444. *
  17445. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  17446. * autodetection however triggers a CSP error to be logged in the console:
  17447. *
  17448. * ```
  17449. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  17450. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  17451. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  17452. * ```
  17453. *
  17454. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  17455. * directive on the root element of the application or on the `angular.js` script tag, whichever
  17456. * appears first in the html document.
  17457. *
  17458. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  17459. *
  17460. * @example
  17461. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  17462. ```html
  17463. <!doctype html>
  17464. <html ng-app ng-csp>
  17465. ...
  17466. ...
  17467. </html>
  17468. ```
  17469. */
  17470. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  17471. // bootstrap the system (before $parse is instantiated), for this reason we just have
  17472. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  17473. /**
  17474. * @ngdoc directive
  17475. * @name ngClick
  17476. *
  17477. * @description
  17478. * The ngClick directive allows you to specify custom behavior when
  17479. * an element is clicked.
  17480. *
  17481. * @element ANY
  17482. * @priority 0
  17483. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  17484. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  17485. *
  17486. * @example
  17487. <example>
  17488. <file name="index.html">
  17489. <button ng-click="count = count + 1" ng-init="count=0">
  17490. Increment
  17491. </button>
  17492. <span>
  17493. count: {{count}}
  17494. <span>
  17495. </file>
  17496. <file name="protractor.js" type="protractor">
  17497. it('should check ng-click', function() {
  17498. expect(element(by.binding('count')).getText()).toMatch('0');
  17499. element(by.css('button')).click();
  17500. expect(element(by.binding('count')).getText()).toMatch('1');
  17501. });
  17502. </file>
  17503. </example>
  17504. */
  17505. /*
  17506. * A collection of directives that allows creation of custom event handlers that are defined as
  17507. * angular expressions and are compiled and executed within the current scope.
  17508. */
  17509. var ngEventDirectives = {};
  17510. // For events that might fire synchronously during DOM manipulation
  17511. // we need to execute their event handlers asynchronously using $evalAsync,
  17512. // so that they are not executed in an inconsistent state.
  17513. var forceAsyncEvents = {
  17514. 'blur': true,
  17515. 'focus': true
  17516. };
  17517. forEach(
  17518. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  17519. function(eventName) {
  17520. var directiveName = directiveNormalize('ng-' + eventName);
  17521. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  17522. return {
  17523. compile: function($element, attr) {
  17524. // We expose the powerful $event object on the scope that provides access to the Window,
  17525. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  17526. // checks at the cost of speed since event handler expressions are not executed as
  17527. // frequently as regular change detection.
  17528. var fn = $parse(attr[directiveName], /* expensiveChecks */ true);
  17529. return function ngEventHandler(scope, element) {
  17530. element.on(eventName, function(event) {
  17531. var callback = function() {
  17532. fn(scope, {$event:event});
  17533. };
  17534. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  17535. scope.$evalAsync(callback);
  17536. } else {
  17537. scope.$apply(callback);
  17538. }
  17539. });
  17540. };
  17541. }
  17542. };
  17543. }];
  17544. }
  17545. );
  17546. /**
  17547. * @ngdoc directive
  17548. * @name ngDblclick
  17549. *
  17550. * @description
  17551. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  17552. *
  17553. * @element ANY
  17554. * @priority 0
  17555. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  17556. * a dblclick. (The Event object is available as `$event`)
  17557. *
  17558. * @example
  17559. <example>
  17560. <file name="index.html">
  17561. <button ng-dblclick="count = count + 1" ng-init="count=0">
  17562. Increment (on double click)
  17563. </button>
  17564. count: {{count}}
  17565. </file>
  17566. </example>
  17567. */
  17568. /**
  17569. * @ngdoc directive
  17570. * @name ngMousedown
  17571. *
  17572. * @description
  17573. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  17574. *
  17575. * @element ANY
  17576. * @priority 0
  17577. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  17578. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  17579. *
  17580. * @example
  17581. <example>
  17582. <file name="index.html">
  17583. <button ng-mousedown="count = count + 1" ng-init="count=0">
  17584. Increment (on mouse down)
  17585. </button>
  17586. count: {{count}}
  17587. </file>
  17588. </example>
  17589. */
  17590. /**
  17591. * @ngdoc directive
  17592. * @name ngMouseup
  17593. *
  17594. * @description
  17595. * Specify custom behavior on mouseup event.
  17596. *
  17597. * @element ANY
  17598. * @priority 0
  17599. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  17600. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  17601. *
  17602. * @example
  17603. <example>
  17604. <file name="index.html">
  17605. <button ng-mouseup="count = count + 1" ng-init="count=0">
  17606. Increment (on mouse up)
  17607. </button>
  17608. count: {{count}}
  17609. </file>
  17610. </example>
  17611. */
  17612. /**
  17613. * @ngdoc directive
  17614. * @name ngMouseover
  17615. *
  17616. * @description
  17617. * Specify custom behavior on mouseover event.
  17618. *
  17619. * @element ANY
  17620. * @priority 0
  17621. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  17622. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  17623. *
  17624. * @example
  17625. <example>
  17626. <file name="index.html">
  17627. <button ng-mouseover="count = count + 1" ng-init="count=0">
  17628. Increment (when mouse is over)
  17629. </button>
  17630. count: {{count}}
  17631. </file>
  17632. </example>
  17633. */
  17634. /**
  17635. * @ngdoc directive
  17636. * @name ngMouseenter
  17637. *
  17638. * @description
  17639. * Specify custom behavior on mouseenter event.
  17640. *
  17641. * @element ANY
  17642. * @priority 0
  17643. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  17644. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  17645. *
  17646. * @example
  17647. <example>
  17648. <file name="index.html">
  17649. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  17650. Increment (when mouse enters)
  17651. </button>
  17652. count: {{count}}
  17653. </file>
  17654. </example>
  17655. */
  17656. /**
  17657. * @ngdoc directive
  17658. * @name ngMouseleave
  17659. *
  17660. * @description
  17661. * Specify custom behavior on mouseleave event.
  17662. *
  17663. * @element ANY
  17664. * @priority 0
  17665. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17666. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17667. *
  17668. * @example
  17669. <example>
  17670. <file name="index.html">
  17671. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17672. Increment (when mouse leaves)
  17673. </button>
  17674. count: {{count}}
  17675. </file>
  17676. </example>
  17677. */
  17678. /**
  17679. * @ngdoc directive
  17680. * @name ngMousemove
  17681. *
  17682. * @description
  17683. * Specify custom behavior on mousemove event.
  17684. *
  17685. * @element ANY
  17686. * @priority 0
  17687. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17688. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17689. *
  17690. * @example
  17691. <example>
  17692. <file name="index.html">
  17693. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17694. Increment (when mouse moves)
  17695. </button>
  17696. count: {{count}}
  17697. </file>
  17698. </example>
  17699. */
  17700. /**
  17701. * @ngdoc directive
  17702. * @name ngKeydown
  17703. *
  17704. * @description
  17705. * Specify custom behavior on keydown event.
  17706. *
  17707. * @element ANY
  17708. * @priority 0
  17709. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17710. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17711. *
  17712. * @example
  17713. <example>
  17714. <file name="index.html">
  17715. <input ng-keydown="count = count + 1" ng-init="count=0">
  17716. key down count: {{count}}
  17717. </file>
  17718. </example>
  17719. */
  17720. /**
  17721. * @ngdoc directive
  17722. * @name ngKeyup
  17723. *
  17724. * @description
  17725. * Specify custom behavior on keyup event.
  17726. *
  17727. * @element ANY
  17728. * @priority 0
  17729. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17730. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17731. *
  17732. * @example
  17733. <example>
  17734. <file name="index.html">
  17735. <p>Typing in the input box below updates the key count</p>
  17736. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  17737. <p>Typing in the input box below updates the keycode</p>
  17738. <input ng-keyup="event=$event">
  17739. <p>event keyCode: {{ event.keyCode }}</p>
  17740. <p>event altKey: {{ event.altKey }}</p>
  17741. </file>
  17742. </example>
  17743. */
  17744. /**
  17745. * @ngdoc directive
  17746. * @name ngKeypress
  17747. *
  17748. * @description
  17749. * Specify custom behavior on keypress event.
  17750. *
  17751. * @element ANY
  17752. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17753. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17754. * and can be interrogated for keyCode, altKey, etc.)
  17755. *
  17756. * @example
  17757. <example>
  17758. <file name="index.html">
  17759. <input ng-keypress="count = count + 1" ng-init="count=0">
  17760. key press count: {{count}}
  17761. </file>
  17762. </example>
  17763. */
  17764. /**
  17765. * @ngdoc directive
  17766. * @name ngSubmit
  17767. *
  17768. * @description
  17769. * Enables binding angular expressions to onsubmit events.
  17770. *
  17771. * Additionally it prevents the default action (which for form means sending the request to the
  17772. * server and reloading the current page), but only if the form does not contain `action`,
  17773. * `data-action`, or `x-action` attributes.
  17774. *
  17775. * <div class="alert alert-warning">
  17776. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  17777. * `ngSubmit` handlers together. See the
  17778. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  17779. * for a detailed discussion of when `ngSubmit` may be triggered.
  17780. * </div>
  17781. *
  17782. * @element form
  17783. * @priority 0
  17784. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17785. * ({@link guide/expression#-event- Event object is available as `$event`})
  17786. *
  17787. * @example
  17788. <example module="submitExample">
  17789. <file name="index.html">
  17790. <script>
  17791. angular.module('submitExample', [])
  17792. .controller('ExampleController', ['$scope', function($scope) {
  17793. $scope.list = [];
  17794. $scope.text = 'hello';
  17795. $scope.submit = function() {
  17796. if ($scope.text) {
  17797. $scope.list.push(this.text);
  17798. $scope.text = '';
  17799. }
  17800. };
  17801. }]);
  17802. </script>
  17803. <form ng-submit="submit()" ng-controller="ExampleController">
  17804. Enter text and hit enter:
  17805. <input type="text" ng-model="text" name="text" />
  17806. <input type="submit" id="submit" value="Submit" />
  17807. <pre>list={{list}}</pre>
  17808. </form>
  17809. </file>
  17810. <file name="protractor.js" type="protractor">
  17811. it('should check ng-submit', function() {
  17812. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17813. element(by.css('#submit')).click();
  17814. expect(element(by.binding('list')).getText()).toContain('hello');
  17815. expect(element(by.model('text')).getAttribute('value')).toBe('');
  17816. });
  17817. it('should ignore empty strings', function() {
  17818. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17819. element(by.css('#submit')).click();
  17820. element(by.css('#submit')).click();
  17821. expect(element(by.binding('list')).getText()).toContain('hello');
  17822. });
  17823. </file>
  17824. </example>
  17825. */
  17826. /**
  17827. * @ngdoc directive
  17828. * @name ngFocus
  17829. *
  17830. * @description
  17831. * Specify custom behavior on focus event.
  17832. *
  17833. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  17834. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17835. * during an `$apply` to ensure a consistent state.
  17836. *
  17837. * @element window, input, select, textarea, a
  17838. * @priority 0
  17839. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17840. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17841. *
  17842. * @example
  17843. * See {@link ng.directive:ngClick ngClick}
  17844. */
  17845. /**
  17846. * @ngdoc directive
  17847. * @name ngBlur
  17848. *
  17849. * @description
  17850. * Specify custom behavior on blur event.
  17851. *
  17852. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  17853. * an element has lost focus.
  17854. *
  17855. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  17856. * (e.g. removing a focussed input),
  17857. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17858. * during an `$apply` to ensure a consistent state.
  17859. *
  17860. * @element window, input, select, textarea, a
  17861. * @priority 0
  17862. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17863. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17864. *
  17865. * @example
  17866. * See {@link ng.directive:ngClick ngClick}
  17867. */
  17868. /**
  17869. * @ngdoc directive
  17870. * @name ngCopy
  17871. *
  17872. * @description
  17873. * Specify custom behavior on copy event.
  17874. *
  17875. * @element window, input, select, textarea, a
  17876. * @priority 0
  17877. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17878. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17879. *
  17880. * @example
  17881. <example>
  17882. <file name="index.html">
  17883. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17884. copied: {{copied}}
  17885. </file>
  17886. </example>
  17887. */
  17888. /**
  17889. * @ngdoc directive
  17890. * @name ngCut
  17891. *
  17892. * @description
  17893. * Specify custom behavior on cut event.
  17894. *
  17895. * @element window, input, select, textarea, a
  17896. * @priority 0
  17897. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17898. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17899. *
  17900. * @example
  17901. <example>
  17902. <file name="index.html">
  17903. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17904. cut: {{cut}}
  17905. </file>
  17906. </example>
  17907. */
  17908. /**
  17909. * @ngdoc directive
  17910. * @name ngPaste
  17911. *
  17912. * @description
  17913. * Specify custom behavior on paste event.
  17914. *
  17915. * @element window, input, select, textarea, a
  17916. * @priority 0
  17917. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17918. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17919. *
  17920. * @example
  17921. <example>
  17922. <file name="index.html">
  17923. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17924. pasted: {{paste}}
  17925. </file>
  17926. </example>
  17927. */
  17928. /**
  17929. * @ngdoc directive
  17930. * @name ngIf
  17931. * @restrict A
  17932. *
  17933. * @description
  17934. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17935. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17936. * value then the element is removed from the DOM, otherwise a clone of the
  17937. * element is reinserted into the DOM.
  17938. *
  17939. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17940. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17941. * case when this difference is significant is when using css selectors that rely on an element's
  17942. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17943. *
  17944. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17945. * is created when the element is restored. The scope created within `ngIf` inherits from
  17946. * its parent scope using
  17947. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  17948. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17949. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17950. * variable within the child scope will override (hide) the value in the parent scope.
  17951. *
  17952. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17953. * is if an element's class attribute is directly modified after it's compiled, using something like
  17954. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17955. * the added class will be lost because the original compiled state is used to regenerate the element.
  17956. *
  17957. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17958. * and `leave` effects.
  17959. *
  17960. * @animations
  17961. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  17962. * leave - happens just before the `ngIf` contents are removed from the DOM
  17963. *
  17964. * @element ANY
  17965. * @scope
  17966. * @priority 600
  17967. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17968. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17969. * element is added to the DOM tree.
  17970. *
  17971. * @example
  17972. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17973. <file name="index.html">
  17974. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17975. Show when checked:
  17976. <span ng-if="checked" class="animate-if">
  17977. I'm removed when the checkbox is unchecked.
  17978. </span>
  17979. </file>
  17980. <file name="animations.css">
  17981. .animate-if {
  17982. background:white;
  17983. border:1px solid black;
  17984. padding:10px;
  17985. }
  17986. .animate-if.ng-enter, .animate-if.ng-leave {
  17987. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17988. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17989. }
  17990. .animate-if.ng-enter,
  17991. .animate-if.ng-leave.ng-leave-active {
  17992. opacity:0;
  17993. }
  17994. .animate-if.ng-leave,
  17995. .animate-if.ng-enter.ng-enter-active {
  17996. opacity:1;
  17997. }
  17998. </file>
  17999. </example>
  18000. */
  18001. var ngIfDirective = ['$animate', function($animate) {
  18002. return {
  18003. transclude: 'element',
  18004. priority: 600,
  18005. terminal: true,
  18006. restrict: 'A',
  18007. $$tlb: true,
  18008. link: function ($scope, $element, $attr, ctrl, $transclude) {
  18009. var block, childScope, previousElements;
  18010. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  18011. if (toBoolean(value)) {
  18012. if (!childScope) {
  18013. childScope = $scope.$new();
  18014. $transclude(childScope, function (clone) {
  18015. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  18016. // Note: We only need the first/last node of the cloned nodes.
  18017. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18018. // by a directive with templateUrl when its template arrives.
  18019. block = {
  18020. clone: clone
  18021. };
  18022. $animate.enter(clone, $element.parent(), $element);
  18023. });
  18024. }
  18025. } else {
  18026. if(previousElements) {
  18027. previousElements.remove();
  18028. previousElements = null;
  18029. }
  18030. if(childScope) {
  18031. childScope.$destroy();
  18032. childScope = null;
  18033. }
  18034. if(block) {
  18035. previousElements = getBlockElements(block.clone);
  18036. $animate.leave(previousElements, function() {
  18037. previousElements = null;
  18038. });
  18039. block = null;
  18040. }
  18041. }
  18042. });
  18043. }
  18044. };
  18045. }];
  18046. /**
  18047. * @ngdoc directive
  18048. * @name ngInclude
  18049. * @restrict ECA
  18050. *
  18051. * @description
  18052. * Fetches, compiles and includes an external HTML fragment.
  18053. *
  18054. * By default, the template URL is restricted to the same domain and protocol as the
  18055. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  18056. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  18057. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  18058. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  18059. * ng.$sce Strict Contextual Escaping}.
  18060. *
  18061. * In addition, the browser's
  18062. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  18063. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  18064. * policy may further restrict whether the template is successfully loaded.
  18065. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  18066. * access on some browsers.
  18067. *
  18068. * @animations
  18069. * enter - animation is used to bring new content into the browser.
  18070. * leave - animation is used to animate existing content away.
  18071. *
  18072. * The enter and leave animation occur concurrently.
  18073. *
  18074. * @scope
  18075. * @priority 400
  18076. *
  18077. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  18078. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  18079. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  18080. *
  18081. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  18082. * $anchorScroll} to scroll the viewport after the content is loaded.
  18083. *
  18084. * - If the attribute is not set, disable scrolling.
  18085. * - If the attribute is set without value, enable scrolling.
  18086. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  18087. *
  18088. * @example
  18089. <example module="includeExample" deps="angular-animate.js" animations="true">
  18090. <file name="index.html">
  18091. <div ng-controller="ExampleController">
  18092. <select ng-model="template" ng-options="t.name for t in templates">
  18093. <option value="">(blank)</option>
  18094. </select>
  18095. url of the template: <code>{{template.url}}</code>
  18096. <hr/>
  18097. <div class="slide-animate-container">
  18098. <div class="slide-animate" ng-include="template.url"></div>
  18099. </div>
  18100. </div>
  18101. </file>
  18102. <file name="script.js">
  18103. angular.module('includeExample', ['ngAnimate'])
  18104. .controller('ExampleController', ['$scope', function($scope) {
  18105. $scope.templates =
  18106. [ { name: 'template1.html', url: 'template1.html'},
  18107. { name: 'template2.html', url: 'template2.html'} ];
  18108. $scope.template = $scope.templates[0];
  18109. }]);
  18110. </file>
  18111. <file name="template1.html">
  18112. Content of template1.html
  18113. </file>
  18114. <file name="template2.html">
  18115. Content of template2.html
  18116. </file>
  18117. <file name="animations.css">
  18118. .slide-animate-container {
  18119. position:relative;
  18120. background:white;
  18121. border:1px solid black;
  18122. height:40px;
  18123. overflow:hidden;
  18124. }
  18125. .slide-animate {
  18126. padding:10px;
  18127. }
  18128. .slide-animate.ng-enter, .slide-animate.ng-leave {
  18129. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18130. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18131. position:absolute;
  18132. top:0;
  18133. left:0;
  18134. right:0;
  18135. bottom:0;
  18136. display:block;
  18137. padding:10px;
  18138. }
  18139. .slide-animate.ng-enter {
  18140. top:-50px;
  18141. }
  18142. .slide-animate.ng-enter.ng-enter-active {
  18143. top:0;
  18144. }
  18145. .slide-animate.ng-leave {
  18146. top:0;
  18147. }
  18148. .slide-animate.ng-leave.ng-leave-active {
  18149. top:50px;
  18150. }
  18151. </file>
  18152. <file name="protractor.js" type="protractor">
  18153. var templateSelect = element(by.model('template'));
  18154. var includeElem = element(by.css('[ng-include]'));
  18155. it('should load template1.html', function() {
  18156. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  18157. });
  18158. it('should load template2.html', function() {
  18159. if (browser.params.browser == 'firefox') {
  18160. // Firefox can't handle using selects
  18161. // See https://github.com/angular/protractor/issues/480
  18162. return;
  18163. }
  18164. templateSelect.click();
  18165. templateSelect.all(by.css('option')).get(2).click();
  18166. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  18167. });
  18168. it('should change to blank', function() {
  18169. if (browser.params.browser == 'firefox') {
  18170. // Firefox can't handle using selects
  18171. return;
  18172. }
  18173. templateSelect.click();
  18174. templateSelect.all(by.css('option')).get(0).click();
  18175. expect(includeElem.isPresent()).toBe(false);
  18176. });
  18177. </file>
  18178. </example>
  18179. */
  18180. /**
  18181. * @ngdoc event
  18182. * @name ngInclude#$includeContentRequested
  18183. * @eventType emit on the scope ngInclude was declared in
  18184. * @description
  18185. * Emitted every time the ngInclude content is requested.
  18186. */
  18187. /**
  18188. * @ngdoc event
  18189. * @name ngInclude#$includeContentLoaded
  18190. * @eventType emit on the current ngInclude scope
  18191. * @description
  18192. * Emitted every time the ngInclude content is reloaded.
  18193. */
  18194. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  18195. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  18196. return {
  18197. restrict: 'ECA',
  18198. priority: 400,
  18199. terminal: true,
  18200. transclude: 'element',
  18201. controller: angular.noop,
  18202. compile: function(element, attr) {
  18203. var srcExp = attr.ngInclude || attr.src,
  18204. onloadExp = attr.onload || '',
  18205. autoScrollExp = attr.autoscroll;
  18206. return function(scope, $element, $attr, ctrl, $transclude) {
  18207. var changeCounter = 0,
  18208. currentScope,
  18209. previousElement,
  18210. currentElement;
  18211. var cleanupLastIncludeContent = function() {
  18212. if(previousElement) {
  18213. previousElement.remove();
  18214. previousElement = null;
  18215. }
  18216. if(currentScope) {
  18217. currentScope.$destroy();
  18218. currentScope = null;
  18219. }
  18220. if(currentElement) {
  18221. $animate.leave(currentElement, function() {
  18222. previousElement = null;
  18223. });
  18224. previousElement = currentElement;
  18225. currentElement = null;
  18226. }
  18227. };
  18228. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  18229. var afterAnimation = function() {
  18230. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  18231. $anchorScroll();
  18232. }
  18233. };
  18234. var thisChangeId = ++changeCounter;
  18235. if (src) {
  18236. $http.get(src, {cache: $templateCache}).success(function(response) {
  18237. if (thisChangeId !== changeCounter) return;
  18238. var newScope = scope.$new();
  18239. ctrl.template = response;
  18240. // Note: This will also link all children of ng-include that were contained in the original
  18241. // html. If that content contains controllers, ... they could pollute/change the scope.
  18242. // However, using ng-include on an element with additional content does not make sense...
  18243. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  18244. // function is called before linking the content, which would apply child
  18245. // directives to non existing elements.
  18246. var clone = $transclude(newScope, function(clone) {
  18247. cleanupLastIncludeContent();
  18248. $animate.enter(clone, null, $element, afterAnimation);
  18249. });
  18250. currentScope = newScope;
  18251. currentElement = clone;
  18252. currentScope.$emit('$includeContentLoaded');
  18253. scope.$eval(onloadExp);
  18254. }).error(function() {
  18255. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  18256. });
  18257. scope.$emit('$includeContentRequested');
  18258. } else {
  18259. cleanupLastIncludeContent();
  18260. ctrl.template = null;
  18261. }
  18262. });
  18263. };
  18264. }
  18265. };
  18266. }];
  18267. // This directive is called during the $transclude call of the first `ngInclude` directive.
  18268. // It will replace and compile the content of the element with the loaded template.
  18269. // We need this directive so that the element content is already filled when
  18270. // the link function of another directive on the same element as ngInclude
  18271. // is called.
  18272. var ngIncludeFillContentDirective = ['$compile',
  18273. function($compile) {
  18274. return {
  18275. restrict: 'ECA',
  18276. priority: -400,
  18277. require: 'ngInclude',
  18278. link: function(scope, $element, $attr, ctrl) {
  18279. $element.html(ctrl.template);
  18280. $compile($element.contents())(scope);
  18281. }
  18282. };
  18283. }];
  18284. /**
  18285. * @ngdoc directive
  18286. * @name ngInit
  18287. * @restrict AC
  18288. *
  18289. * @description
  18290. * The `ngInit` directive allows you to evaluate an expression in the
  18291. * current scope.
  18292. *
  18293. * <div class="alert alert-error">
  18294. * The only appropriate use of `ngInit` is for aliasing special properties of
  18295. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  18296. * should use {@link guide/controller controllers} rather than `ngInit`
  18297. * to initialize values on a scope.
  18298. * </div>
  18299. * <div class="alert alert-warning">
  18300. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  18301. * sure you have parenthesis for correct precedence:
  18302. * <pre class="prettyprint">
  18303. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  18304. * </pre>
  18305. * </div>
  18306. *
  18307. * @priority 450
  18308. *
  18309. * @element ANY
  18310. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  18311. *
  18312. * @example
  18313. <example module="initExample">
  18314. <file name="index.html">
  18315. <script>
  18316. angular.module('initExample', [])
  18317. .controller('ExampleController', ['$scope', function($scope) {
  18318. $scope.list = [['a', 'b'], ['c', 'd']];
  18319. }]);
  18320. </script>
  18321. <div ng-controller="ExampleController">
  18322. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  18323. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  18324. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  18325. </div>
  18326. </div>
  18327. </div>
  18328. </file>
  18329. <file name="protractor.js" type="protractor">
  18330. it('should alias index positions', function() {
  18331. var elements = element.all(by.css('.example-init'));
  18332. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  18333. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  18334. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  18335. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  18336. });
  18337. </file>
  18338. </example>
  18339. */
  18340. var ngInitDirective = ngDirective({
  18341. priority: 450,
  18342. compile: function() {
  18343. return {
  18344. pre: function(scope, element, attrs) {
  18345. scope.$eval(attrs.ngInit);
  18346. }
  18347. };
  18348. }
  18349. });
  18350. /**
  18351. * @ngdoc directive
  18352. * @name ngNonBindable
  18353. * @restrict AC
  18354. * @priority 1000
  18355. *
  18356. * @description
  18357. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  18358. * DOM element. This is useful if the element contains what appears to be Angular directives and
  18359. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  18360. * displays snippets of code, for instance.
  18361. *
  18362. * @element ANY
  18363. *
  18364. * @example
  18365. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  18366. * but the one wrapped in `ngNonBindable` is left alone.
  18367. *
  18368. * @example
  18369. <example>
  18370. <file name="index.html">
  18371. <div>Normal: {{1 + 2}}</div>
  18372. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  18373. </file>
  18374. <file name="protractor.js" type="protractor">
  18375. it('should check ng-non-bindable', function() {
  18376. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  18377. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  18378. });
  18379. </file>
  18380. </example>
  18381. */
  18382. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  18383. /**
  18384. * @ngdoc directive
  18385. * @name ngPluralize
  18386. * @restrict EA
  18387. *
  18388. * @description
  18389. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  18390. * These rules are bundled with angular.js, but can be overridden
  18391. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  18392. * by specifying the mappings between
  18393. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18394. * and the strings to be displayed.
  18395. *
  18396. * # Plural categories and explicit number rules
  18397. * There are two
  18398. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18399. * in Angular's default en-US locale: "one" and "other".
  18400. *
  18401. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  18402. * any number that is not 1), an explicit number rule can only match one number. For example, the
  18403. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  18404. * and explicit number rules throughout the rest of this documentation.
  18405. *
  18406. * # Configuring ngPluralize
  18407. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  18408. * You can also provide an optional attribute, `offset`.
  18409. *
  18410. * The value of the `count` attribute can be either a string or an {@link guide/expression
  18411. * Angular expression}; these are evaluated on the current scope for its bound value.
  18412. *
  18413. * The `when` attribute specifies the mappings between plural categories and the actual
  18414. * string to be displayed. The value of the attribute should be a JSON object.
  18415. *
  18416. * The following example shows how to configure ngPluralize:
  18417. *
  18418. * ```html
  18419. * <ng-pluralize count="personCount"
  18420. when="{'0': 'Nobody is viewing.',
  18421. * 'one': '1 person is viewing.',
  18422. * 'other': '{} people are viewing.'}">
  18423. * </ng-pluralize>
  18424. *```
  18425. *
  18426. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  18427. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  18428. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  18429. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  18430. * show "a dozen people are viewing".
  18431. *
  18432. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  18433. * into pluralized strings. In the previous example, Angular will replace `{}` with
  18434. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  18435. * for <span ng-non-bindable>{{numberExpression}}</span>.
  18436. *
  18437. * # Configuring ngPluralize with offset
  18438. * The `offset` attribute allows further customization of pluralized text, which can result in
  18439. * a better user experience. For example, instead of the message "4 people are viewing this document",
  18440. * you might display "John, Kate and 2 others are viewing this document".
  18441. * The offset attribute allows you to offset a number by any desired value.
  18442. * Let's take a look at an example:
  18443. *
  18444. * ```html
  18445. * <ng-pluralize count="personCount" offset=2
  18446. * when="{'0': 'Nobody is viewing.',
  18447. * '1': '{{person1}} is viewing.',
  18448. * '2': '{{person1}} and {{person2}} are viewing.',
  18449. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18450. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18451. * </ng-pluralize>
  18452. * ```
  18453. *
  18454. * Notice that we are still using two plural categories(one, other), but we added
  18455. * three explicit number rules 0, 1 and 2.
  18456. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  18457. * When three people view the document, no explicit number rule is found, so
  18458. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  18459. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  18460. * is shown.
  18461. *
  18462. * Note that when you specify offsets, you must provide explicit number rules for
  18463. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  18464. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  18465. * plural categories "one" and "other".
  18466. *
  18467. * @param {string|expression} count The variable to be bound to.
  18468. * @param {string} when The mapping between plural category to its corresponding strings.
  18469. * @param {number=} offset Offset to deduct from the total number.
  18470. *
  18471. * @example
  18472. <example module="pluralizeExample">
  18473. <file name="index.html">
  18474. <script>
  18475. angular.module('pluralizeExample', [])
  18476. .controller('ExampleController', ['$scope', function($scope) {
  18477. $scope.person1 = 'Igor';
  18478. $scope.person2 = 'Misko';
  18479. $scope.personCount = 1;
  18480. }]);
  18481. </script>
  18482. <div ng-controller="ExampleController">
  18483. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  18484. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  18485. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  18486. <!--- Example with simple pluralization rules for en locale --->
  18487. Without Offset:
  18488. <ng-pluralize count="personCount"
  18489. when="{'0': 'Nobody is viewing.',
  18490. 'one': '1 person is viewing.',
  18491. 'other': '{} people are viewing.'}">
  18492. </ng-pluralize><br>
  18493. <!--- Example with offset --->
  18494. With Offset(2):
  18495. <ng-pluralize count="personCount" offset=2
  18496. when="{'0': 'Nobody is viewing.',
  18497. '1': '{{person1}} is viewing.',
  18498. '2': '{{person1}} and {{person2}} are viewing.',
  18499. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18500. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18501. </ng-pluralize>
  18502. </div>
  18503. </file>
  18504. <file name="protractor.js" type="protractor">
  18505. it('should show correct pluralized string', function() {
  18506. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  18507. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18508. var countInput = element(by.model('personCount'));
  18509. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  18510. expect(withOffset.getText()).toEqual('Igor is viewing.');
  18511. countInput.clear();
  18512. countInput.sendKeys('0');
  18513. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  18514. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  18515. countInput.clear();
  18516. countInput.sendKeys('2');
  18517. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  18518. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  18519. countInput.clear();
  18520. countInput.sendKeys('3');
  18521. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  18522. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  18523. countInput.clear();
  18524. countInput.sendKeys('4');
  18525. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  18526. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  18527. });
  18528. it('should show data-bound names', function() {
  18529. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18530. var personCount = element(by.model('personCount'));
  18531. var person1 = element(by.model('person1'));
  18532. var person2 = element(by.model('person2'));
  18533. personCount.clear();
  18534. personCount.sendKeys('4');
  18535. person1.clear();
  18536. person1.sendKeys('Di');
  18537. person2.clear();
  18538. person2.sendKeys('Vojta');
  18539. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  18540. });
  18541. </file>
  18542. </example>
  18543. */
  18544. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  18545. var BRACE = /{}/g;
  18546. return {
  18547. restrict: 'EA',
  18548. link: function(scope, element, attr) {
  18549. var numberExp = attr.count,
  18550. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  18551. offset = attr.offset || 0,
  18552. whens = scope.$eval(whenExp) || {},
  18553. whensExpFns = {},
  18554. startSymbol = $interpolate.startSymbol(),
  18555. endSymbol = $interpolate.endSymbol(),
  18556. isWhen = /^when(Minus)?(.+)$/;
  18557. forEach(attr, function(expression, attributeName) {
  18558. if (isWhen.test(attributeName)) {
  18559. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  18560. element.attr(attr.$attr[attributeName]);
  18561. }
  18562. });
  18563. forEach(whens, function(expression, key) {
  18564. whensExpFns[key] =
  18565. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  18566. offset + endSymbol));
  18567. });
  18568. scope.$watch(function ngPluralizeWatch() {
  18569. var value = parseFloat(scope.$eval(numberExp));
  18570. if (!isNaN(value)) {
  18571. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  18572. //check it against pluralization rules in $locale service
  18573. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  18574. return whensExpFns[value](scope, element, true);
  18575. } else {
  18576. return '';
  18577. }
  18578. }, function ngPluralizeWatchAction(newVal) {
  18579. element.text(newVal);
  18580. });
  18581. }
  18582. };
  18583. }];
  18584. /**
  18585. * @ngdoc directive
  18586. * @name ngRepeat
  18587. *
  18588. * @description
  18589. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  18590. * instance gets its own scope, where the given loop variable is set to the current collection item,
  18591. * and `$index` is set to the item index or key.
  18592. *
  18593. * Special properties are exposed on the local scope of each template instance, including:
  18594. *
  18595. * | Variable | Type | Details |
  18596. * |-----------|-----------------|-----------------------------------------------------------------------------|
  18597. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  18598. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  18599. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  18600. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  18601. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  18602. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  18603. *
  18604. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  18605. * This may be useful when, for instance, nesting ngRepeats.
  18606. *
  18607. * # Special repeat start and end points
  18608. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  18609. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  18610. * 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)
  18611. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  18612. *
  18613. * The example below makes use of this feature:
  18614. * ```html
  18615. * <header ng-repeat-start="item in items">
  18616. * Header {{ item }}
  18617. * </header>
  18618. * <div class="body">
  18619. * Body {{ item }}
  18620. * </div>
  18621. * <footer ng-repeat-end>
  18622. * Footer {{ item }}
  18623. * </footer>
  18624. * ```
  18625. *
  18626. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  18627. * ```html
  18628. * <header>
  18629. * Header A
  18630. * </header>
  18631. * <div class="body">
  18632. * Body A
  18633. * </div>
  18634. * <footer>
  18635. * Footer A
  18636. * </footer>
  18637. * <header>
  18638. * Header B
  18639. * </header>
  18640. * <div class="body">
  18641. * Body B
  18642. * </div>
  18643. * <footer>
  18644. * Footer B
  18645. * </footer>
  18646. * ```
  18647. *
  18648. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  18649. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  18650. *
  18651. * @animations
  18652. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  18653. *
  18654. * **.leave** - when an item is removed from the list or when an item is filtered out
  18655. *
  18656. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  18657. *
  18658. * @element ANY
  18659. * @scope
  18660. * @priority 1000
  18661. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  18662. * formats are currently supported:
  18663. *
  18664. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  18665. * is a scope expression giving the collection to enumerate.
  18666. *
  18667. * For example: `album in artist.albums`.
  18668. *
  18669. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  18670. * and `expression` is the scope expression giving the collection to enumerate.
  18671. *
  18672. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  18673. *
  18674. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  18675. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  18676. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  18677. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  18678. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  18679. * before specifying a tracking expression.
  18680. *
  18681. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  18682. * will be associated by item identity in the array.
  18683. *
  18684. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18685. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18686. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18687. * element in the same way in the DOM.
  18688. *
  18689. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18690. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18691. * property is same.
  18692. *
  18693. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18694. * to items in conjunction with a tracking expression.
  18695. *
  18696. * @example
  18697. * This example initializes the scope to a list of names and
  18698. * then uses `ngRepeat` to display every person:
  18699. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18700. <file name="index.html">
  18701. <div ng-init="friends = [
  18702. {name:'John', age:25, gender:'boy'},
  18703. {name:'Jessie', age:30, gender:'girl'},
  18704. {name:'Johanna', age:28, gender:'girl'},
  18705. {name:'Joy', age:15, gender:'girl'},
  18706. {name:'Mary', age:28, gender:'girl'},
  18707. {name:'Peter', age:95, gender:'boy'},
  18708. {name:'Sebastian', age:50, gender:'boy'},
  18709. {name:'Erika', age:27, gender:'girl'},
  18710. {name:'Patrick', age:40, gender:'boy'},
  18711. {name:'Samantha', age:60, gender:'girl'}
  18712. ]">
  18713. I have {{friends.length}} friends. They are:
  18714. <input type="search" ng-model="q" placeholder="filter friends..." />
  18715. <ul class="example-animate-container">
  18716. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18717. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18718. </li>
  18719. </ul>
  18720. </div>
  18721. </file>
  18722. <file name="animations.css">
  18723. .example-animate-container {
  18724. background:white;
  18725. border:1px solid black;
  18726. list-style:none;
  18727. margin:0;
  18728. padding:0 10px;
  18729. }
  18730. .animate-repeat {
  18731. line-height:40px;
  18732. list-style:none;
  18733. box-sizing:border-box;
  18734. }
  18735. .animate-repeat.ng-move,
  18736. .animate-repeat.ng-enter,
  18737. .animate-repeat.ng-leave {
  18738. -webkit-transition:all linear 0.5s;
  18739. transition:all linear 0.5s;
  18740. }
  18741. .animate-repeat.ng-leave.ng-leave-active,
  18742. .animate-repeat.ng-move,
  18743. .animate-repeat.ng-enter {
  18744. opacity:0;
  18745. max-height:0;
  18746. }
  18747. .animate-repeat.ng-leave,
  18748. .animate-repeat.ng-move.ng-move-active,
  18749. .animate-repeat.ng-enter.ng-enter-active {
  18750. opacity:1;
  18751. max-height:40px;
  18752. }
  18753. </file>
  18754. <file name="protractor.js" type="protractor">
  18755. var friends = element.all(by.repeater('friend in friends'));
  18756. it('should render initial data set', function() {
  18757. expect(friends.count()).toBe(10);
  18758. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18759. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18760. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18761. expect(element(by.binding('friends.length')).getText())
  18762. .toMatch("I have 10 friends. They are:");
  18763. });
  18764. it('should update repeater when filter predicate changes', function() {
  18765. expect(friends.count()).toBe(10);
  18766. element(by.model('q')).sendKeys('ma');
  18767. expect(friends.count()).toBe(2);
  18768. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18769. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18770. });
  18771. </file>
  18772. </example>
  18773. */
  18774. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18775. var NG_REMOVED = '$$NG_REMOVED';
  18776. var ngRepeatMinErr = minErr('ngRepeat');
  18777. return {
  18778. transclude: 'element',
  18779. priority: 1000,
  18780. terminal: true,
  18781. $$tlb: true,
  18782. link: function($scope, $element, $attr, ctrl, $transclude){
  18783. var expression = $attr.ngRepeat;
  18784. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18785. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18786. lhs, rhs, valueIdentifier, keyIdentifier,
  18787. hashFnLocals = {$id: hashKey};
  18788. if (!match) {
  18789. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18790. expression);
  18791. }
  18792. lhs = match[1];
  18793. rhs = match[2];
  18794. trackByExp = match[3];
  18795. if (trackByExp) {
  18796. trackByExpGetter = $parse(trackByExp);
  18797. trackByIdExpFn = function(key, value, index) {
  18798. // assign key, value, and $index to the locals so that they can be used in hash functions
  18799. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18800. hashFnLocals[valueIdentifier] = value;
  18801. hashFnLocals.$index = index;
  18802. return trackByExpGetter($scope, hashFnLocals);
  18803. };
  18804. } else {
  18805. trackByIdArrayFn = function(key, value) {
  18806. return hashKey(value);
  18807. };
  18808. trackByIdObjFn = function(key) {
  18809. return key;
  18810. };
  18811. }
  18812. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18813. if (!match) {
  18814. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18815. lhs);
  18816. }
  18817. valueIdentifier = match[3] || match[1];
  18818. keyIdentifier = match[2];
  18819. // Store a list of elements from previous run. This is a hash where key is the item from the
  18820. // iterator, and the value is objects with following properties.
  18821. // - scope: bound scope
  18822. // - element: previous element.
  18823. // - index: position
  18824. var lastBlockMap = {};
  18825. //watch props
  18826. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18827. var index, length,
  18828. previousNode = $element[0], // current position of the node
  18829. nextNode,
  18830. // Same as lastBlockMap but it has the current state. It will become the
  18831. // lastBlockMap on the next iteration.
  18832. nextBlockMap = {},
  18833. arrayLength,
  18834. childScope,
  18835. key, value, // key/value of iteration
  18836. trackById,
  18837. trackByIdFn,
  18838. collectionKeys,
  18839. block, // last object information {scope, element, id}
  18840. nextBlockOrder = [],
  18841. elementsToRemove;
  18842. if (isArrayLike(collection)) {
  18843. collectionKeys = collection;
  18844. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18845. } else {
  18846. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18847. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18848. collectionKeys = [];
  18849. for (key in collection) {
  18850. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18851. collectionKeys.push(key);
  18852. }
  18853. }
  18854. collectionKeys.sort();
  18855. }
  18856. arrayLength = collectionKeys.length;
  18857. // locate existing items
  18858. length = nextBlockOrder.length = collectionKeys.length;
  18859. for(index = 0; index < length; index++) {
  18860. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18861. value = collection[key];
  18862. trackById = trackByIdFn(key, value, index);
  18863. assertNotHasOwnProperty(trackById, '`track by` id');
  18864. if(lastBlockMap.hasOwnProperty(trackById)) {
  18865. block = lastBlockMap[trackById];
  18866. delete lastBlockMap[trackById];
  18867. nextBlockMap[trackById] = block;
  18868. nextBlockOrder[index] = block;
  18869. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18870. // restore lastBlockMap
  18871. forEach(nextBlockOrder, function(block) {
  18872. if (block && block.scope) lastBlockMap[block.id] = block;
  18873. });
  18874. // This is a duplicate and we need to throw an error
  18875. throw ngRepeatMinErr('dupes',
  18876. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  18877. expression, trackById, toJson(value));
  18878. } else {
  18879. // new never before seen block
  18880. nextBlockOrder[index] = { id: trackById };
  18881. nextBlockMap[trackById] = false;
  18882. }
  18883. }
  18884. // remove existing items
  18885. for (key in lastBlockMap) {
  18886. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18887. if (lastBlockMap.hasOwnProperty(key)) {
  18888. block = lastBlockMap[key];
  18889. elementsToRemove = getBlockElements(block.clone);
  18890. $animate.leave(elementsToRemove);
  18891. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18892. block.scope.$destroy();
  18893. }
  18894. }
  18895. // we are not using forEach for perf reasons (trying to avoid #call)
  18896. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18897. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18898. value = collection[key];
  18899. block = nextBlockOrder[index];
  18900. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18901. if (block.scope) {
  18902. // if we have already seen this object, then we need to reuse the
  18903. // associated scope/element
  18904. childScope = block.scope;
  18905. nextNode = previousNode;
  18906. do {
  18907. nextNode = nextNode.nextSibling;
  18908. } while(nextNode && nextNode[NG_REMOVED]);
  18909. if (getBlockStart(block) != nextNode) {
  18910. // existing item which got moved
  18911. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18912. }
  18913. previousNode = getBlockEnd(block);
  18914. } else {
  18915. // new item which we don't know about
  18916. childScope = $scope.$new();
  18917. }
  18918. childScope[valueIdentifier] = value;
  18919. if (keyIdentifier) childScope[keyIdentifier] = key;
  18920. childScope.$index = index;
  18921. childScope.$first = (index === 0);
  18922. childScope.$last = (index === (arrayLength - 1));
  18923. childScope.$middle = !(childScope.$first || childScope.$last);
  18924. // jshint bitwise: false
  18925. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18926. // jshint bitwise: true
  18927. if (!block.scope) {
  18928. $transclude(childScope, function(clone) {
  18929. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18930. $animate.enter(clone, null, jqLite(previousNode));
  18931. previousNode = clone;
  18932. block.scope = childScope;
  18933. // Note: We only need the first/last node of the cloned nodes.
  18934. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18935. // by a directive with templateUrl when its template arrives.
  18936. block.clone = clone;
  18937. nextBlockMap[block.id] = block;
  18938. });
  18939. }
  18940. }
  18941. lastBlockMap = nextBlockMap;
  18942. });
  18943. }
  18944. };
  18945. function getBlockStart(block) {
  18946. return block.clone[0];
  18947. }
  18948. function getBlockEnd(block) {
  18949. return block.clone[block.clone.length - 1];
  18950. }
  18951. }];
  18952. /**
  18953. * @ngdoc directive
  18954. * @name ngShow
  18955. *
  18956. * @description
  18957. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18958. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  18959. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18960. * in AngularJS and sets the display style to none (using an !important flag).
  18961. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18962. *
  18963. * ```html
  18964. * <!-- when $scope.myValue is truthy (element is visible) -->
  18965. * <div ng-show="myValue"></div>
  18966. *
  18967. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18968. * <div ng-show="myValue" class="ng-hide"></div>
  18969. * ```
  18970. *
  18971. * When the `ngShow` expression evaluates to false then the `.ng-hide` CSS class is added to the class attribute
  18972. * on the element causing it to become hidden. When true, the `.ng-hide` CSS class is removed
  18973. * from the element causing the element not to appear hidden.
  18974. *
  18975. * <div class="alert alert-warning">
  18976. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18977. * "f" / "0" / "false" / "no" / "n" / "[]"
  18978. * </div>
  18979. *
  18980. * ## Why is !important used?
  18981. *
  18982. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  18983. * can be easily overridden by heavier selectors. For example, something as simple
  18984. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18985. * This also becomes a bigger issue when dealing with CSS frameworks.
  18986. *
  18987. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18988. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18989. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18990. *
  18991. * ### Overriding `.ng-hide`
  18992. *
  18993. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18994. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18995. * class in CSS:
  18996. *
  18997. * ```css
  18998. * .ng-hide {
  18999. * //this is just another form of hiding an element
  19000. * display:block!important;
  19001. * position:absolute;
  19002. * top:-9999px;
  19003. * left:-9999px;
  19004. * }
  19005. * ```
  19006. *
  19007. * By default you don't need to override in CSS anything and the animations will work around the display style.
  19008. *
  19009. * ## A note about animations with `ngShow`
  19010. *
  19011. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  19012. * is true and false. This system works like the animation system present with ngClass except that
  19013. * you must also include the !important flag to override the display property
  19014. * so that you can perform an animation when the element is hidden during the time of the animation.
  19015. *
  19016. * ```css
  19017. * //
  19018. * //a working example can be found at the bottom of this page
  19019. * //
  19020. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  19021. * transition:0.5s linear all;
  19022. * }
  19023. *
  19024. * .my-element.ng-hide-add { ... }
  19025. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  19026. * .my-element.ng-hide-remove { ... }
  19027. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  19028. * ```
  19029. *
  19030. * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display
  19031. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  19032. *
  19033. * @animations
  19034. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  19035. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  19036. *
  19037. * @element ANY
  19038. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  19039. * then the element is shown or hidden respectively.
  19040. *
  19041. * @example
  19042. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19043. <file name="index.html">
  19044. Click me: <input type="checkbox" ng-model="checked"><br/>
  19045. <div>
  19046. Show:
  19047. <div class="check-element animate-show" ng-show="checked">
  19048. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  19049. </div>
  19050. </div>
  19051. <div>
  19052. Hide:
  19053. <div class="check-element animate-show" ng-hide="checked">
  19054. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19055. </div>
  19056. </div>
  19057. </file>
  19058. <file name="glyphicons.css">
  19059. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19060. </file>
  19061. <file name="animations.css">
  19062. .animate-show {
  19063. -webkit-transition:all linear 0.5s;
  19064. transition:all linear 0.5s;
  19065. line-height:20px;
  19066. opacity:1;
  19067. padding:10px;
  19068. border:1px solid black;
  19069. background:white;
  19070. }
  19071. .animate-show.ng-hide {
  19072. line-height:0;
  19073. opacity:0;
  19074. padding:0 10px;
  19075. }
  19076. .check-element {
  19077. padding:10px;
  19078. border:1px solid black;
  19079. background:white;
  19080. }
  19081. </file>
  19082. <file name="protractor.js" type="protractor">
  19083. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19084. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19085. it('should check ng-show / ng-hide', function() {
  19086. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19087. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19088. element(by.model('checked')).click();
  19089. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19090. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19091. });
  19092. </file>
  19093. </example>
  19094. */
  19095. var ngShowDirective = ['$animate', function($animate) {
  19096. return function(scope, element, attr) {
  19097. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  19098. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  19099. });
  19100. };
  19101. }];
  19102. /**
  19103. * @ngdoc directive
  19104. * @name ngHide
  19105. *
  19106. * @description
  19107. * The `ngHide` directive shows or hides the given HTML element based on the expression
  19108. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  19109. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  19110. * in AngularJS and sets the display style to none (using an !important flag).
  19111. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19112. *
  19113. * ```html
  19114. * <!-- when $scope.myValue is truthy (element is hidden) -->
  19115. * <div ng-hide="myValue" class="ng-hide"></div>
  19116. *
  19117. * <!-- when $scope.myValue is falsy (element is visible) -->
  19118. * <div ng-hide="myValue"></div>
  19119. * ```
  19120. *
  19121. * When the `.ngHide` expression evaluates to true then the `.ng-hide` CSS class is added to the class attribute
  19122. * on the element causing it to become hidden. When false, the `.ng-hide` CSS class is removed
  19123. * from the element causing the element not to appear hidden.
  19124. *
  19125. * <div class="alert alert-warning">
  19126. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  19127. * "f" / "0" / "false" / "no" / "n" / "[]"
  19128. * </div>
  19129. *
  19130. * ## Why is !important used?
  19131. *
  19132. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  19133. * can be easily overridden by heavier selectors. For example, something as simple
  19134. * as changing the display style on a HTML list item would make hidden elements appear visible.
  19135. * This also becomes a bigger issue when dealing with CSS frameworks.
  19136. *
  19137. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  19138. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  19139. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  19140. *
  19141. * ### Overriding `.ng-hide`
  19142. *
  19143. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  19144. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  19145. * class in CSS:
  19146. *
  19147. * ```css
  19148. * .ng-hide {
  19149. * //this is just another form of hiding an element
  19150. * display:block!important;
  19151. * position:absolute;
  19152. * top:-9999px;
  19153. * left:-9999px;
  19154. * }
  19155. * ```
  19156. *
  19157. * By default you don't need to override in CSS anything and the animations will work around the display style.
  19158. *
  19159. * ## A note about animations with `ngHide`
  19160. *
  19161. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  19162. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  19163. * CSS class is added and removed for you instead of your own CSS class.
  19164. *
  19165. * ```css
  19166. * //
  19167. * //a working example can be found at the bottom of this page
  19168. * //
  19169. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  19170. * transition:0.5s linear all;
  19171. * }
  19172. *
  19173. * .my-element.ng-hide-add { ... }
  19174. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  19175. * .my-element.ng-hide-remove { ... }
  19176. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  19177. * ```
  19178. *
  19179. * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display
  19180. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  19181. *
  19182. * @animations
  19183. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  19184. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  19185. *
  19186. * @element ANY
  19187. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  19188. * the element is shown or hidden respectively.
  19189. *
  19190. * @example
  19191. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19192. <file name="index.html">
  19193. Click me: <input type="checkbox" ng-model="checked"><br/>
  19194. <div>
  19195. Show:
  19196. <div class="check-element animate-hide" ng-show="checked">
  19197. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  19198. </div>
  19199. </div>
  19200. <div>
  19201. Hide:
  19202. <div class="check-element animate-hide" ng-hide="checked">
  19203. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19204. </div>
  19205. </div>
  19206. </file>
  19207. <file name="glyphicons.css">
  19208. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19209. </file>
  19210. <file name="animations.css">
  19211. .animate-hide {
  19212. -webkit-transition:all linear 0.5s;
  19213. transition:all linear 0.5s;
  19214. line-height:20px;
  19215. opacity:1;
  19216. padding:10px;
  19217. border:1px solid black;
  19218. background:white;
  19219. }
  19220. .animate-hide.ng-hide {
  19221. line-height:0;
  19222. opacity:0;
  19223. padding:0 10px;
  19224. }
  19225. .check-element {
  19226. padding:10px;
  19227. border:1px solid black;
  19228. background:white;
  19229. }
  19230. </file>
  19231. <file name="protractor.js" type="protractor">
  19232. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19233. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19234. it('should check ng-show / ng-hide', function() {
  19235. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19236. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19237. element(by.model('checked')).click();
  19238. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19239. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19240. });
  19241. </file>
  19242. </example>
  19243. */
  19244. var ngHideDirective = ['$animate', function($animate) {
  19245. return function(scope, element, attr) {
  19246. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  19247. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  19248. });
  19249. };
  19250. }];
  19251. /**
  19252. * @ngdoc directive
  19253. * @name ngStyle
  19254. * @restrict AC
  19255. *
  19256. * @description
  19257. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  19258. *
  19259. * @element ANY
  19260. * @param {expression} ngStyle
  19261. *
  19262. * {@link guide/expression Expression} which evals to an
  19263. * object whose keys are CSS style names and values are corresponding values for those CSS
  19264. * keys.
  19265. *
  19266. * Since some CSS style names are not valid keys for an object, they must be quoted.
  19267. * See the 'background-color' style in the example below.
  19268. *
  19269. * @example
  19270. <example>
  19271. <file name="index.html">
  19272. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  19273. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  19274. <input type="button" value="clear" ng-click="myStyle={}">
  19275. <br/>
  19276. <span ng-style="myStyle">Sample Text</span>
  19277. <pre>myStyle={{myStyle}}</pre>
  19278. </file>
  19279. <file name="style.css">
  19280. span {
  19281. color: black;
  19282. }
  19283. </file>
  19284. <file name="protractor.js" type="protractor">
  19285. var colorSpan = element(by.css('span'));
  19286. it('should check ng-style', function() {
  19287. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19288. element(by.css('input[value=\'set color\']')).click();
  19289. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  19290. element(by.css('input[value=clear]')).click();
  19291. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19292. });
  19293. </file>
  19294. </example>
  19295. */
  19296. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  19297. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  19298. if (oldStyles && (newStyles !== oldStyles)) {
  19299. forEach(oldStyles, function(val, style) { element.css(style, '');});
  19300. }
  19301. if (newStyles) element.css(newStyles);
  19302. }, true);
  19303. });
  19304. /**
  19305. * @ngdoc directive
  19306. * @name ngSwitch
  19307. * @restrict EA
  19308. *
  19309. * @description
  19310. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  19311. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  19312. * as specified in the template.
  19313. *
  19314. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  19315. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  19316. * matches the value obtained from the evaluated expression. In other words, you define a container element
  19317. * (where you place the directive), place an expression on the **`on="..."` attribute**
  19318. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  19319. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  19320. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  19321. * attribute is displayed.
  19322. *
  19323. * <div class="alert alert-info">
  19324. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  19325. * as literal string values to match against.
  19326. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  19327. * value of the expression `$scope.someVal`.
  19328. * </div>
  19329. * @animations
  19330. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  19331. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  19332. *
  19333. * @usage
  19334. *
  19335. * ```
  19336. * <ANY ng-switch="expression">
  19337. * <ANY ng-switch-when="matchValue1">...</ANY>
  19338. * <ANY ng-switch-when="matchValue2">...</ANY>
  19339. * <ANY ng-switch-default>...</ANY>
  19340. * </ANY>
  19341. * ```
  19342. *
  19343. *
  19344. * @scope
  19345. * @priority 800
  19346. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  19347. * On child elements add:
  19348. *
  19349. * * `ngSwitchWhen`: the case statement to match against. If match then this
  19350. * case will be displayed. If the same match appears multiple times, all the
  19351. * elements will be displayed.
  19352. * * `ngSwitchDefault`: the default case when no other case match. If there
  19353. * are multiple default cases, all of them will be displayed when no other
  19354. * case match.
  19355. *
  19356. *
  19357. * @example
  19358. <example module="switchExample" deps="angular-animate.js" animations="true">
  19359. <file name="index.html">
  19360. <div ng-controller="ExampleController">
  19361. <select ng-model="selection" ng-options="item for item in items">
  19362. </select>
  19363. <tt>selection={{selection}}</tt>
  19364. <hr/>
  19365. <div class="animate-switch-container"
  19366. ng-switch on="selection">
  19367. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  19368. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  19369. <div class="animate-switch" ng-switch-default>default</div>
  19370. </div>
  19371. </div>
  19372. </file>
  19373. <file name="script.js">
  19374. angular.module('switchExample', ['ngAnimate'])
  19375. .controller('ExampleController', ['$scope', function($scope) {
  19376. $scope.items = ['settings', 'home', 'other'];
  19377. $scope.selection = $scope.items[0];
  19378. }]);
  19379. </file>
  19380. <file name="animations.css">
  19381. .animate-switch-container {
  19382. position:relative;
  19383. background:white;
  19384. border:1px solid black;
  19385. height:40px;
  19386. overflow:hidden;
  19387. }
  19388. .animate-switch {
  19389. padding:10px;
  19390. }
  19391. .animate-switch.ng-animate {
  19392. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19393. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19394. position:absolute;
  19395. top:0;
  19396. left:0;
  19397. right:0;
  19398. bottom:0;
  19399. }
  19400. .animate-switch.ng-leave.ng-leave-active,
  19401. .animate-switch.ng-enter {
  19402. top:-50px;
  19403. }
  19404. .animate-switch.ng-leave,
  19405. .animate-switch.ng-enter.ng-enter-active {
  19406. top:0;
  19407. }
  19408. </file>
  19409. <file name="protractor.js" type="protractor">
  19410. var switchElem = element(by.css('[ng-switch]'));
  19411. var select = element(by.model('selection'));
  19412. it('should start in settings', function() {
  19413. expect(switchElem.getText()).toMatch(/Settings Div/);
  19414. });
  19415. it('should change to home', function() {
  19416. select.all(by.css('option')).get(1).click();
  19417. expect(switchElem.getText()).toMatch(/Home Span/);
  19418. });
  19419. it('should select default', function() {
  19420. select.all(by.css('option')).get(2).click();
  19421. expect(switchElem.getText()).toMatch(/default/);
  19422. });
  19423. </file>
  19424. </example>
  19425. */
  19426. var ngSwitchDirective = ['$animate', function($animate) {
  19427. return {
  19428. restrict: 'EA',
  19429. require: 'ngSwitch',
  19430. // asks for $scope to fool the BC controller module
  19431. controller: ['$scope', function ngSwitchController() {
  19432. this.cases = {};
  19433. }],
  19434. link: function(scope, element, attr, ngSwitchController) {
  19435. var watchExpr = attr.ngSwitch || attr.on,
  19436. selectedTranscludes = [],
  19437. selectedElements = [],
  19438. previousElements = [],
  19439. selectedScopes = [];
  19440. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  19441. var i, ii;
  19442. for (i = 0, ii = previousElements.length; i < ii; ++i) {
  19443. previousElements[i].remove();
  19444. }
  19445. previousElements.length = 0;
  19446. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  19447. var selected = selectedElements[i];
  19448. selectedScopes[i].$destroy();
  19449. previousElements[i] = selected;
  19450. $animate.leave(selected, function() {
  19451. previousElements.splice(i, 1);
  19452. });
  19453. }
  19454. selectedElements.length = 0;
  19455. selectedScopes.length = 0;
  19456. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  19457. scope.$eval(attr.change);
  19458. forEach(selectedTranscludes, function(selectedTransclude) {
  19459. var selectedScope = scope.$new();
  19460. selectedScopes.push(selectedScope);
  19461. selectedTransclude.transclude(selectedScope, function(caseElement) {
  19462. var anchor = selectedTransclude.element;
  19463. selectedElements.push(caseElement);
  19464. $animate.enter(caseElement, anchor.parent(), anchor);
  19465. });
  19466. });
  19467. }
  19468. });
  19469. }
  19470. };
  19471. }];
  19472. var ngSwitchWhenDirective = ngDirective({
  19473. transclude: 'element',
  19474. priority: 800,
  19475. require: '^ngSwitch',
  19476. link: function(scope, element, attrs, ctrl, $transclude) {
  19477. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  19478. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  19479. }
  19480. });
  19481. var ngSwitchDefaultDirective = ngDirective({
  19482. transclude: 'element',
  19483. priority: 800,
  19484. require: '^ngSwitch',
  19485. link: function(scope, element, attr, ctrl, $transclude) {
  19486. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  19487. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  19488. }
  19489. });
  19490. /**
  19491. * @ngdoc directive
  19492. * @name ngTransclude
  19493. * @restrict AC
  19494. *
  19495. * @description
  19496. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  19497. *
  19498. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  19499. *
  19500. * @element ANY
  19501. *
  19502. * @example
  19503. <example module="transcludeExample">
  19504. <file name="index.html">
  19505. <script>
  19506. angular.module('transcludeExample', [])
  19507. .directive('pane', function(){
  19508. return {
  19509. restrict: 'E',
  19510. transclude: true,
  19511. scope: { title:'@' },
  19512. template: '<div style="border: 1px solid black;">' +
  19513. '<div style="background-color: gray">{{title}}</div>' +
  19514. '<div ng-transclude></div>' +
  19515. '</div>'
  19516. };
  19517. })
  19518. .controller('ExampleController', ['$scope', function($scope) {
  19519. $scope.title = 'Lorem Ipsum';
  19520. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  19521. }]);
  19522. </script>
  19523. <div ng-controller="ExampleController">
  19524. <input ng-model="title"><br>
  19525. <textarea ng-model="text"></textarea> <br/>
  19526. <pane title="{{title}}">{{text}}</pane>
  19527. </div>
  19528. </file>
  19529. <file name="protractor.js" type="protractor">
  19530. it('should have transcluded', function() {
  19531. var titleElement = element(by.model('title'));
  19532. titleElement.clear();
  19533. titleElement.sendKeys('TITLE');
  19534. var textElement = element(by.model('text'));
  19535. textElement.clear();
  19536. textElement.sendKeys('TEXT');
  19537. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  19538. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  19539. });
  19540. </file>
  19541. </example>
  19542. *
  19543. */
  19544. var ngTranscludeDirective = ngDirective({
  19545. link: function($scope, $element, $attrs, controller, $transclude) {
  19546. if (!$transclude) {
  19547. throw minErr('ngTransclude')('orphan',
  19548. 'Illegal use of ngTransclude directive in the template! ' +
  19549. 'No parent directive that requires a transclusion found. ' +
  19550. 'Element: {0}',
  19551. startingTag($element));
  19552. }
  19553. $transclude(function(clone) {
  19554. $element.empty();
  19555. $element.append(clone);
  19556. });
  19557. }
  19558. });
  19559. /**
  19560. * @ngdoc directive
  19561. * @name script
  19562. * @restrict E
  19563. *
  19564. * @description
  19565. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  19566. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  19567. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  19568. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  19569. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  19570. *
  19571. * @param {string} type Must be set to `'text/ng-template'`.
  19572. * @param {string} id Cache name of the template.
  19573. *
  19574. * @example
  19575. <example>
  19576. <file name="index.html">
  19577. <script type="text/ng-template" id="/tpl.html">
  19578. Content of the template.
  19579. </script>
  19580. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  19581. <div id="tpl-content" ng-include src="currentTpl"></div>
  19582. </file>
  19583. <file name="protractor.js" type="protractor">
  19584. it('should load template defined inside script tag', function() {
  19585. element(by.css('#tpl-link')).click();
  19586. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  19587. });
  19588. </file>
  19589. </example>
  19590. */
  19591. var scriptDirective = ['$templateCache', function($templateCache) {
  19592. return {
  19593. restrict: 'E',
  19594. terminal: true,
  19595. compile: function(element, attr) {
  19596. if (attr.type == 'text/ng-template') {
  19597. var templateUrl = attr.id,
  19598. text = element[0].text;
  19599. $templateCache.put(templateUrl, text);
  19600. }
  19601. }
  19602. };
  19603. }];
  19604. var ngOptionsMinErr = minErr('ngOptions');
  19605. /**
  19606. * @ngdoc directive
  19607. * @name select
  19608. * @restrict E
  19609. *
  19610. * @description
  19611. * HTML `SELECT` element with angular data-binding.
  19612. *
  19613. * # `ngOptions`
  19614. *
  19615. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  19616. * elements for the `<select>` element using the array or object obtained by evaluating the
  19617. * `ngOptions` comprehension_expression.
  19618. *
  19619. * When an item in the `<select>` menu is selected, the array element or object property
  19620. * represented by the selected option will be bound to the model identified by the `ngModel`
  19621. * directive.
  19622. *
  19623. * <div class="alert alert-warning">
  19624. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  19625. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  19626. * </div>
  19627. *
  19628. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  19629. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  19630. * option. See example below for demonstration.
  19631. *
  19632. * <div class="alert alert-warning">
  19633. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  19634. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  19635. * `select` model to be bound to a non-string value. This is because an option element can only
  19636. * be bound to string values at present.
  19637. * </div>
  19638. *
  19639. * @param {string} ngModel Assignable angular expression to data-bind to.
  19640. * @param {string=} name Property name of the form under which the control is published.
  19641. * @param {string=} required The control is considered valid only if value is entered.
  19642. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19643. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19644. * `required` when you want to data-bind to the `required` attribute.
  19645. * @param {comprehension_expression=} ngOptions in one of the following forms:
  19646. *
  19647. * * for array data sources:
  19648. * * `label` **`for`** `value` **`in`** `array`
  19649. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  19650. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  19651. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  19652. * * for object data sources:
  19653. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19654. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19655. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  19656. * * `select` **`as`** `label` **`group by`** `group`
  19657. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  19658. *
  19659. * Where:
  19660. *
  19661. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  19662. * * `value`: local variable which will refer to each item in the `array` or each property value
  19663. * of `object` during iteration.
  19664. * * `key`: local variable which will refer to a property name in `object` during iteration.
  19665. * * `label`: The result of this expression will be the label for `<option>` element. The
  19666. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  19667. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  19668. * element. If not specified, `select` expression will default to `value`.
  19669. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  19670. * DOM element.
  19671. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  19672. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  19673. * `value` variable (e.g. `value.propertyName`).
  19674. *
  19675. * @example
  19676. <example module="selectExample">
  19677. <file name="index.html">
  19678. <script>
  19679. angular.module('selectExample', [])
  19680. .controller('ExampleController', ['$scope', function($scope) {
  19681. $scope.colors = [
  19682. {name:'black', shade:'dark'},
  19683. {name:'white', shade:'light'},
  19684. {name:'red', shade:'dark'},
  19685. {name:'blue', shade:'dark'},
  19686. {name:'yellow', shade:'light'}
  19687. ];
  19688. $scope.myColor = $scope.colors[2]; // red
  19689. }]);
  19690. </script>
  19691. <div ng-controller="ExampleController">
  19692. <ul>
  19693. <li ng-repeat="color in colors">
  19694. Name: <input ng-model="color.name">
  19695. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19696. </li>
  19697. <li>
  19698. [<a href ng-click="colors.push({})">add</a>]
  19699. </li>
  19700. </ul>
  19701. <hr/>
  19702. Color (null not allowed):
  19703. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  19704. Color (null allowed):
  19705. <span class="nullable">
  19706. <select ng-model="myColor" ng-options="color.name for color in colors">
  19707. <option value="">-- choose color --</option>
  19708. </select>
  19709. </span><br/>
  19710. Color grouped by shade:
  19711. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  19712. </select><br/>
  19713. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  19714. <hr/>
  19715. Currently selected: {{ {selected_color:myColor} }}
  19716. <div style="border:solid 1px black; height:20px"
  19717. ng-style="{'background-color':myColor.name}">
  19718. </div>
  19719. </div>
  19720. </file>
  19721. <file name="protractor.js" type="protractor">
  19722. it('should check ng-options', function() {
  19723. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  19724. element.all(by.model('myColor')).first().click();
  19725. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  19726. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  19727. element(by.css('.nullable select[ng-model="myColor"]')).click();
  19728. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  19729. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  19730. });
  19731. </file>
  19732. </example>
  19733. */
  19734. var ngOptionsDirective = valueFn({ terminal: true });
  19735. // jshint maxlen: false
  19736. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19737. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19738. 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]+?))?$/,
  19739. nullModelCtrl = {$setViewValue: noop};
  19740. // jshint maxlen: 100
  19741. return {
  19742. restrict: 'E',
  19743. require: ['select', '?ngModel'],
  19744. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19745. var self = this,
  19746. optionsMap = {},
  19747. ngModelCtrl = nullModelCtrl,
  19748. nullOption,
  19749. unknownOption;
  19750. self.databound = $attrs.ngModel;
  19751. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19752. ngModelCtrl = ngModelCtrl_;
  19753. nullOption = nullOption_;
  19754. unknownOption = unknownOption_;
  19755. };
  19756. self.addOption = function(value) {
  19757. assertNotHasOwnProperty(value, '"option value"');
  19758. optionsMap[value] = true;
  19759. if (ngModelCtrl.$viewValue == value) {
  19760. $element.val(value);
  19761. if (unknownOption.parent()) unknownOption.remove();
  19762. }
  19763. };
  19764. self.removeOption = function(value) {
  19765. if (this.hasOption(value)) {
  19766. delete optionsMap[value];
  19767. if (ngModelCtrl.$viewValue == value) {
  19768. this.renderUnknownOption(value);
  19769. }
  19770. }
  19771. };
  19772. self.renderUnknownOption = function(val) {
  19773. var unknownVal = '? ' + hashKey(val) + ' ?';
  19774. unknownOption.val(unknownVal);
  19775. $element.prepend(unknownOption);
  19776. $element.val(unknownVal);
  19777. unknownOption.prop('selected', true); // needed for IE
  19778. };
  19779. self.hasOption = function(value) {
  19780. return optionsMap.hasOwnProperty(value);
  19781. };
  19782. $scope.$on('$destroy', function() {
  19783. // disable unknown option so that we don't do work when the whole select is being destroyed
  19784. self.renderUnknownOption = noop;
  19785. });
  19786. }],
  19787. link: function(scope, element, attr, ctrls) {
  19788. // if ngModel is not defined, we don't need to do anything
  19789. if (!ctrls[1]) return;
  19790. var selectCtrl = ctrls[0],
  19791. ngModelCtrl = ctrls[1],
  19792. multiple = attr.multiple,
  19793. optionsExp = attr.ngOptions,
  19794. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19795. emptyOption,
  19796. // we can't just jqLite('<option>') since jqLite is not smart enough
  19797. // to create it in <select> and IE barfs otherwise.
  19798. optionTemplate = jqLite(document.createElement('option')),
  19799. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19800. unknownOption = optionTemplate.clone();
  19801. // find "null" option
  19802. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19803. if (children[i].value === '') {
  19804. emptyOption = nullOption = children.eq(i);
  19805. break;
  19806. }
  19807. }
  19808. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19809. // required validator
  19810. if (multiple) {
  19811. ngModelCtrl.$isEmpty = function(value) {
  19812. return !value || value.length === 0;
  19813. };
  19814. }
  19815. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19816. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19817. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19818. ////////////////////////////
  19819. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19820. ngModelCtrl.$render = function() {
  19821. var viewValue = ngModelCtrl.$viewValue;
  19822. if (selectCtrl.hasOption(viewValue)) {
  19823. if (unknownOption.parent()) unknownOption.remove();
  19824. selectElement.val(viewValue);
  19825. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19826. } else {
  19827. if (isUndefined(viewValue) && emptyOption) {
  19828. selectElement.val('');
  19829. } else {
  19830. selectCtrl.renderUnknownOption(viewValue);
  19831. }
  19832. }
  19833. };
  19834. selectElement.on('change', function() {
  19835. scope.$apply(function() {
  19836. if (unknownOption.parent()) unknownOption.remove();
  19837. ngModelCtrl.$setViewValue(selectElement.val());
  19838. });
  19839. });
  19840. }
  19841. function setupAsMultiple(scope, selectElement, ctrl) {
  19842. var lastView;
  19843. ctrl.$render = function() {
  19844. var items = new HashMap(ctrl.$viewValue);
  19845. forEach(selectElement.find('option'), function(option) {
  19846. option.selected = isDefined(items.get(option.value));
  19847. });
  19848. };
  19849. // we have to do it on each watch since ngModel watches reference, but
  19850. // we need to work of an array, so we need to see if anything was inserted/removed
  19851. scope.$watch(function selectMultipleWatch() {
  19852. if (!equals(lastView, ctrl.$viewValue)) {
  19853. lastView = shallowCopy(ctrl.$viewValue);
  19854. ctrl.$render();
  19855. }
  19856. });
  19857. selectElement.on('change', function() {
  19858. scope.$apply(function() {
  19859. var array = [];
  19860. forEach(selectElement.find('option'), function(option) {
  19861. if (option.selected) {
  19862. array.push(option.value);
  19863. }
  19864. });
  19865. ctrl.$setViewValue(array);
  19866. });
  19867. });
  19868. }
  19869. function setupAsOptions(scope, selectElement, ctrl) {
  19870. var match;
  19871. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19872. throw ngOptionsMinErr('iexp',
  19873. "Expected expression in form of " +
  19874. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19875. " but got '{0}'. Element: {1}",
  19876. optionsExp, startingTag(selectElement));
  19877. }
  19878. var displayFn = $parse(match[2] || match[1]),
  19879. valueName = match[4] || match[6],
  19880. keyName = match[5],
  19881. groupByFn = $parse(match[3] || ''),
  19882. valueFn = $parse(match[2] ? match[1] : valueName),
  19883. valuesFn = $parse(match[7]),
  19884. track = match[8],
  19885. trackFn = track ? $parse(match[8]) : null,
  19886. // This is an array of array of existing option groups in DOM.
  19887. // We try to reuse these if possible
  19888. // - optionGroupsCache[0] is the options with no option group
  19889. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19890. optionGroupsCache = [[{element: selectElement, label:''}]];
  19891. if (nullOption) {
  19892. // compile the element since there might be bindings in it
  19893. $compile(nullOption)(scope);
  19894. // remove the class, which is added automatically because we recompile the element and it
  19895. // becomes the compilation root
  19896. nullOption.removeClass('ng-scope');
  19897. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19898. // remove the label from the element. wtf?
  19899. nullOption.remove();
  19900. }
  19901. // clear contents, we'll add what's needed based on the model
  19902. selectElement.empty();
  19903. selectElement.on('change', function() {
  19904. scope.$apply(function() {
  19905. var optionGroup,
  19906. collection = valuesFn(scope) || [],
  19907. locals = {},
  19908. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19909. if (multiple) {
  19910. value = [];
  19911. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19912. groupIndex < groupLength;
  19913. groupIndex++) {
  19914. // list of options for that group. (first item has the parent)
  19915. optionGroup = optionGroupsCache[groupIndex];
  19916. for(index = 1, length = optionGroup.length; index < length; index++) {
  19917. if ((optionElement = optionGroup[index].element)[0].selected) {
  19918. key = optionElement.val();
  19919. if (keyName) locals[keyName] = key;
  19920. if (trackFn) {
  19921. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19922. locals[valueName] = collection[trackIndex];
  19923. if (trackFn(scope, locals) == key) break;
  19924. }
  19925. } else {
  19926. locals[valueName] = collection[key];
  19927. }
  19928. value.push(valueFn(scope, locals));
  19929. }
  19930. }
  19931. }
  19932. } else {
  19933. key = selectElement.val();
  19934. if (key == '?') {
  19935. value = undefined;
  19936. } else if (key === ''){
  19937. value = null;
  19938. } else {
  19939. if (trackFn) {
  19940. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19941. locals[valueName] = collection[trackIndex];
  19942. if (trackFn(scope, locals) == key) {
  19943. value = valueFn(scope, locals);
  19944. break;
  19945. }
  19946. }
  19947. } else {
  19948. locals[valueName] = collection[key];
  19949. if (keyName) locals[keyName] = key;
  19950. value = valueFn(scope, locals);
  19951. }
  19952. }
  19953. }
  19954. ctrl.$setViewValue(value);
  19955. render();
  19956. });
  19957. });
  19958. ctrl.$render = render;
  19959. scope.$watchCollection(valuesFn, render);
  19960. scope.$watchCollection(function () {
  19961. var locals = {},
  19962. values = valuesFn(scope);
  19963. if (values) {
  19964. var toDisplay = new Array(values.length);
  19965. for (var i = 0, ii = values.length; i < ii; i++) {
  19966. locals[valueName] = values[i];
  19967. toDisplay[i] = displayFn(scope, locals);
  19968. }
  19969. return toDisplay;
  19970. }
  19971. }, render);
  19972. if ( multiple ) {
  19973. scope.$watchCollection(function() { return ctrl.$modelValue; }, render);
  19974. }
  19975. function getSelectedSet() {
  19976. var selectedSet = false;
  19977. if (multiple) {
  19978. var modelValue = ctrl.$modelValue;
  19979. if (trackFn && isArray(modelValue)) {
  19980. selectedSet = new HashMap([]);
  19981. var locals = {};
  19982. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19983. locals[valueName] = modelValue[trackIndex];
  19984. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19985. }
  19986. } else {
  19987. selectedSet = new HashMap(modelValue);
  19988. }
  19989. }
  19990. return selectedSet;
  19991. }
  19992. function render() {
  19993. // Temporary location for the option groups before we render them
  19994. var optionGroups = {'':[]},
  19995. optionGroupNames = [''],
  19996. optionGroupName,
  19997. optionGroup,
  19998. option,
  19999. existingParent, existingOptions, existingOption,
  20000. modelValue = ctrl.$modelValue,
  20001. values = valuesFn(scope) || [],
  20002. keys = keyName ? sortedKeys(values) : values,
  20003. key,
  20004. groupLength, length,
  20005. groupIndex, index,
  20006. locals = {},
  20007. selected,
  20008. selectedSet = getSelectedSet(),
  20009. lastElement,
  20010. element,
  20011. label;
  20012. // We now build up the list of options we need (we merge later)
  20013. for (index = 0; length = keys.length, index < length; index++) {
  20014. key = index;
  20015. if (keyName) {
  20016. key = keys[index];
  20017. if ( key.charAt(0) === '$' ) continue;
  20018. locals[keyName] = key;
  20019. }
  20020. locals[valueName] = values[key];
  20021. optionGroupName = groupByFn(scope, locals) || '';
  20022. if (!(optionGroup = optionGroups[optionGroupName])) {
  20023. optionGroup = optionGroups[optionGroupName] = [];
  20024. optionGroupNames.push(optionGroupName);
  20025. }
  20026. if (multiple) {
  20027. selected = isDefined(
  20028. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  20029. );
  20030. } else {
  20031. if (trackFn) {
  20032. var modelCast = {};
  20033. modelCast[valueName] = modelValue;
  20034. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  20035. } else {
  20036. selected = modelValue === valueFn(scope, locals);
  20037. }
  20038. selectedSet = selectedSet || selected; // see if at least one item is selected
  20039. }
  20040. label = displayFn(scope, locals); // what will be seen by the user
  20041. // doing displayFn(scope, locals) || '' overwrites zero values
  20042. label = isDefined(label) ? label : '';
  20043. optionGroup.push({
  20044. // either the index into array or key from object
  20045. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  20046. label: label,
  20047. selected: selected // determine if we should be selected
  20048. });
  20049. }
  20050. if (!multiple) {
  20051. if (nullOption || modelValue === null) {
  20052. // insert null option if we have a placeholder, or the model is null
  20053. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  20054. } else if (!selectedSet) {
  20055. // option could not be found, we have to insert the undefined item
  20056. optionGroups[''].unshift({id:'?', label:'', selected:true});
  20057. }
  20058. }
  20059. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  20060. for (groupIndex = 0, groupLength = optionGroupNames.length;
  20061. groupIndex < groupLength;
  20062. groupIndex++) {
  20063. // current option group name or '' if no group
  20064. optionGroupName = optionGroupNames[groupIndex];
  20065. // list of options for that group. (first item has the parent)
  20066. optionGroup = optionGroups[optionGroupName];
  20067. if (optionGroupsCache.length <= groupIndex) {
  20068. // we need to grow the optionGroups
  20069. existingParent = {
  20070. element: optGroupTemplate.clone().attr('label', optionGroupName),
  20071. label: optionGroup.label
  20072. };
  20073. existingOptions = [existingParent];
  20074. optionGroupsCache.push(existingOptions);
  20075. selectElement.append(existingParent.element);
  20076. } else {
  20077. existingOptions = optionGroupsCache[groupIndex];
  20078. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  20079. // update the OPTGROUP label if not the same.
  20080. if (existingParent.label != optionGroupName) {
  20081. existingParent.element.attr('label', existingParent.label = optionGroupName);
  20082. }
  20083. }
  20084. lastElement = null; // start at the beginning
  20085. for(index = 0, length = optionGroup.length; index < length; index++) {
  20086. option = optionGroup[index];
  20087. if ((existingOption = existingOptions[index+1])) {
  20088. // reuse elements
  20089. lastElement = existingOption.element;
  20090. if (existingOption.label !== option.label) {
  20091. lastElement.text(existingOption.label = option.label);
  20092. lastElement.prop('label', existingOption.label);
  20093. }
  20094. if (existingOption.id !== option.id) {
  20095. lastElement.val(existingOption.id = option.id);
  20096. }
  20097. // lastElement.prop('selected') provided by jQuery has side-effects
  20098. if (lastElement[0].selected !== option.selected) {
  20099. lastElement.prop('selected', (existingOption.selected = option.selected));
  20100. if (msie) {
  20101. // See #7692
  20102. // The selected item wouldn't visually update on IE without this.
  20103. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  20104. lastElement.prop('selected', existingOption.selected);
  20105. }
  20106. }
  20107. } else {
  20108. // grow elements
  20109. // if it's a null option
  20110. if (option.id === '' && nullOption) {
  20111. // put back the pre-compiled element
  20112. element = nullOption;
  20113. } else {
  20114. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  20115. // in this version of jQuery on some browser the .text() returns a string
  20116. // rather then the element.
  20117. (element = optionTemplate.clone())
  20118. .val(option.id)
  20119. .prop('selected', option.selected)
  20120. .attr('selected', option.selected)
  20121. .prop('label', option.label)
  20122. .text(option.label);
  20123. }
  20124. existingOptions.push(existingOption = {
  20125. element: element,
  20126. label: option.label,
  20127. id: option.id,
  20128. selected: option.selected
  20129. });
  20130. selectCtrl.addOption(option.label, element);
  20131. if (lastElement) {
  20132. lastElement.after(element);
  20133. } else {
  20134. existingParent.element.append(element);
  20135. }
  20136. lastElement = element;
  20137. }
  20138. }
  20139. // remove any excessive OPTIONs in a group
  20140. index++; // increment since the existingOptions[0] is parent element not OPTION
  20141. while(existingOptions.length > index) {
  20142. option = existingOptions.pop();
  20143. selectCtrl.removeOption(option.label);
  20144. option.element.remove();
  20145. }
  20146. }
  20147. // remove any excessive OPTGROUPs from select
  20148. while(optionGroupsCache.length > groupIndex) {
  20149. optionGroupsCache.pop()[0].element.remove();
  20150. }
  20151. }
  20152. }
  20153. }
  20154. };
  20155. }];
  20156. var optionDirective = ['$interpolate', function($interpolate) {
  20157. var nullSelectCtrl = {
  20158. addOption: noop,
  20159. removeOption: noop
  20160. };
  20161. return {
  20162. restrict: 'E',
  20163. priority: 100,
  20164. compile: function(element, attr) {
  20165. if (isUndefined(attr.value)) {
  20166. var interpolateFn = $interpolate(element.text(), true);
  20167. if (!interpolateFn) {
  20168. attr.$set('value', element.text());
  20169. }
  20170. }
  20171. return function (scope, element, attr) {
  20172. var selectCtrlName = '$selectController',
  20173. parent = element.parent(),
  20174. selectCtrl = parent.data(selectCtrlName) ||
  20175. parent.parent().data(selectCtrlName); // in case we are in optgroup
  20176. if (selectCtrl && selectCtrl.databound) {
  20177. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  20178. // We don't want the view to drive the initialization of the model anyway.
  20179. element.prop('selected', false);
  20180. } else {
  20181. selectCtrl = nullSelectCtrl;
  20182. }
  20183. if (interpolateFn) {
  20184. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  20185. attr.$set('value', newVal);
  20186. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  20187. selectCtrl.addOption(newVal);
  20188. });
  20189. } else {
  20190. selectCtrl.addOption(attr.value);
  20191. }
  20192. element.on('$destroy', function() {
  20193. selectCtrl.removeOption(attr.value);
  20194. });
  20195. };
  20196. }
  20197. };
  20198. }];
  20199. var styleDirective = valueFn({
  20200. restrict: 'E',
  20201. terminal: true
  20202. });
  20203. if (window.angular.bootstrap) {
  20204. //AngularJS is already loaded, so we can return here...
  20205. console.log('WARNING: Tried to load angular more than once.');
  20206. return;
  20207. }
  20208. //try to bind to jquery now so that one can write angular.element().read()
  20209. //but we will rebind on bootstrap again.
  20210. bindJQuery();
  20211. publishExternalAPI(angular);
  20212. jqLite(document).ready(function() {
  20213. angularInit(document, bootstrap);
  20214. });
  20215. })(window, document);
  20216. !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{display:none !important;}ng\\:form{display:block;}.ng-animate-block-transitions{transition:0s all!important;-webkit-transition:0s all!important;}.ng-hide-add-active,.ng-hide-remove{display:block!important;}</style>');