angular.js 748 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674
  1. /**
  2. * @license AngularJS v1.2.17
  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.17/' +
  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
  77. -angular,
  78. -msie,
  79. -jqLite,
  80. -jQuery,
  81. -slice,
  82. -push,
  83. -toString,
  84. -ngMinErr,
  85. -angularModule,
  86. -nodeName_,
  87. -uid,
  88. -lowercase,
  89. -uppercase,
  90. -manualLowercase,
  91. -manualUppercase,
  92. -nodeName_,
  93. -isArrayLike,
  94. -forEach,
  95. -sortedKeys,
  96. -forEachSorted,
  97. -reverseParams,
  98. -nextUid,
  99. -setHashKey,
  100. -extend,
  101. -int,
  102. -inherit,
  103. -noop,
  104. -identity,
  105. -valueFn,
  106. -isUndefined,
  107. -isDefined,
  108. -isObject,
  109. -isString,
  110. -isNumber,
  111. -isDate,
  112. -isArray,
  113. -isFunction,
  114. -isRegExp,
  115. -isWindow,
  116. -isScope,
  117. -isFile,
  118. -isBlob,
  119. -isBoolean,
  120. -trim,
  121. -isElement,
  122. -makeMap,
  123. -map,
  124. -size,
  125. -includes,
  126. -indexOf,
  127. -arrayRemove,
  128. -isLeafNode,
  129. -copy,
  130. -shallowCopy,
  131. -equals,
  132. -csp,
  133. -concat,
  134. -sliceArgs,
  135. -bind,
  136. -toJsonReplacer,
  137. -toJson,
  138. -fromJson,
  139. -toBoolean,
  140. -startingTag,
  141. -tryDecodeURIComponent,
  142. -parseKeyValue,
  143. -toKeyValue,
  144. -encodeUriSegment,
  145. -encodeUriQuery,
  146. -angularInit,
  147. -bootstrap,
  148. -snake_case,
  149. -bindJQuery,
  150. -assertArg,
  151. -assertArgFn,
  152. -assertNotHasOwnProperty,
  153. -getter,
  154. -getBlockElements,
  155. -hasOwnProperty,
  156. */
  157. ////////////////////////////////////
  158. /**
  159. * @ngdoc module
  160. * @name ng
  161. * @module ng
  162. * @description
  163. *
  164. * # ng (core module)
  165. * The ng module is loaded by default when an AngularJS application is started. The module itself
  166. * contains the essential components for an AngularJS application to function. The table below
  167. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  168. * components available within this core module.
  169. *
  170. * <div doc-module-components="ng"></div>
  171. */
  172. /**
  173. * @ngdoc function
  174. * @name angular.lowercase
  175. * @module ng
  176. * @kind function
  177. *
  178. * @description Converts the specified string to lowercase.
  179. * @param {string} string String to be converted to lowercase.
  180. * @returns {string} Lowercased string.
  181. */
  182. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  183. var hasOwnProperty = Object.prototype.hasOwnProperty;
  184. /**
  185. * @ngdoc function
  186. * @name angular.uppercase
  187. * @module ng
  188. * @kind function
  189. *
  190. * @description Converts the specified string to uppercase.
  191. * @param {string} string String to be converted to uppercase.
  192. * @returns {string} Uppercased string.
  193. */
  194. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  195. var manualLowercase = function(s) {
  196. /* jshint bitwise: false */
  197. return isString(s)
  198. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  199. : s;
  200. };
  201. var manualUppercase = function(s) {
  202. /* jshint bitwise: false */
  203. return isString(s)
  204. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  205. : s;
  206. };
  207. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  208. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  209. // with correct but slower alternatives.
  210. if ('i' !== 'I'.toLowerCase()) {
  211. lowercase = manualLowercase;
  212. uppercase = manualUppercase;
  213. }
  214. var /** holds major version number for IE or NaN for real browsers */
  215. msie,
  216. jqLite, // delay binding since jQuery could be loaded after us.
  217. jQuery, // delay binding
  218. slice = [].slice,
  219. push = [].push,
  220. toString = Object.prototype.toString,
  221. ngMinErr = minErr('ng'),
  222. /** @name angular */
  223. angular = window.angular || (window.angular = {}),
  224. angularModule,
  225. nodeName_,
  226. uid = ['0', '0', '0'];
  227. /**
  228. * IE 11 changed the format of the UserAgent string.
  229. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  230. */
  231. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  232. if (isNaN(msie)) {
  233. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  234. }
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. if (obj == null || isWindow(obj)) {
  243. return false;
  244. }
  245. var length = obj.length;
  246. if (obj.nodeType === 1 && length) {
  247. return true;
  248. }
  249. return isString(obj) || isArray(obj) || length === 0 ||
  250. typeof length === 'number' && length > 0 && (length - 1) in obj;
  251. }
  252. /**
  253. * @ngdoc function
  254. * @name angular.forEach
  255. * @module ng
  256. * @kind function
  257. *
  258. * @description
  259. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  260. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  261. * is the value of an object property or an array element and `key` is the object property key or
  262. * array element index. Specifying a `context` for the function is optional.
  263. *
  264. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  265. * using the `hasOwnProperty` method.
  266. *
  267. ```js
  268. var values = {name: 'misko', gender: 'male'};
  269. var log = [];
  270. angular.forEach(values, function(value, key) {
  271. this.push(key + ': ' + value);
  272. }, log);
  273. expect(log).toEqual(['name: misko', 'gender: male']);
  274. ```
  275. *
  276. * @param {Object|Array} obj Object to iterate over.
  277. * @param {Function} iterator Iterator function.
  278. * @param {Object=} context Object to become context (`this`) for the iterator function.
  279. * @returns {Object|Array} Reference to `obj`.
  280. */
  281. function forEach(obj, iterator, context) {
  282. var key;
  283. if (obj) {
  284. if (isFunction(obj)) {
  285. for (key in obj) {
  286. // Need to check if hasOwnProperty exists,
  287. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  288. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  289. iterator.call(context, obj[key], key);
  290. }
  291. }
  292. } else if (obj.forEach && obj.forEach !== forEach) {
  293. obj.forEach(iterator, context);
  294. } else if (isArrayLike(obj)) {
  295. for (key = 0; key < obj.length; key++)
  296. iterator.call(context, obj[key], key);
  297. } else {
  298. for (key in obj) {
  299. if (obj.hasOwnProperty(key)) {
  300. iterator.call(context, obj[key], key);
  301. }
  302. }
  303. }
  304. }
  305. return obj;
  306. }
  307. function sortedKeys(obj) {
  308. var keys = [];
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. keys.push(key);
  312. }
  313. }
  314. return keys.sort();
  315. }
  316. function forEachSorted(obj, iterator, context) {
  317. var keys = sortedKeys(obj);
  318. for ( var i = 0; i < keys.length; i++) {
  319. iterator.call(context, obj[keys[i]], keys[i]);
  320. }
  321. return keys;
  322. }
  323. /**
  324. * when using forEach the params are value, key, but it is often useful to have key, value.
  325. * @param {function(string, *)} iteratorFn
  326. * @returns {function(*, string)}
  327. */
  328. function reverseParams(iteratorFn) {
  329. return function(value, key) { iteratorFn(key, value); };
  330. }
  331. /**
  332. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  333. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  334. * the number string gets longer over time, and it can also overflow, where as the nextId
  335. * will grow much slower, it is a string, and it will never overflow.
  336. *
  337. * @returns {string} an unique alpha-numeric string
  338. */
  339. function nextUid() {
  340. var index = uid.length;
  341. var digit;
  342. while(index) {
  343. index--;
  344. digit = uid[index].charCodeAt(0);
  345. if (digit == 57 /*'9'*/) {
  346. uid[index] = 'A';
  347. return uid.join('');
  348. }
  349. if (digit == 90 /*'Z'*/) {
  350. uid[index] = '0';
  351. } else {
  352. uid[index] = String.fromCharCode(digit + 1);
  353. return uid.join('');
  354. }
  355. }
  356. uid.unshift('0');
  357. return uid.join('');
  358. }
  359. /**
  360. * Set or clear the hashkey for an object.
  361. * @param obj object
  362. * @param h the hashkey (!truthy to delete the hashkey)
  363. */
  364. function setHashKey(obj, h) {
  365. if (h) {
  366. obj.$$hashKey = h;
  367. }
  368. else {
  369. delete obj.$$hashKey;
  370. }
  371. }
  372. /**
  373. * @ngdoc function
  374. * @name angular.extend
  375. * @module ng
  376. * @kind function
  377. *
  378. * @description
  379. * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
  380. * to `dst`. You can specify multiple `src` objects.
  381. *
  382. * @param {Object} dst Destination object.
  383. * @param {...Object} src Source object(s).
  384. * @returns {Object} Reference to `dst`.
  385. */
  386. function extend(dst) {
  387. var h = dst.$$hashKey;
  388. forEach(arguments, function(obj) {
  389. if (obj !== dst) {
  390. forEach(obj, function(value, key) {
  391. dst[key] = value;
  392. });
  393. }
  394. });
  395. setHashKey(dst,h);
  396. return dst;
  397. }
  398. function int(str) {
  399. return parseInt(str, 10);
  400. }
  401. function inherit(parent, extra) {
  402. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  403. }
  404. /**
  405. * @ngdoc function
  406. * @name angular.noop
  407. * @module ng
  408. * @kind function
  409. *
  410. * @description
  411. * A function that performs no operations. This function can be useful when writing code in the
  412. * functional style.
  413. ```js
  414. function foo(callback) {
  415. var result = calculateResult();
  416. (callback || angular.noop)(result);
  417. }
  418. ```
  419. */
  420. function noop() {}
  421. noop.$inject = [];
  422. /**
  423. * @ngdoc function
  424. * @name angular.identity
  425. * @module ng
  426. * @kind function
  427. *
  428. * @description
  429. * A function that returns its first argument. This function is useful when writing code in the
  430. * functional style.
  431. *
  432. ```js
  433. function transformer(transformationFn, value) {
  434. return (transformationFn || angular.identity)(value);
  435. };
  436. ```
  437. */
  438. function identity($) {return $;}
  439. identity.$inject = [];
  440. function valueFn(value) {return function() {return value;};}
  441. /**
  442. * @ngdoc function
  443. * @name angular.isUndefined
  444. * @module ng
  445. * @kind function
  446. *
  447. * @description
  448. * Determines if a reference is undefined.
  449. *
  450. * @param {*} value Reference to check.
  451. * @returns {boolean} True if `value` is undefined.
  452. */
  453. function isUndefined(value){return typeof value === 'undefined';}
  454. /**
  455. * @ngdoc function
  456. * @name angular.isDefined
  457. * @module ng
  458. * @kind function
  459. *
  460. * @description
  461. * Determines if a reference is defined.
  462. *
  463. * @param {*} value Reference to check.
  464. * @returns {boolean} True if `value` is defined.
  465. */
  466. function isDefined(value){return typeof value !== 'undefined';}
  467. /**
  468. * @ngdoc function
  469. * @name angular.isObject
  470. * @module ng
  471. * @kind function
  472. *
  473. * @description
  474. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  475. * considered to be objects. Note that JavaScript arrays are objects.
  476. *
  477. * @param {*} value Reference to check.
  478. * @returns {boolean} True if `value` is an `Object` but not `null`.
  479. */
  480. function isObject(value){return value != null && typeof value === 'object';}
  481. /**
  482. * @ngdoc function
  483. * @name angular.isString
  484. * @module ng
  485. * @kind function
  486. *
  487. * @description
  488. * Determines if a reference is a `String`.
  489. *
  490. * @param {*} value Reference to check.
  491. * @returns {boolean} True if `value` is a `String`.
  492. */
  493. function isString(value){return typeof value === 'string';}
  494. /**
  495. * @ngdoc function
  496. * @name angular.isNumber
  497. * @module ng
  498. * @kind function
  499. *
  500. * @description
  501. * Determines if a reference is a `Number`.
  502. *
  503. * @param {*} value Reference to check.
  504. * @returns {boolean} True if `value` is a `Number`.
  505. */
  506. function isNumber(value){return typeof value === 'number';}
  507. /**
  508. * @ngdoc function
  509. * @name angular.isDate
  510. * @module ng
  511. * @kind function
  512. *
  513. * @description
  514. * Determines if a value is a date.
  515. *
  516. * @param {*} value Reference to check.
  517. * @returns {boolean} True if `value` is a `Date`.
  518. */
  519. function isDate(value) {
  520. return toString.call(value) === '[object Date]';
  521. }
  522. /**
  523. * @ngdoc function
  524. * @name angular.isArray
  525. * @module ng
  526. * @kind function
  527. *
  528. * @description
  529. * Determines if a reference is an `Array`.
  530. *
  531. * @param {*} value Reference to check.
  532. * @returns {boolean} True if `value` is an `Array`.
  533. */
  534. function isArray(value) {
  535. return toString.call(value) === '[object Array]';
  536. }
  537. /**
  538. * @ngdoc function
  539. * @name angular.isFunction
  540. * @module ng
  541. * @kind function
  542. *
  543. * @description
  544. * Determines if a reference is a `Function`.
  545. *
  546. * @param {*} value Reference to check.
  547. * @returns {boolean} True if `value` is a `Function`.
  548. */
  549. function isFunction(value){return typeof value === 'function';}
  550. /**
  551. * Determines if a value is a regular expression object.
  552. *
  553. * @private
  554. * @param {*} value Reference to check.
  555. * @returns {boolean} True if `value` is a `RegExp`.
  556. */
  557. function isRegExp(value) {
  558. return toString.call(value) === '[object RegExp]';
  559. }
  560. /**
  561. * Checks if `obj` is a window object.
  562. *
  563. * @private
  564. * @param {*} obj Object to check
  565. * @returns {boolean} True if `obj` is a window obj.
  566. */
  567. function isWindow(obj) {
  568. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  569. }
  570. function isScope(obj) {
  571. return obj && obj.$evalAsync && obj.$watch;
  572. }
  573. function isFile(obj) {
  574. return toString.call(obj) === '[object File]';
  575. }
  576. function isBlob(obj) {
  577. return toString.call(obj) === '[object Blob]';
  578. }
  579. function isBoolean(value) {
  580. return typeof value === 'boolean';
  581. }
  582. var trim = (function() {
  583. // native trim is way faster: http://jsperf.com/angular-trim-test
  584. // but IE doesn't have it... :-(
  585. // TODO: we should move this into IE/ES5 polyfill
  586. if (!String.prototype.trim) {
  587. return function(value) {
  588. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  589. };
  590. }
  591. return function(value) {
  592. return isString(value) ? value.trim() : value;
  593. };
  594. })();
  595. /**
  596. * @ngdoc function
  597. * @name angular.isElement
  598. * @module ng
  599. * @kind function
  600. *
  601. * @description
  602. * Determines if a reference is a DOM element (or wrapped jQuery element).
  603. *
  604. * @param {*} value Reference to check.
  605. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  606. */
  607. function isElement(node) {
  608. return !!(node &&
  609. (node.nodeName // we are a direct element
  610. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  611. }
  612. /**
  613. * @param str 'key1,key2,...'
  614. * @returns {object} in the form of {key1:true, key2:true, ...}
  615. */
  616. function makeMap(str) {
  617. var obj = {}, items = str.split(","), i;
  618. for ( i = 0; i < items.length; i++ )
  619. obj[ items[i] ] = true;
  620. return obj;
  621. }
  622. if (msie < 9) {
  623. nodeName_ = function(element) {
  624. element = element.nodeName ? element : element[0];
  625. return (element.scopeName && element.scopeName != 'HTML')
  626. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  627. };
  628. } else {
  629. nodeName_ = function(element) {
  630. return element.nodeName ? element.nodeName : element[0].nodeName;
  631. };
  632. }
  633. function map(obj, iterator, context) {
  634. var results = [];
  635. forEach(obj, function(value, index, list) {
  636. results.push(iterator.call(context, value, index, list));
  637. });
  638. return results;
  639. }
  640. /**
  641. * @description
  642. * Determines the number of elements in an array, the number of properties an object has, or
  643. * the length of a string.
  644. *
  645. * Note: This function is used to augment the Object type in Angular expressions. See
  646. * {@link angular.Object} for more information about Angular arrays.
  647. *
  648. * @param {Object|Array|string} obj Object, array, or string to inspect.
  649. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  650. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  651. */
  652. function size(obj, ownPropsOnly) {
  653. var count = 0, key;
  654. if (isArray(obj) || isString(obj)) {
  655. return obj.length;
  656. } else if (isObject(obj)) {
  657. for (key in obj)
  658. if (!ownPropsOnly || obj.hasOwnProperty(key))
  659. count++;
  660. }
  661. return count;
  662. }
  663. function includes(array, obj) {
  664. return indexOf(array, obj) != -1;
  665. }
  666. function indexOf(array, obj) {
  667. if (array.indexOf) return array.indexOf(obj);
  668. for (var i = 0; i < array.length; i++) {
  669. if (obj === array[i]) return i;
  670. }
  671. return -1;
  672. }
  673. function arrayRemove(array, value) {
  674. var index = indexOf(array, value);
  675. if (index >=0)
  676. array.splice(index, 1);
  677. return value;
  678. }
  679. function isLeafNode (node) {
  680. if (node) {
  681. switch (node.nodeName) {
  682. case "OPTION":
  683. case "PRE":
  684. case "TITLE":
  685. return true;
  686. }
  687. }
  688. return false;
  689. }
  690. /**
  691. * @ngdoc function
  692. * @name angular.copy
  693. * @module ng
  694. * @kind function
  695. *
  696. * @description
  697. * Creates a deep copy of `source`, which should be an object or an array.
  698. *
  699. * * If no destination is supplied, a copy of the object or array is created.
  700. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  701. * are deleted and then all elements/properties from the source are copied to it.
  702. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  703. * * If `source` is identical to 'destination' an exception will be thrown.
  704. *
  705. * @param {*} source The source that will be used to make a copy.
  706. * Can be any type, including primitives, `null`, and `undefined`.
  707. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  708. * provided, must be of the same type as `source`.
  709. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  710. *
  711. * @example
  712. <example>
  713. <file name="index.html">
  714. <div ng-controller="Controller">
  715. <form novalidate class="simple-form">
  716. Name: <input type="text" ng-model="user.name" /><br />
  717. E-mail: <input type="email" ng-model="user.email" /><br />
  718. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  719. <input type="radio" ng-model="user.gender" value="female" />female<br />
  720. <button ng-click="reset()">RESET</button>
  721. <button ng-click="update(user)">SAVE</button>
  722. </form>
  723. <pre>form = {{user | json}}</pre>
  724. <pre>master = {{master | json}}</pre>
  725. </div>
  726. <script>
  727. function Controller($scope) {
  728. $scope.master= {};
  729. $scope.update = function(user) {
  730. // Example with 1 argument
  731. $scope.master= angular.copy(user);
  732. };
  733. $scope.reset = function() {
  734. // Example with 2 arguments
  735. angular.copy($scope.master, $scope.user);
  736. };
  737. $scope.reset();
  738. }
  739. </script>
  740. </file>
  741. </example>
  742. */
  743. function copy(source, destination, stackSource, stackDest) {
  744. if (isWindow(source) || isScope(source)) {
  745. throw ngMinErr('cpws',
  746. "Can't copy! Making copies of Window or Scope instances is not supported.");
  747. }
  748. if (!destination) {
  749. destination = source;
  750. if (source) {
  751. if (isArray(source)) {
  752. destination = copy(source, [], stackSource, stackDest);
  753. } else if (isDate(source)) {
  754. destination = new Date(source.getTime());
  755. } else if (isRegExp(source)) {
  756. destination = new RegExp(source.source);
  757. } else if (isObject(source)) {
  758. destination = copy(source, {}, stackSource, stackDest);
  759. }
  760. }
  761. } else {
  762. if (source === destination) throw ngMinErr('cpi',
  763. "Can't copy! Source and destination are identical.");
  764. stackSource = stackSource || [];
  765. stackDest = stackDest || [];
  766. if (isObject(source)) {
  767. var index = indexOf(stackSource, source);
  768. if (index !== -1) return stackDest[index];
  769. stackSource.push(source);
  770. stackDest.push(destination);
  771. }
  772. var result;
  773. if (isArray(source)) {
  774. destination.length = 0;
  775. for ( var i = 0; i < source.length; i++) {
  776. result = copy(source[i], null, stackSource, stackDest);
  777. if (isObject(source[i])) {
  778. stackSource.push(source[i]);
  779. stackDest.push(result);
  780. }
  781. destination.push(result);
  782. }
  783. } else {
  784. var h = destination.$$hashKey;
  785. forEach(destination, function(value, key) {
  786. delete destination[key];
  787. });
  788. for ( var key in source) {
  789. result = copy(source[key], null, stackSource, stackDest);
  790. if (isObject(source[key])) {
  791. stackSource.push(source[key]);
  792. stackDest.push(result);
  793. }
  794. destination[key] = result;
  795. }
  796. setHashKey(destination,h);
  797. }
  798. }
  799. return destination;
  800. }
  801. /**
  802. * Creates a shallow copy of an object, an array or a primitive
  803. */
  804. function shallowCopy(src, dst) {
  805. if (isArray(src)) {
  806. dst = dst || [];
  807. for ( var i = 0; i < src.length; i++) {
  808. dst[i] = src[i];
  809. }
  810. } else if (isObject(src)) {
  811. dst = dst || {};
  812. for (var key in src) {
  813. if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  814. dst[key] = src[key];
  815. }
  816. }
  817. }
  818. return dst || src;
  819. }
  820. /**
  821. * @ngdoc function
  822. * @name angular.equals
  823. * @module ng
  824. * @kind function
  825. *
  826. * @description
  827. * Determines if two objects or two values are equivalent. Supports value types, regular
  828. * expressions, arrays and objects.
  829. *
  830. * Two objects or values are considered equivalent if at least one of the following is true:
  831. *
  832. * * Both objects or values pass `===` comparison.
  833. * * Both objects or values are of the same type and all of their properties are equal by
  834. * comparing them with `angular.equals`.
  835. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  836. * * Both values represent the same regular expression (In JavaScript,
  837. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  838. * representation matches).
  839. *
  840. * During a property comparison, properties of `function` type and properties with names
  841. * that begin with `$` are ignored.
  842. *
  843. * Scope and DOMWindow objects are being compared only by identify (`===`).
  844. *
  845. * @param {*} o1 Object or value to compare.
  846. * @param {*} o2 Object or value to compare.
  847. * @returns {boolean} True if arguments are equal.
  848. */
  849. function equals(o1, o2) {
  850. if (o1 === o2) return true;
  851. if (o1 === null || o2 === null) return false;
  852. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  853. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  854. if (t1 == t2) {
  855. if (t1 == 'object') {
  856. if (isArray(o1)) {
  857. if (!isArray(o2)) return false;
  858. if ((length = o1.length) == o2.length) {
  859. for(key=0; key<length; key++) {
  860. if (!equals(o1[key], o2[key])) return false;
  861. }
  862. return true;
  863. }
  864. } else if (isDate(o1)) {
  865. return isDate(o2) && o1.getTime() == o2.getTime();
  866. } else if (isRegExp(o1) && isRegExp(o2)) {
  867. return o1.toString() == o2.toString();
  868. } else {
  869. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  870. keySet = {};
  871. for(key in o1) {
  872. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  873. if (!equals(o1[key], o2[key])) return false;
  874. keySet[key] = true;
  875. }
  876. for(key in o2) {
  877. if (!keySet.hasOwnProperty(key) &&
  878. key.charAt(0) !== '$' &&
  879. o2[key] !== undefined &&
  880. !isFunction(o2[key])) return false;
  881. }
  882. return true;
  883. }
  884. }
  885. }
  886. return false;
  887. }
  888. function csp() {
  889. return (document.securityPolicy && document.securityPolicy.isActive) ||
  890. (document.querySelector &&
  891. !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
  892. }
  893. function concat(array1, array2, index) {
  894. return array1.concat(slice.call(array2, index));
  895. }
  896. function sliceArgs(args, startIndex) {
  897. return slice.call(args, startIndex || 0);
  898. }
  899. /* jshint -W101 */
  900. /**
  901. * @ngdoc function
  902. * @name angular.bind
  903. * @module ng
  904. * @kind function
  905. *
  906. * @description
  907. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  908. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  909. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  910. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  911. *
  912. * @param {Object} self Context which `fn` should be evaluated in.
  913. * @param {function()} fn Function to be bound.
  914. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  915. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  916. */
  917. /* jshint +W101 */
  918. function bind(self, fn) {
  919. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  920. if (isFunction(fn) && !(fn instanceof RegExp)) {
  921. return curryArgs.length
  922. ? function() {
  923. return arguments.length
  924. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  925. : fn.apply(self, curryArgs);
  926. }
  927. : function() {
  928. return arguments.length
  929. ? fn.apply(self, arguments)
  930. : fn.call(self);
  931. };
  932. } else {
  933. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  934. return fn;
  935. }
  936. }
  937. function toJsonReplacer(key, value) {
  938. var val = value;
  939. if (typeof key === 'string' && key.charAt(0) === '$') {
  940. val = undefined;
  941. } else if (isWindow(value)) {
  942. val = '$WINDOW';
  943. } else if (value && document === value) {
  944. val = '$DOCUMENT';
  945. } else if (isScope(value)) {
  946. val = '$SCOPE';
  947. }
  948. return val;
  949. }
  950. /**
  951. * @ngdoc function
  952. * @name angular.toJson
  953. * @module ng
  954. * @kind function
  955. *
  956. * @description
  957. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  958. * stripped since angular uses this notation internally.
  959. *
  960. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  961. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  962. * @returns {string|undefined} JSON-ified string representing `obj`.
  963. */
  964. function toJson(obj, pretty) {
  965. if (typeof obj === 'undefined') return undefined;
  966. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  967. }
  968. /**
  969. * @ngdoc function
  970. * @name angular.fromJson
  971. * @module ng
  972. * @kind function
  973. *
  974. * @description
  975. * Deserializes a JSON string.
  976. *
  977. * @param {string} json JSON string to deserialize.
  978. * @returns {Object|Array|string|number} Deserialized thingy.
  979. */
  980. function fromJson(json) {
  981. return isString(json)
  982. ? JSON.parse(json)
  983. : json;
  984. }
  985. function toBoolean(value) {
  986. if (typeof value === 'function') {
  987. value = true;
  988. } else if (value && value.length !== 0) {
  989. var v = lowercase("" + value);
  990. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  991. } else {
  992. value = false;
  993. }
  994. return value;
  995. }
  996. /**
  997. * @returns {string} Returns the string representation of the element.
  998. */
  999. function startingTag(element) {
  1000. element = jqLite(element).clone();
  1001. try {
  1002. // turns out IE does not let you set .html() on elements which
  1003. // are not allowed to have children. So we just ignore it.
  1004. element.empty();
  1005. } catch(e) {}
  1006. // As Per DOM Standards
  1007. var TEXT_NODE = 3;
  1008. var elemHtml = jqLite('<div>').append(element).html();
  1009. try {
  1010. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  1011. elemHtml.
  1012. match(/^(<[^>]+>)/)[1].
  1013. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1014. } catch(e) {
  1015. return lowercase(elemHtml);
  1016. }
  1017. }
  1018. /////////////////////////////////////////////////
  1019. /**
  1020. * Tries to decode the URI component without throwing an exception.
  1021. *
  1022. * @private
  1023. * @param str value potential URI component to check.
  1024. * @returns {boolean} True if `value` can be decoded
  1025. * with the decodeURIComponent function.
  1026. */
  1027. function tryDecodeURIComponent(value) {
  1028. try {
  1029. return decodeURIComponent(value);
  1030. } catch(e) {
  1031. // Ignore any invalid uri component
  1032. }
  1033. }
  1034. /**
  1035. * Parses an escaped url query string into key-value pairs.
  1036. * @returns {Object.<string,boolean|Array>}
  1037. */
  1038. function parseKeyValue(/**string*/keyValue) {
  1039. var obj = {}, key_value, key;
  1040. forEach((keyValue || "").split('&'), function(keyValue) {
  1041. if ( keyValue ) {
  1042. key_value = keyValue.split('=');
  1043. key = tryDecodeURIComponent(key_value[0]);
  1044. if ( isDefined(key) ) {
  1045. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1046. if (!obj[key]) {
  1047. obj[key] = val;
  1048. } else if(isArray(obj[key])) {
  1049. obj[key].push(val);
  1050. } else {
  1051. obj[key] = [obj[key],val];
  1052. }
  1053. }
  1054. }
  1055. });
  1056. return obj;
  1057. }
  1058. function toKeyValue(obj) {
  1059. var parts = [];
  1060. forEach(obj, function(value, key) {
  1061. if (isArray(value)) {
  1062. forEach(value, function(arrayValue) {
  1063. parts.push(encodeUriQuery(key, true) +
  1064. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1065. });
  1066. } else {
  1067. parts.push(encodeUriQuery(key, true) +
  1068. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1069. }
  1070. });
  1071. return parts.length ? parts.join('&') : '';
  1072. }
  1073. /**
  1074. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1075. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1076. * segments:
  1077. * segment = *pchar
  1078. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1079. * pct-encoded = "%" HEXDIG HEXDIG
  1080. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1081. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1082. * / "*" / "+" / "," / ";" / "="
  1083. */
  1084. function encodeUriSegment(val) {
  1085. return encodeUriQuery(val, true).
  1086. replace(/%26/gi, '&').
  1087. replace(/%3D/gi, '=').
  1088. replace(/%2B/gi, '+');
  1089. }
  1090. /**
  1091. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1092. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1093. * encoded per http://tools.ietf.org/html/rfc3986:
  1094. * query = *( pchar / "/" / "?" )
  1095. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1096. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1097. * pct-encoded = "%" HEXDIG HEXDIG
  1098. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1099. * / "*" / "+" / "," / ";" / "="
  1100. */
  1101. function encodeUriQuery(val, pctEncodeSpaces) {
  1102. return encodeURIComponent(val).
  1103. replace(/%40/gi, '@').
  1104. replace(/%3A/gi, ':').
  1105. replace(/%24/g, '$').
  1106. replace(/%2C/gi, ',').
  1107. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1108. }
  1109. /**
  1110. * @ngdoc directive
  1111. * @name ngApp
  1112. * @module ng
  1113. *
  1114. * @element ANY
  1115. * @param {angular.Module} ngApp an optional application
  1116. * {@link angular.module module} name to load.
  1117. *
  1118. * @description
  1119. *
  1120. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1121. * designates the **root element** of the application and is typically placed near the root element
  1122. * of the page - e.g. on the `<body>` or `<html>` tags.
  1123. *
  1124. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1125. * found in the document will be used to define the root element to auto-bootstrap as an
  1126. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1127. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1128. *
  1129. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1130. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1131. * should contain the application code needed or have dependencies on other modules that will
  1132. * contain the code. See {@link angular.module} for more information.
  1133. *
  1134. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1135. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1136. * would not be resolved to `3`.
  1137. *
  1138. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1139. *
  1140. <example module="ngAppDemo">
  1141. <file name="index.html">
  1142. <div ng-controller="ngAppDemoController">
  1143. I can add: {{a}} + {{b}} = {{ a+b }}
  1144. </div>
  1145. </file>
  1146. <file name="script.js">
  1147. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1148. $scope.a = 1;
  1149. $scope.b = 2;
  1150. });
  1151. </file>
  1152. </example>
  1153. *
  1154. */
  1155. function angularInit(element, bootstrap) {
  1156. var elements = [element],
  1157. appElement,
  1158. module,
  1159. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1160. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1161. function append(element) {
  1162. element && elements.push(element);
  1163. }
  1164. forEach(names, function(name) {
  1165. names[name] = true;
  1166. append(document.getElementById(name));
  1167. name = name.replace(':', '\\:');
  1168. if (element.querySelectorAll) {
  1169. forEach(element.querySelectorAll('.' + name), append);
  1170. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1171. forEach(element.querySelectorAll('[' + name + ']'), append);
  1172. }
  1173. });
  1174. forEach(elements, function(element) {
  1175. if (!appElement) {
  1176. var className = ' ' + element.className + ' ';
  1177. var match = NG_APP_CLASS_REGEXP.exec(className);
  1178. if (match) {
  1179. appElement = element;
  1180. module = (match[2] || '').replace(/\s+/g, ',');
  1181. } else {
  1182. forEach(element.attributes, function(attr) {
  1183. if (!appElement && names[attr.name]) {
  1184. appElement = element;
  1185. module = attr.value;
  1186. }
  1187. });
  1188. }
  1189. }
  1190. });
  1191. if (appElement) {
  1192. bootstrap(appElement, module ? [module] : []);
  1193. }
  1194. }
  1195. /**
  1196. * @ngdoc function
  1197. * @name angular.bootstrap
  1198. * @module ng
  1199. * @description
  1200. * Use this function to manually start up angular application.
  1201. *
  1202. * See: {@link guide/bootstrap Bootstrap}
  1203. *
  1204. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1205. * They must use {@link ng.directive:ngApp ngApp}.
  1206. *
  1207. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1208. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1209. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1210. * multiple instances of Angular try to work on the DOM.
  1211. *
  1212. * <example name="multi-bootstrap" module="multi-bootstrap">
  1213. * <file name="index.html">
  1214. * <script src="../../../angular.js"></script>
  1215. * <div ng-controller="BrokenTable">
  1216. * <table>
  1217. * <tr>
  1218. * <th ng-repeat="heading in headings">{{heading}}</th>
  1219. * </tr>
  1220. * <tr ng-repeat="filling in fillings">
  1221. * <td ng-repeat="fill in filling">{{fill}}</td>
  1222. * </tr>
  1223. * </table>
  1224. * </div>
  1225. * </file>
  1226. * <file name="controller.js">
  1227. * var app = angular.module('multi-bootstrap', [])
  1228. *
  1229. * .controller('BrokenTable', function($scope) {
  1230. * $scope.headings = ['One', 'Two', 'Three'];
  1231. * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
  1232. * });
  1233. * </file>
  1234. * <file name="protractor.js" type="protractor">
  1235. * it('should only insert one table cell for each item in $scope.fillings', function() {
  1236. * expect(element.all(by.css('td')).count())
  1237. * .toBe(9);
  1238. * });
  1239. * </file>
  1240. * </example>
  1241. *
  1242. * @param {DOMElement} element DOM element which is the root of angular application.
  1243. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1244. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1245. * function that will be invoked by the injector as a run block.
  1246. * See: {@link angular.module modules}
  1247. * @returns {auto.$injector} Returns the newly created injector for this app.
  1248. */
  1249. function bootstrap(element, modules) {
  1250. var doBootstrap = function() {
  1251. element = jqLite(element);
  1252. if (element.injector()) {
  1253. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1254. throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
  1255. }
  1256. modules = modules || [];
  1257. modules.unshift(['$provide', function($provide) {
  1258. $provide.value('$rootElement', element);
  1259. }]);
  1260. modules.unshift('ng');
  1261. var injector = createInjector(modules);
  1262. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1263. function(scope, element, compile, injector, animate) {
  1264. scope.$apply(function() {
  1265. element.data('$injector', injector);
  1266. compile(element)(scope);
  1267. });
  1268. }]
  1269. );
  1270. return injector;
  1271. };
  1272. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1273. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1274. return doBootstrap();
  1275. }
  1276. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1277. angular.resumeBootstrap = function(extraModules) {
  1278. forEach(extraModules, function(module) {
  1279. modules.push(module);
  1280. });
  1281. doBootstrap();
  1282. };
  1283. }
  1284. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1285. function snake_case(name, separator) {
  1286. separator = separator || '_';
  1287. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1288. return (pos ? separator : '') + letter.toLowerCase();
  1289. });
  1290. }
  1291. function bindJQuery() {
  1292. // bind to jQuery if present;
  1293. jQuery = window.jQuery;
  1294. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1295. // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support.
  1296. if (jQuery && jQuery.fn.on) {
  1297. jqLite = jQuery;
  1298. extend(jQuery.fn, {
  1299. scope: JQLitePrototype.scope,
  1300. isolateScope: JQLitePrototype.isolateScope,
  1301. controller: JQLitePrototype.controller,
  1302. injector: JQLitePrototype.injector,
  1303. inheritedData: JQLitePrototype.inheritedData
  1304. });
  1305. // Method signature:
  1306. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1307. jqLitePatchJQueryRemove('remove', true, true, false);
  1308. jqLitePatchJQueryRemove('empty', false, false, false);
  1309. jqLitePatchJQueryRemove('html', false, false, true);
  1310. } else {
  1311. jqLite = JQLite;
  1312. }
  1313. angular.element = jqLite;
  1314. }
  1315. /**
  1316. * throw error if the argument is falsy.
  1317. */
  1318. function assertArg(arg, name, reason) {
  1319. if (!arg) {
  1320. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1321. }
  1322. return arg;
  1323. }
  1324. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1325. if (acceptArrayAnnotation && isArray(arg)) {
  1326. arg = arg[arg.length - 1];
  1327. }
  1328. assertArg(isFunction(arg), name, 'not a function, got ' +
  1329. (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1330. return arg;
  1331. }
  1332. /**
  1333. * throw error if the name given is hasOwnProperty
  1334. * @param {String} name the name to test
  1335. * @param {String} context the context in which the name is used, such as module or directive
  1336. */
  1337. function assertNotHasOwnProperty(name, context) {
  1338. if (name === 'hasOwnProperty') {
  1339. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1340. }
  1341. }
  1342. /**
  1343. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1344. * @param {Object} obj starting object
  1345. * @param {String} path path to traverse
  1346. * @param {boolean} [bindFnToScope=true]
  1347. * @returns {Object} value as accessible by path
  1348. */
  1349. //TODO(misko): this function needs to be removed
  1350. function getter(obj, path, bindFnToScope) {
  1351. if (!path) return obj;
  1352. var keys = path.split('.');
  1353. var key;
  1354. var lastInstance = obj;
  1355. var len = keys.length;
  1356. for (var i = 0; i < len; i++) {
  1357. key = keys[i];
  1358. if (obj) {
  1359. obj = (lastInstance = obj)[key];
  1360. }
  1361. }
  1362. if (!bindFnToScope && isFunction(obj)) {
  1363. return bind(lastInstance, obj);
  1364. }
  1365. return obj;
  1366. }
  1367. /**
  1368. * Return the DOM siblings between the first and last node in the given array.
  1369. * @param {Array} array like object
  1370. * @returns {DOMElement} object containing the elements
  1371. */
  1372. function getBlockElements(nodes) {
  1373. var startNode = nodes[0],
  1374. endNode = nodes[nodes.length - 1];
  1375. if (startNode === endNode) {
  1376. return jqLite(startNode);
  1377. }
  1378. var element = startNode;
  1379. var elements = [element];
  1380. do {
  1381. element = element.nextSibling;
  1382. if (!element) break;
  1383. elements.push(element);
  1384. } while (element !== endNode);
  1385. return jqLite(elements);
  1386. }
  1387. /**
  1388. * @ngdoc type
  1389. * @name angular.Module
  1390. * @module ng
  1391. * @description
  1392. *
  1393. * Interface for configuring angular {@link angular.module modules}.
  1394. */
  1395. function setupModuleLoader(window) {
  1396. var $injectorMinErr = minErr('$injector');
  1397. var ngMinErr = minErr('ng');
  1398. function ensure(obj, name, factory) {
  1399. return obj[name] || (obj[name] = factory());
  1400. }
  1401. var angular = ensure(window, 'angular', Object);
  1402. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1403. angular.$$minErr = angular.$$minErr || minErr;
  1404. return ensure(angular, 'module', function() {
  1405. /** @type {Object.<string, angular.Module>} */
  1406. var modules = {};
  1407. /**
  1408. * @ngdoc function
  1409. * @name angular.module
  1410. * @module ng
  1411. * @description
  1412. *
  1413. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1414. * modules.
  1415. * All modules (angular core or 3rd party) that should be available to an application must be
  1416. * registered using this mechanism.
  1417. *
  1418. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1419. * existing module (the name passed as the first argument to `module`) is retrieved.
  1420. *
  1421. *
  1422. * # Module
  1423. *
  1424. * A module is a collection of services, directives, filters, and configuration information.
  1425. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1426. *
  1427. * ```js
  1428. * // Create a new module
  1429. * var myModule = angular.module('myModule', []);
  1430. *
  1431. * // register a new service
  1432. * myModule.value('appName', 'MyCoolApp');
  1433. *
  1434. * // configure existing services inside initialization blocks.
  1435. * myModule.config(['$locationProvider', function($locationProvider) {
  1436. * // Configure existing providers
  1437. * $locationProvider.hashPrefix('!');
  1438. * }]);
  1439. * ```
  1440. *
  1441. * Then you can create an injector and load your modules like this:
  1442. *
  1443. * ```js
  1444. * var injector = angular.injector(['ng', 'myModule'])
  1445. * ```
  1446. *
  1447. * However it's more likely that you'll just use
  1448. * {@link ng.directive:ngApp ngApp} or
  1449. * {@link angular.bootstrap} to simplify this process for you.
  1450. *
  1451. * @param {!string} name The name of the module to create or retrieve.
  1452. <<<<<* @param {!Array.<string>=} requires If specified then new module is being created. If
  1453. >>>>>* unspecified then the module is being retrieved for further configuration.
  1454. * @param {Function} configFn Optional configuration function for the module. Same as
  1455. * {@link angular.Module#config Module#config()}.
  1456. * @returns {module} new module with the {@link angular.Module} api.
  1457. */
  1458. return function module(name, requires, configFn) {
  1459. var assertNotHasOwnProperty = function(name, context) {
  1460. if (name === 'hasOwnProperty') {
  1461. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1462. }
  1463. };
  1464. assertNotHasOwnProperty(name, 'module');
  1465. if (requires && modules.hasOwnProperty(name)) {
  1466. modules[name] = null;
  1467. }
  1468. return ensure(modules, name, function() {
  1469. if (!requires) {
  1470. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1471. "the module name or forgot to load it. If registering a module ensure that you " +
  1472. "specify the dependencies as the second argument.", name);
  1473. }
  1474. /** @type {!Array.<Array.<*>>} */
  1475. var invokeQueue = [];
  1476. /** @type {!Array.<Function>} */
  1477. var runBlocks = [];
  1478. var config = invokeLater('$injector', 'invoke');
  1479. /** @type {angular.Module} */
  1480. var moduleInstance = {
  1481. // Private state
  1482. _invokeQueue: invokeQueue,
  1483. _runBlocks: runBlocks,
  1484. /**
  1485. * @ngdoc property
  1486. * @name angular.Module#requires
  1487. * @module ng
  1488. * @returns {Array.<string>} List of module names which must be loaded before this module.
  1489. * @description
  1490. * Holds the list of modules which the injector will load before the current module is
  1491. * loaded.
  1492. */
  1493. requires: requires,
  1494. /**
  1495. * @ngdoc property
  1496. * @name angular.Module#name
  1497. * @module ng
  1498. * @returns {string} Name of the module.
  1499. * @description
  1500. */
  1501. name: name,
  1502. /**
  1503. * @ngdoc method
  1504. * @name angular.Module#provider
  1505. * @module ng
  1506. * @param {string} name service name
  1507. * @param {Function} providerType Construction function for creating new instance of the
  1508. * service.
  1509. * @description
  1510. * See {@link auto.$provide#provider $provide.provider()}.
  1511. */
  1512. provider: invokeLater('$provide', 'provider'),
  1513. /**
  1514. * @ngdoc method
  1515. * @name angular.Module#factory
  1516. * @module ng
  1517. * @param {string} name service name
  1518. * @param {Function} providerFunction Function for creating new instance of the service.
  1519. * @description
  1520. * See {@link auto.$provide#factory $provide.factory()}.
  1521. */
  1522. factory: invokeLater('$provide', 'factory'),
  1523. /**
  1524. * @ngdoc method
  1525. * @name angular.Module#service
  1526. * @module ng
  1527. * @param {string} name service name
  1528. * @param {Function} constructor A constructor function that will be instantiated.
  1529. * @description
  1530. * See {@link auto.$provide#service $provide.service()}.
  1531. */
  1532. service: invokeLater('$provide', 'service'),
  1533. /**
  1534. * @ngdoc method
  1535. * @name angular.Module#value
  1536. * @module ng
  1537. * @param {string} name service name
  1538. * @param {*} object Service instance object.
  1539. * @description
  1540. * See {@link auto.$provide#value $provide.value()}.
  1541. */
  1542. value: invokeLater('$provide', 'value'),
  1543. /**
  1544. * @ngdoc method
  1545. * @name angular.Module#constant
  1546. * @module ng
  1547. * @param {string} name constant name
  1548. * @param {*} object Constant value.
  1549. * @description
  1550. * Because the constant are fixed, they get applied before other provide methods.
  1551. * See {@link auto.$provide#constant $provide.constant()}.
  1552. */
  1553. constant: invokeLater('$provide', 'constant', 'unshift'),
  1554. /**
  1555. * @ngdoc method
  1556. * @name angular.Module#animation
  1557. * @module ng
  1558. * @param {string} name animation name
  1559. * @param {Function} animationFactory Factory function for creating new instance of an
  1560. * animation.
  1561. * @description
  1562. *
  1563. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1564. *
  1565. *
  1566. * Defines an animation hook that can be later used with
  1567. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1568. *
  1569. * ```js
  1570. * module.animation('.animation-name', function($inject1, $inject2) {
  1571. * return {
  1572. * eventName : function(element, done) {
  1573. * //code to run the animation
  1574. * //once complete, then run done()
  1575. * return function cancellationFunction(element) {
  1576. * //code to cancel the animation
  1577. * }
  1578. * }
  1579. * }
  1580. * })
  1581. * ```
  1582. *
  1583. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1584. * {@link ngAnimate ngAnimate module} for more information.
  1585. */
  1586. animation: invokeLater('$animateProvider', 'register'),
  1587. /**
  1588. * @ngdoc method
  1589. * @name angular.Module#filter
  1590. * @module ng
  1591. * @param {string} name Filter name.
  1592. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1593. * @description
  1594. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1595. */
  1596. filter: invokeLater('$filterProvider', 'register'),
  1597. /**
  1598. * @ngdoc method
  1599. * @name angular.Module#controller
  1600. * @module ng
  1601. * @param {string|Object} name Controller name, or an object map of controllers where the
  1602. * keys are the names and the values are the constructors.
  1603. * @param {Function} constructor Controller constructor function.
  1604. * @description
  1605. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1606. */
  1607. controller: invokeLater('$controllerProvider', 'register'),
  1608. /**
  1609. * @ngdoc method
  1610. * @name angular.Module#directive
  1611. * @module ng
  1612. * @param {string|Object} name Directive name, or an object map of directives where the
  1613. * keys are the names and the values are the factories.
  1614. * @param {Function} directiveFactory Factory function for creating new instance of
  1615. * directives.
  1616. * @description
  1617. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1618. */
  1619. directive: invokeLater('$compileProvider', 'directive'),
  1620. /**
  1621. * @ngdoc method
  1622. * @name angular.Module#config
  1623. * @module ng
  1624. * @param {Function} configFn Execute this function on module load. Useful for service
  1625. * configuration.
  1626. * @description
  1627. * Use this method to register work which needs to be performed on module loading.
  1628. * For more about how to configure services, see
  1629. * {@link providers#providers_provider-recipe Provider Recipe}.
  1630. */
  1631. config: config,
  1632. /**
  1633. * @ngdoc method
  1634. * @name angular.Module#run
  1635. * @module ng
  1636. * @param {Function} initializationFn Execute this function after injector creation.
  1637. * Useful for application initialization.
  1638. * @description
  1639. * Use this method to register work which should be performed when the injector is done
  1640. * loading all modules.
  1641. */
  1642. run: function(block) {
  1643. runBlocks.push(block);
  1644. return this;
  1645. }
  1646. };
  1647. if (configFn) {
  1648. config(configFn);
  1649. }
  1650. return moduleInstance;
  1651. /**
  1652. * @param {string} provider
  1653. * @param {string} method
  1654. * @param {String=} insertMethod
  1655. * @returns {angular.Module}
  1656. */
  1657. function invokeLater(provider, method, insertMethod) {
  1658. return function() {
  1659. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1660. return moduleInstance;
  1661. };
  1662. }
  1663. });
  1664. };
  1665. });
  1666. }
  1667. /* global
  1668. angularModule: true,
  1669. version: true,
  1670. $LocaleProvider,
  1671. $CompileProvider,
  1672. htmlAnchorDirective,
  1673. inputDirective,
  1674. inputDirective,
  1675. formDirective,
  1676. scriptDirective,
  1677. selectDirective,
  1678. styleDirective,
  1679. optionDirective,
  1680. ngBindDirective,
  1681. ngBindHtmlDirective,
  1682. ngBindTemplateDirective,
  1683. ngClassDirective,
  1684. ngClassEvenDirective,
  1685. ngClassOddDirective,
  1686. ngCspDirective,
  1687. ngCloakDirective,
  1688. ngControllerDirective,
  1689. ngFormDirective,
  1690. ngHideDirective,
  1691. ngIfDirective,
  1692. ngIncludeDirective,
  1693. ngIncludeFillContentDirective,
  1694. ngInitDirective,
  1695. ngNonBindableDirective,
  1696. ngPluralizeDirective,
  1697. ngRepeatDirective,
  1698. ngShowDirective,
  1699. ngStyleDirective,
  1700. ngSwitchDirective,
  1701. ngSwitchWhenDirective,
  1702. ngSwitchDefaultDirective,
  1703. ngOptionsDirective,
  1704. ngTranscludeDirective,
  1705. ngModelDirective,
  1706. ngListDirective,
  1707. ngChangeDirective,
  1708. requiredDirective,
  1709. requiredDirective,
  1710. ngValueDirective,
  1711. ngAttributeAliasDirectives,
  1712. ngEventDirectives,
  1713. $AnchorScrollProvider,
  1714. $AnimateProvider,
  1715. $BrowserProvider,
  1716. $CacheFactoryProvider,
  1717. $ControllerProvider,
  1718. $DocumentProvider,
  1719. $ExceptionHandlerProvider,
  1720. $FilterProvider,
  1721. $InterpolateProvider,
  1722. $IntervalProvider,
  1723. $HttpProvider,
  1724. $HttpBackendProvider,
  1725. $LocationProvider,
  1726. $LogProvider,
  1727. $ParseProvider,
  1728. $RootScopeProvider,
  1729. $QProvider,
  1730. $$SanitizeUriProvider,
  1731. $SceProvider,
  1732. $SceDelegateProvider,
  1733. $SnifferProvider,
  1734. $TemplateCacheProvider,
  1735. $TimeoutProvider,
  1736. $$RAFProvider,
  1737. $$AsyncCallbackProvider,
  1738. $WindowProvider
  1739. */
  1740. /**
  1741. * @ngdoc object
  1742. * @name angular.version
  1743. * @module ng
  1744. * @description
  1745. * An object that contains information about the current AngularJS version. This object has the
  1746. * following properties:
  1747. *
  1748. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1749. * - `major` – `{number}` – Major version number, such as "0".
  1750. * - `minor` – `{number}` – Minor version number, such as "9".
  1751. * - `dot` – `{number}` – Dot version number, such as "18".
  1752. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1753. */
  1754. var version = {
  1755. full: '1.2.17', // all of these placeholder strings will be replaced by grunt's
  1756. major: 1, // package task
  1757. minor: 2,
  1758. dot: 17,
  1759. codeName: 'quantum-disentanglement'
  1760. };
  1761. function publishExternalAPI(angular){
  1762. extend(angular, {
  1763. 'bootstrap': bootstrap,
  1764. 'copy': copy,
  1765. 'extend': extend,
  1766. 'equals': equals,
  1767. 'element': jqLite,
  1768. 'forEach': forEach,
  1769. 'injector': createInjector,
  1770. 'noop':noop,
  1771. 'bind':bind,
  1772. 'toJson': toJson,
  1773. 'fromJson': fromJson,
  1774. 'identity':identity,
  1775. 'isUndefined': isUndefined,
  1776. 'isDefined': isDefined,
  1777. 'isString': isString,
  1778. 'isFunction': isFunction,
  1779. 'isObject': isObject,
  1780. 'isNumber': isNumber,
  1781. 'isElement': isElement,
  1782. 'isArray': isArray,
  1783. 'version': version,
  1784. 'isDate': isDate,
  1785. 'lowercase': lowercase,
  1786. 'uppercase': uppercase,
  1787. 'callbacks': {counter: 0},
  1788. '$$minErr': minErr,
  1789. '$$csp': csp
  1790. });
  1791. angularModule = setupModuleLoader(window);
  1792. try {
  1793. angularModule('ngLocale');
  1794. } catch (e) {
  1795. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1796. }
  1797. angularModule('ng', ['ngLocale'], ['$provide',
  1798. function ngModule($provide) {
  1799. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1800. $provide.provider({
  1801. $$sanitizeUri: $$SanitizeUriProvider
  1802. });
  1803. $provide.provider('$compile', $CompileProvider).
  1804. directive({
  1805. a: htmlAnchorDirective,
  1806. input: inputDirective,
  1807. textarea: inputDirective,
  1808. form: formDirective,
  1809. script: scriptDirective,
  1810. select: selectDirective,
  1811. style: styleDirective,
  1812. option: optionDirective,
  1813. ngBind: ngBindDirective,
  1814. ngBindHtml: ngBindHtmlDirective,
  1815. ngBindTemplate: ngBindTemplateDirective,
  1816. ngClass: ngClassDirective,
  1817. ngClassEven: ngClassEvenDirective,
  1818. ngClassOdd: ngClassOddDirective,
  1819. ngCloak: ngCloakDirective,
  1820. ngController: ngControllerDirective,
  1821. ngForm: ngFormDirective,
  1822. ngHide: ngHideDirective,
  1823. ngIf: ngIfDirective,
  1824. ngInclude: ngIncludeDirective,
  1825. ngInit: ngInitDirective,
  1826. ngNonBindable: ngNonBindableDirective,
  1827. ngPluralize: ngPluralizeDirective,
  1828. ngRepeat: ngRepeatDirective,
  1829. ngShow: ngShowDirective,
  1830. ngStyle: ngStyleDirective,
  1831. ngSwitch: ngSwitchDirective,
  1832. ngSwitchWhen: ngSwitchWhenDirective,
  1833. ngSwitchDefault: ngSwitchDefaultDirective,
  1834. ngOptions: ngOptionsDirective,
  1835. ngTransclude: ngTranscludeDirective,
  1836. ngModel: ngModelDirective,
  1837. ngList: ngListDirective,
  1838. ngChange: ngChangeDirective,
  1839. required: requiredDirective,
  1840. ngRequired: requiredDirective,
  1841. ngValue: ngValueDirective
  1842. }).
  1843. directive({
  1844. ngInclude: ngIncludeFillContentDirective
  1845. }).
  1846. directive(ngAttributeAliasDirectives).
  1847. directive(ngEventDirectives);
  1848. $provide.provider({
  1849. $anchorScroll: $AnchorScrollProvider,
  1850. $animate: $AnimateProvider,
  1851. $browser: $BrowserProvider,
  1852. $cacheFactory: $CacheFactoryProvider,
  1853. $controller: $ControllerProvider,
  1854. $document: $DocumentProvider,
  1855. $exceptionHandler: $ExceptionHandlerProvider,
  1856. $filter: $FilterProvider,
  1857. $interpolate: $InterpolateProvider,
  1858. $interval: $IntervalProvider,
  1859. $http: $HttpProvider,
  1860. $httpBackend: $HttpBackendProvider,
  1861. $location: $LocationProvider,
  1862. $log: $LogProvider,
  1863. $parse: $ParseProvider,
  1864. $rootScope: $RootScopeProvider,
  1865. $q: $QProvider,
  1866. $sce: $SceProvider,
  1867. $sceDelegate: $SceDelegateProvider,
  1868. $sniffer: $SnifferProvider,
  1869. $templateCache: $TemplateCacheProvider,
  1870. $timeout: $TimeoutProvider,
  1871. $window: $WindowProvider,
  1872. $$rAF: $$RAFProvider,
  1873. $$asyncCallback : $$AsyncCallbackProvider
  1874. });
  1875. }
  1876. ]);
  1877. }
  1878. /* global
  1879. -JQLitePrototype,
  1880. -addEventListenerFn,
  1881. -removeEventListenerFn,
  1882. -BOOLEAN_ATTR
  1883. */
  1884. //////////////////////////////////
  1885. //JQLite
  1886. //////////////////////////////////
  1887. /**
  1888. * @ngdoc function
  1889. * @name angular.element
  1890. * @module ng
  1891. * @kind function
  1892. *
  1893. * @description
  1894. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1895. *
  1896. * If jQuery is available, `angular.element` is an alias for the
  1897. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1898. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1899. *
  1900. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1901. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1902. * commonly needed functionality with the goal of having a very small footprint.</div>
  1903. *
  1904. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1905. *
  1906. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1907. * jqLite; they are never raw DOM references.</div>
  1908. *
  1909. * ## Angular's jqLite
  1910. * jqLite provides only the following jQuery methods:
  1911. *
  1912. * - [`addClass()`](http://api.jquery.com/addClass/)
  1913. * - [`after()`](http://api.jquery.com/after/)
  1914. * - [`append()`](http://api.jquery.com/append/)
  1915. * - [`attr()`](http://api.jquery.com/attr/)
  1916. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  1917. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1918. * - [`clone()`](http://api.jquery.com/clone/)
  1919. * - [`contents()`](http://api.jquery.com/contents/)
  1920. * - [`css()`](http://api.jquery.com/css/)
  1921. * - [`data()`](http://api.jquery.com/data/)
  1922. * - [`empty()`](http://api.jquery.com/empty/)
  1923. * - [`eq()`](http://api.jquery.com/eq/)
  1924. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1925. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1926. * - [`html()`](http://api.jquery.com/html/)
  1927. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1928. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1929. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1930. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1931. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1932. * - [`prepend()`](http://api.jquery.com/prepend/)
  1933. * - [`prop()`](http://api.jquery.com/prop/)
  1934. * - [`ready()`](http://api.jquery.com/ready/)
  1935. * - [`remove()`](http://api.jquery.com/remove/)
  1936. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1937. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1938. * - [`removeData()`](http://api.jquery.com/removeData/)
  1939. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1940. * - [`text()`](http://api.jquery.com/text/)
  1941. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1942. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1943. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  1944. * - [`val()`](http://api.jquery.com/val/)
  1945. * - [`wrap()`](http://api.jquery.com/wrap/)
  1946. *
  1947. * ## jQuery/jqLite Extras
  1948. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1949. *
  1950. * ### Events
  1951. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1952. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1953. * element before it is removed.
  1954. *
  1955. * ### Methods
  1956. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1957. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1958. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1959. * `'ngModel'`).
  1960. * - `injector()` - retrieves the injector of the current element or its parent.
  1961. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  1962. * element or its parent.
  1963. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  1964. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1965. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1966. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  1967. * parent element is reached.
  1968. *
  1969. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  1970. * @returns {Object} jQuery object.
  1971. */
  1972. var jqCache = JQLite.cache = {},
  1973. jqName = JQLite.expando = 'ng' + new Date().getTime(),
  1974. jqId = 1,
  1975. addEventListenerFn = (window.document.addEventListener
  1976. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  1977. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  1978. removeEventListenerFn = (window.document.removeEventListener
  1979. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  1980. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  1981. /*
  1982. * !!! This is an undocumented "private" function !!!
  1983. */
  1984. var jqData = JQLite._data = function(node) {
  1985. //jQuery always returns an object on cache miss
  1986. return this.cache[node[this.expando]] || {};
  1987. };
  1988. function jqNextId() { return ++jqId; }
  1989. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  1990. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  1991. var jqLiteMinErr = minErr('jqLite');
  1992. /**
  1993. * Converts snake_case to camelCase.
  1994. * Also there is special case for Moz prefix starting with upper case letter.
  1995. * @param name Name to normalize
  1996. */
  1997. function camelCase(name) {
  1998. return name.
  1999. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2000. return offset ? letter.toUpperCase() : letter;
  2001. }).
  2002. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2003. }
  2004. /////////////////////////////////////////////
  2005. // jQuery mutation patch
  2006. //
  2007. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  2008. // $destroy event on all DOM nodes being removed.
  2009. //
  2010. /////////////////////////////////////////////
  2011. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  2012. var originalJqFn = jQuery.fn[name];
  2013. originalJqFn = originalJqFn.$original || originalJqFn;
  2014. removePatch.$original = originalJqFn;
  2015. jQuery.fn[name] = removePatch;
  2016. function removePatch(param) {
  2017. // jshint -W040
  2018. var list = filterElems && param ? [this.filter(param)] : [this],
  2019. fireEvent = dispatchThis,
  2020. set, setIndex, setLength,
  2021. element, childIndex, childLength, children;
  2022. if (!getterIfNoArguments || param != null) {
  2023. while(list.length) {
  2024. set = list.shift();
  2025. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  2026. element = jqLite(set[setIndex]);
  2027. if (fireEvent) {
  2028. element.triggerHandler('$destroy');
  2029. } else {
  2030. fireEvent = !fireEvent;
  2031. }
  2032. for(childIndex = 0, childLength = (children = element.children()).length;
  2033. childIndex < childLength;
  2034. childIndex++) {
  2035. list.push(jQuery(children[childIndex]));
  2036. }
  2037. }
  2038. }
  2039. }
  2040. return originalJqFn.apply(this, arguments);
  2041. }
  2042. }
  2043. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2044. var HTML_REGEXP = /<|&#?\w+;/;
  2045. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2046. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2047. var wrapMap = {
  2048. 'option': [1, '<select multiple="multiple">', '</select>'],
  2049. 'thead': [1, '<table>', '</table>'],
  2050. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2051. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2052. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2053. '_default': [0, "", ""]
  2054. };
  2055. wrapMap.optgroup = wrapMap.option;
  2056. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2057. wrapMap.th = wrapMap.td;
  2058. function jqLiteIsTextNode(html) {
  2059. return !HTML_REGEXP.test(html);
  2060. }
  2061. function jqLiteBuildFragment(html, context) {
  2062. var elem, tmp, tag, wrap,
  2063. fragment = context.createDocumentFragment(),
  2064. nodes = [], i, j, jj;
  2065. if (jqLiteIsTextNode(html)) {
  2066. // Convert non-html into a text node
  2067. nodes.push(context.createTextNode(html));
  2068. } else {
  2069. tmp = fragment.appendChild(context.createElement('div'));
  2070. // Convert html into DOM nodes
  2071. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2072. wrap = wrapMap[tag] || wrapMap._default;
  2073. tmp.innerHTML = '<div>&#160;</div>' +
  2074. wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2075. tmp.removeChild(tmp.firstChild);
  2076. // Descend through wrappers to the right content
  2077. i = wrap[0];
  2078. while (i--) {
  2079. tmp = tmp.lastChild;
  2080. }
  2081. for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);
  2082. tmp = fragment.firstChild;
  2083. tmp.textContent = "";
  2084. }
  2085. // Remove wrapper from fragment
  2086. fragment.textContent = "";
  2087. fragment.innerHTML = ""; // Clear inner HTML
  2088. return nodes;
  2089. }
  2090. function jqLiteParseHTML(html, context) {
  2091. context = context || document;
  2092. var parsed;
  2093. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2094. return [context.createElement(parsed[1])];
  2095. }
  2096. return jqLiteBuildFragment(html, context);
  2097. }
  2098. /////////////////////////////////////////////
  2099. function JQLite(element) {
  2100. if (element instanceof JQLite) {
  2101. return element;
  2102. }
  2103. if (isString(element)) {
  2104. element = trim(element);
  2105. }
  2106. if (!(this instanceof JQLite)) {
  2107. if (isString(element) && element.charAt(0) != '<') {
  2108. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2109. }
  2110. return new JQLite(element);
  2111. }
  2112. if (isString(element)) {
  2113. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2114. var fragment = jqLite(document.createDocumentFragment());
  2115. fragment.append(this);
  2116. } else {
  2117. jqLiteAddNodes(this, element);
  2118. }
  2119. }
  2120. function jqLiteClone(element) {
  2121. return element.cloneNode(true);
  2122. }
  2123. function jqLiteDealoc(element){
  2124. jqLiteRemoveData(element);
  2125. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  2126. jqLiteDealoc(children[i]);
  2127. }
  2128. }
  2129. function jqLiteOff(element, type, fn, unsupported) {
  2130. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2131. var events = jqLiteExpandoStore(element, 'events'),
  2132. handle = jqLiteExpandoStore(element, 'handle');
  2133. if (!handle) return; //no listeners registered
  2134. if (isUndefined(type)) {
  2135. forEach(events, function(eventHandler, type) {
  2136. removeEventListenerFn(element, type, eventHandler);
  2137. delete events[type];
  2138. });
  2139. } else {
  2140. forEach(type.split(' '), function(type) {
  2141. if (isUndefined(fn)) {
  2142. removeEventListenerFn(element, type, events[type]);
  2143. delete events[type];
  2144. } else {
  2145. arrayRemove(events[type] || [], fn);
  2146. }
  2147. });
  2148. }
  2149. }
  2150. function jqLiteRemoveData(element, name) {
  2151. var expandoId = element[jqName],
  2152. expandoStore = jqCache[expandoId];
  2153. if (expandoStore) {
  2154. if (name) {
  2155. delete jqCache[expandoId].data[name];
  2156. return;
  2157. }
  2158. if (expandoStore.handle) {
  2159. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  2160. jqLiteOff(element);
  2161. }
  2162. delete jqCache[expandoId];
  2163. element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
  2164. }
  2165. }
  2166. function jqLiteExpandoStore(element, key, value) {
  2167. var expandoId = element[jqName],
  2168. expandoStore = jqCache[expandoId || -1];
  2169. if (isDefined(value)) {
  2170. if (!expandoStore) {
  2171. element[jqName] = expandoId = jqNextId();
  2172. expandoStore = jqCache[expandoId] = {};
  2173. }
  2174. expandoStore[key] = value;
  2175. } else {
  2176. return expandoStore && expandoStore[key];
  2177. }
  2178. }
  2179. function jqLiteData(element, key, value) {
  2180. var data = jqLiteExpandoStore(element, 'data'),
  2181. isSetter = isDefined(value),
  2182. keyDefined = !isSetter && isDefined(key),
  2183. isSimpleGetter = keyDefined && !isObject(key);
  2184. if (!data && !isSimpleGetter) {
  2185. jqLiteExpandoStore(element, 'data', data = {});
  2186. }
  2187. if (isSetter) {
  2188. data[key] = value;
  2189. } else {
  2190. if (keyDefined) {
  2191. if (isSimpleGetter) {
  2192. // don't create data in this case.
  2193. return data && data[key];
  2194. } else {
  2195. extend(data, key);
  2196. }
  2197. } else {
  2198. return data;
  2199. }
  2200. }
  2201. }
  2202. function jqLiteHasClass(element, selector) {
  2203. if (!element.getAttribute) return false;
  2204. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2205. indexOf( " " + selector + " " ) > -1);
  2206. }
  2207. function jqLiteRemoveClass(element, cssClasses) {
  2208. if (cssClasses && element.setAttribute) {
  2209. forEach(cssClasses.split(' '), function(cssClass) {
  2210. element.setAttribute('class', trim(
  2211. (" " + (element.getAttribute('class') || '') + " ")
  2212. .replace(/[\n\t]/g, " ")
  2213. .replace(" " + trim(cssClass) + " ", " "))
  2214. );
  2215. });
  2216. }
  2217. }
  2218. function jqLiteAddClass(element, cssClasses) {
  2219. if (cssClasses && element.setAttribute) {
  2220. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2221. .replace(/[\n\t]/g, " ");
  2222. forEach(cssClasses.split(' '), function(cssClass) {
  2223. cssClass = trim(cssClass);
  2224. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2225. existingClasses += cssClass + ' ';
  2226. }
  2227. });
  2228. element.setAttribute('class', trim(existingClasses));
  2229. }
  2230. }
  2231. function jqLiteAddNodes(root, elements) {
  2232. if (elements) {
  2233. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2234. ? elements
  2235. : [ elements ];
  2236. for(var i=0; i < elements.length; i++) {
  2237. root.push(elements[i]);
  2238. }
  2239. }
  2240. }
  2241. function jqLiteController(element, name) {
  2242. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2243. }
  2244. function jqLiteInheritedData(element, name, value) {
  2245. element = jqLite(element);
  2246. // if element is the document object work with the html element instead
  2247. // this makes $(document).scope() possible
  2248. if(element[0].nodeType == 9) {
  2249. element = element.find('html');
  2250. }
  2251. var names = isArray(name) ? name : [name];
  2252. while (element.length) {
  2253. var node = element[0];
  2254. for (var i = 0, ii = names.length; i < ii; i++) {
  2255. if ((value = element.data(names[i])) !== undefined) return value;
  2256. }
  2257. // If dealing with a document fragment node with a host element, and no parent, use the host
  2258. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2259. // to lookup parent controllers.
  2260. element = jqLite(node.parentNode || (node.nodeType === 11 && node.host));
  2261. }
  2262. }
  2263. function jqLiteEmpty(element) {
  2264. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2265. jqLiteDealoc(childNodes[i]);
  2266. }
  2267. while (element.firstChild) {
  2268. element.removeChild(element.firstChild);
  2269. }
  2270. }
  2271. //////////////////////////////////////////
  2272. // Functions which are declared directly.
  2273. //////////////////////////////////////////
  2274. var JQLitePrototype = JQLite.prototype = {
  2275. ready: function(fn) {
  2276. var fired = false;
  2277. function trigger() {
  2278. if (fired) return;
  2279. fired = true;
  2280. fn();
  2281. }
  2282. // check if document already is loaded
  2283. if (document.readyState === 'complete'){
  2284. setTimeout(trigger);
  2285. } else {
  2286. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2287. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2288. // jshint -W064
  2289. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2290. // jshint +W064
  2291. }
  2292. },
  2293. toString: function() {
  2294. var value = [];
  2295. forEach(this, function(e){ value.push('' + e);});
  2296. return '[' + value.join(', ') + ']';
  2297. },
  2298. eq: function(index) {
  2299. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2300. },
  2301. length: 0,
  2302. push: push,
  2303. sort: [].sort,
  2304. splice: [].splice
  2305. };
  2306. //////////////////////////////////////////
  2307. // Functions iterating getter/setters.
  2308. // these functions return self on setter and
  2309. // value on get.
  2310. //////////////////////////////////////////
  2311. var BOOLEAN_ATTR = {};
  2312. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2313. BOOLEAN_ATTR[lowercase(value)] = value;
  2314. });
  2315. var BOOLEAN_ELEMENTS = {};
  2316. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2317. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2318. });
  2319. function getBooleanAttrName(element, name) {
  2320. // check dom last since we will most likely fail on name
  2321. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2322. // booleanAttr is here twice to minimize DOM access
  2323. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2324. }
  2325. forEach({
  2326. data: jqLiteData,
  2327. inheritedData: jqLiteInheritedData,
  2328. scope: function(element) {
  2329. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2330. return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2331. },
  2332. isolateScope: function(element) {
  2333. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2334. return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
  2335. },
  2336. controller: jqLiteController,
  2337. injector: function(element) {
  2338. return jqLiteInheritedData(element, '$injector');
  2339. },
  2340. removeAttr: function(element,name) {
  2341. element.removeAttribute(name);
  2342. },
  2343. hasClass: jqLiteHasClass,
  2344. css: function(element, name, value) {
  2345. name = camelCase(name);
  2346. if (isDefined(value)) {
  2347. element.style[name] = value;
  2348. } else {
  2349. var val;
  2350. if (msie <= 8) {
  2351. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2352. val = element.currentStyle && element.currentStyle[name];
  2353. if (val === '') val = 'auto';
  2354. }
  2355. val = val || element.style[name];
  2356. if (msie <= 8) {
  2357. // jquery weirdness :-/
  2358. val = (val === '') ? undefined : val;
  2359. }
  2360. return val;
  2361. }
  2362. },
  2363. attr: function(element, name, value){
  2364. var lowercasedName = lowercase(name);
  2365. if (BOOLEAN_ATTR[lowercasedName]) {
  2366. if (isDefined(value)) {
  2367. if (!!value) {
  2368. element[name] = true;
  2369. element.setAttribute(name, lowercasedName);
  2370. } else {
  2371. element[name] = false;
  2372. element.removeAttribute(lowercasedName);
  2373. }
  2374. } else {
  2375. return (element[name] ||
  2376. (element.attributes.getNamedItem(name)|| noop).specified)
  2377. ? lowercasedName
  2378. : undefined;
  2379. }
  2380. } else if (isDefined(value)) {
  2381. element.setAttribute(name, value);
  2382. } else if (element.getAttribute) {
  2383. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2384. // some elements (e.g. Document) don't have get attribute, so return undefined
  2385. var ret = element.getAttribute(name, 2);
  2386. // normalize non-existing attributes to undefined (as jQuery)
  2387. return ret === null ? undefined : ret;
  2388. }
  2389. },
  2390. prop: function(element, name, value) {
  2391. if (isDefined(value)) {
  2392. element[name] = value;
  2393. } else {
  2394. return element[name];
  2395. }
  2396. },
  2397. text: (function() {
  2398. var NODE_TYPE_TEXT_PROPERTY = [];
  2399. if (msie < 9) {
  2400. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2401. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2402. } else {
  2403. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2404. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2405. }
  2406. getText.$dv = '';
  2407. return getText;
  2408. function getText(element, value) {
  2409. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2410. if (isUndefined(value)) {
  2411. return textProp ? element[textProp] : '';
  2412. }
  2413. element[textProp] = value;
  2414. }
  2415. })(),
  2416. val: function(element, value) {
  2417. if (isUndefined(value)) {
  2418. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2419. var result = [];
  2420. forEach(element.options, function (option) {
  2421. if (option.selected) {
  2422. result.push(option.value || option.text);
  2423. }
  2424. });
  2425. return result.length === 0 ? null : result;
  2426. }
  2427. return element.value;
  2428. }
  2429. element.value = value;
  2430. },
  2431. html: function(element, value) {
  2432. if (isUndefined(value)) {
  2433. return element.innerHTML;
  2434. }
  2435. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2436. jqLiteDealoc(childNodes[i]);
  2437. }
  2438. element.innerHTML = value;
  2439. },
  2440. empty: jqLiteEmpty
  2441. }, function(fn, name){
  2442. /**
  2443. * Properties: writes return selection, reads return first value
  2444. */
  2445. JQLite.prototype[name] = function(arg1, arg2) {
  2446. var i, key;
  2447. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2448. // in a way that survives minification.
  2449. // jqLiteEmpty takes no arguments but is a setter.
  2450. if (fn !== jqLiteEmpty &&
  2451. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2452. if (isObject(arg1)) {
  2453. // we are a write, but the object properties are the key/values
  2454. for (i = 0; i < this.length; i++) {
  2455. if (fn === jqLiteData) {
  2456. // data() takes the whole object in jQuery
  2457. fn(this[i], arg1);
  2458. } else {
  2459. for (key in arg1) {
  2460. fn(this[i], key, arg1[key]);
  2461. }
  2462. }
  2463. }
  2464. // return self for chaining
  2465. return this;
  2466. } else {
  2467. // we are a read, so read the first child.
  2468. var value = fn.$dv;
  2469. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2470. var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
  2471. for (var j = 0; j < jj; j++) {
  2472. var nodeValue = fn(this[j], arg1, arg2);
  2473. value = value ? value + nodeValue : nodeValue;
  2474. }
  2475. return value;
  2476. }
  2477. } else {
  2478. // we are a write, so apply to all children
  2479. for (i = 0; i < this.length; i++) {
  2480. fn(this[i], arg1, arg2);
  2481. }
  2482. // return self for chaining
  2483. return this;
  2484. }
  2485. };
  2486. });
  2487. function createEventHandler(element, events) {
  2488. var eventHandler = function (event, type) {
  2489. if (!event.preventDefault) {
  2490. event.preventDefault = function() {
  2491. event.returnValue = false; //ie
  2492. };
  2493. }
  2494. if (!event.stopPropagation) {
  2495. event.stopPropagation = function() {
  2496. event.cancelBubble = true; //ie
  2497. };
  2498. }
  2499. if (!event.target) {
  2500. event.target = event.srcElement || document;
  2501. }
  2502. if (isUndefined(event.defaultPrevented)) {
  2503. var prevent = event.preventDefault;
  2504. event.preventDefault = function() {
  2505. event.defaultPrevented = true;
  2506. prevent.call(event);
  2507. };
  2508. event.defaultPrevented = false;
  2509. }
  2510. event.isDefaultPrevented = function() {
  2511. return event.defaultPrevented || event.returnValue === false;
  2512. };
  2513. // Copy event handlers in case event handlers array is modified during execution.
  2514. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2515. forEach(eventHandlersCopy, function(fn) {
  2516. fn.call(element, event);
  2517. });
  2518. // Remove monkey-patched methods (IE),
  2519. // as they would cause memory leaks in IE8.
  2520. if (msie <= 8) {
  2521. // IE7/8 does not allow to delete property on native object
  2522. event.preventDefault = null;
  2523. event.stopPropagation = null;
  2524. event.isDefaultPrevented = null;
  2525. } else {
  2526. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2527. delete event.preventDefault;
  2528. delete event.stopPropagation;
  2529. delete event.isDefaultPrevented;
  2530. }
  2531. };
  2532. eventHandler.elem = element;
  2533. return eventHandler;
  2534. }
  2535. //////////////////////////////////////////
  2536. // Functions iterating traversal.
  2537. // These functions chain results into a single
  2538. // selector.
  2539. //////////////////////////////////////////
  2540. forEach({
  2541. removeData: jqLiteRemoveData,
  2542. dealoc: jqLiteDealoc,
  2543. on: function onFn(element, type, fn, unsupported){
  2544. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2545. var events = jqLiteExpandoStore(element, 'events'),
  2546. handle = jqLiteExpandoStore(element, 'handle');
  2547. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2548. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2549. forEach(type.split(' '), function(type){
  2550. var eventFns = events[type];
  2551. if (!eventFns) {
  2552. if (type == 'mouseenter' || type == 'mouseleave') {
  2553. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2554. function( a, b ) {
  2555. // jshint bitwise: false
  2556. var adown = a.nodeType === 9 ? a.documentElement : a,
  2557. bup = b && b.parentNode;
  2558. return a === bup || !!( bup && bup.nodeType === 1 && (
  2559. adown.contains ?
  2560. adown.contains( bup ) :
  2561. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2562. ));
  2563. } :
  2564. function( a, b ) {
  2565. if ( b ) {
  2566. while ( (b = b.parentNode) ) {
  2567. if ( b === a ) {
  2568. return true;
  2569. }
  2570. }
  2571. }
  2572. return false;
  2573. };
  2574. events[type] = [];
  2575. // Refer to jQuery's implementation of mouseenter & mouseleave
  2576. // Read about mouseenter and mouseleave:
  2577. // http://www.quirksmode.org/js/events_mouse.html#link8
  2578. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2579. onFn(element, eventmap[type], function(event) {
  2580. var target = this, related = event.relatedTarget;
  2581. // For mousenter/leave call the handler if related is outside the target.
  2582. // NB: No relatedTarget if the mouse left/entered the browser window
  2583. if ( !related || (related !== target && !contains(target, related)) ){
  2584. handle(event, type);
  2585. }
  2586. });
  2587. } else {
  2588. addEventListenerFn(element, type, handle);
  2589. events[type] = [];
  2590. }
  2591. eventFns = events[type];
  2592. }
  2593. eventFns.push(fn);
  2594. });
  2595. },
  2596. off: jqLiteOff,
  2597. one: function(element, type, fn) {
  2598. element = jqLite(element);
  2599. //add the listener twice so that when it is called
  2600. //you can remove the original function and still be
  2601. //able to call element.off(ev, fn) normally
  2602. element.on(type, function onFn() {
  2603. element.off(type, fn);
  2604. element.off(type, onFn);
  2605. });
  2606. element.on(type, fn);
  2607. },
  2608. replaceWith: function(element, replaceNode) {
  2609. var index, parent = element.parentNode;
  2610. jqLiteDealoc(element);
  2611. forEach(new JQLite(replaceNode), function(node){
  2612. if (index) {
  2613. parent.insertBefore(node, index.nextSibling);
  2614. } else {
  2615. parent.replaceChild(node, element);
  2616. }
  2617. index = node;
  2618. });
  2619. },
  2620. children: function(element) {
  2621. var children = [];
  2622. forEach(element.childNodes, function(element){
  2623. if (element.nodeType === 1)
  2624. children.push(element);
  2625. });
  2626. return children;
  2627. },
  2628. contents: function(element) {
  2629. return element.contentDocument || element.childNodes || [];
  2630. },
  2631. append: function(element, node) {
  2632. forEach(new JQLite(node), function(child){
  2633. if (element.nodeType === 1 || element.nodeType === 11) {
  2634. element.appendChild(child);
  2635. }
  2636. });
  2637. },
  2638. prepend: function(element, node) {
  2639. if (element.nodeType === 1) {
  2640. var index = element.firstChild;
  2641. forEach(new JQLite(node), function(child){
  2642. element.insertBefore(child, index);
  2643. });
  2644. }
  2645. },
  2646. wrap: function(element, wrapNode) {
  2647. wrapNode = jqLite(wrapNode)[0];
  2648. var parent = element.parentNode;
  2649. if (parent) {
  2650. parent.replaceChild(wrapNode, element);
  2651. }
  2652. wrapNode.appendChild(element);
  2653. },
  2654. remove: function(element) {
  2655. jqLiteDealoc(element);
  2656. var parent = element.parentNode;
  2657. if (parent) parent.removeChild(element);
  2658. },
  2659. after: function(element, newElement) {
  2660. var index = element, parent = element.parentNode;
  2661. forEach(new JQLite(newElement), function(node){
  2662. parent.insertBefore(node, index.nextSibling);
  2663. index = node;
  2664. });
  2665. },
  2666. addClass: jqLiteAddClass,
  2667. removeClass: jqLiteRemoveClass,
  2668. toggleClass: function(element, selector, condition) {
  2669. if (selector) {
  2670. forEach(selector.split(' '), function(className){
  2671. var classCondition = condition;
  2672. if (isUndefined(classCondition)) {
  2673. classCondition = !jqLiteHasClass(element, className);
  2674. }
  2675. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2676. });
  2677. }
  2678. },
  2679. parent: function(element) {
  2680. var parent = element.parentNode;
  2681. return parent && parent.nodeType !== 11 ? parent : null;
  2682. },
  2683. next: function(element) {
  2684. if (element.nextElementSibling) {
  2685. return element.nextElementSibling;
  2686. }
  2687. // IE8 doesn't have nextElementSibling
  2688. var elm = element.nextSibling;
  2689. while (elm != null && elm.nodeType !== 1) {
  2690. elm = elm.nextSibling;
  2691. }
  2692. return elm;
  2693. },
  2694. find: function(element, selector) {
  2695. if (element.getElementsByTagName) {
  2696. return element.getElementsByTagName(selector);
  2697. } else {
  2698. return [];
  2699. }
  2700. },
  2701. clone: jqLiteClone,
  2702. triggerHandler: function(element, eventName, eventData) {
  2703. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2704. eventData = eventData || [];
  2705. var event = [{
  2706. preventDefault: noop,
  2707. stopPropagation: noop
  2708. }];
  2709. forEach(eventFns, function(fn) {
  2710. fn.apply(element, event.concat(eventData));
  2711. });
  2712. }
  2713. }, function(fn, name){
  2714. /**
  2715. * chaining functions
  2716. */
  2717. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2718. var value;
  2719. for(var i=0; i < this.length; i++) {
  2720. if (isUndefined(value)) {
  2721. value = fn(this[i], arg1, arg2, arg3);
  2722. if (isDefined(value)) {
  2723. // any function which returns a value needs to be wrapped
  2724. value = jqLite(value);
  2725. }
  2726. } else {
  2727. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2728. }
  2729. }
  2730. return isDefined(value) ? value : this;
  2731. };
  2732. // bind legacy bind/unbind to on/off
  2733. JQLite.prototype.bind = JQLite.prototype.on;
  2734. JQLite.prototype.unbind = JQLite.prototype.off;
  2735. });
  2736. /**
  2737. * Computes a hash of an 'obj'.
  2738. * Hash of a:
  2739. * string is string
  2740. * number is number as string
  2741. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2742. * that is also assigned to the $$hashKey property of the object.
  2743. *
  2744. * @param obj
  2745. * @returns {string} hash string such that the same input will have the same hash string.
  2746. * The resulting string key is in 'type:hashKey' format.
  2747. */
  2748. function hashKey(obj) {
  2749. var objType = typeof obj,
  2750. key;
  2751. if (objType == 'object' && obj !== null) {
  2752. if (typeof (key = obj.$$hashKey) == 'function') {
  2753. // must invoke on object to keep the right this
  2754. key = obj.$$hashKey();
  2755. } else if (key === undefined) {
  2756. key = obj.$$hashKey = nextUid();
  2757. }
  2758. } else {
  2759. key = obj;
  2760. }
  2761. return objType + ':' + key;
  2762. }
  2763. /**
  2764. * HashMap which can use objects as keys
  2765. */
  2766. function HashMap(array){
  2767. forEach(array, this.put, this);
  2768. }
  2769. HashMap.prototype = {
  2770. /**
  2771. * Store key value pair
  2772. * @param key key to store can be any type
  2773. * @param value value to store can be any type
  2774. */
  2775. put: function(key, value) {
  2776. this[hashKey(key)] = value;
  2777. },
  2778. /**
  2779. * @param key
  2780. * @returns {Object} the value for the key
  2781. */
  2782. get: function(key) {
  2783. return this[hashKey(key)];
  2784. },
  2785. /**
  2786. * Remove the key/value pair
  2787. * @param key
  2788. */
  2789. remove: function(key) {
  2790. var value = this[key = hashKey(key)];
  2791. delete this[key];
  2792. return value;
  2793. }
  2794. };
  2795. /**
  2796. * @ngdoc function
  2797. * @module ng
  2798. * @name angular.injector
  2799. * @kind function
  2800. *
  2801. * @description
  2802. * Creates an injector function that can be used for retrieving services as well as for
  2803. * dependency injection (see {@link guide/di dependency injection}).
  2804. *
  2805. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2806. * {@link angular.module}. The `ng` module must be explicitly added.
  2807. * @returns {function()} Injector function. See {@link auto.$injector $injector}.
  2808. *
  2809. * @example
  2810. * Typical usage
  2811. * ```js
  2812. * // create an injector
  2813. * var $injector = angular.injector(['ng']);
  2814. *
  2815. * // use the injector to kick off your application
  2816. * // use the type inference to auto inject arguments, or use implicit injection
  2817. * $injector.invoke(function($rootScope, $compile, $document){
  2818. * $compile($document)($rootScope);
  2819. * $rootScope.$digest();
  2820. * });
  2821. * ```
  2822. *
  2823. * Sometimes you want to get access to the injector of a currently running Angular app
  2824. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2825. * application has been bootstrapped. You can do this using the extra `injector()` added
  2826. * to JQuery/jqLite elements. See {@link angular.element}.
  2827. *
  2828. * *This is fairly rare but could be the case if a third party library is injecting the
  2829. * markup.*
  2830. *
  2831. * In the following example a new block of HTML containing a `ng-controller`
  2832. * directive is added to the end of the document body by JQuery. We then compile and link
  2833. * it into the current AngularJS scope.
  2834. *
  2835. * ```js
  2836. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2837. * $(document.body).append($div);
  2838. *
  2839. * angular.element(document).injector().invoke(function($compile) {
  2840. * var scope = angular.element($div).scope();
  2841. * $compile($div)(scope);
  2842. * });
  2843. * ```
  2844. */
  2845. /**
  2846. * @ngdoc module
  2847. * @name auto
  2848. * @description
  2849. *
  2850. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2851. */
  2852. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2853. var FN_ARG_SPLIT = /,/;
  2854. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2855. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2856. var $injectorMinErr = minErr('$injector');
  2857. function annotate(fn) {
  2858. var $inject,
  2859. fnText,
  2860. argDecl,
  2861. last;
  2862. if (typeof fn == 'function') {
  2863. if (!($inject = fn.$inject)) {
  2864. $inject = [];
  2865. if (fn.length) {
  2866. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2867. argDecl = fnText.match(FN_ARGS);
  2868. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2869. arg.replace(FN_ARG, function(all, underscore, name){
  2870. $inject.push(name);
  2871. });
  2872. });
  2873. }
  2874. fn.$inject = $inject;
  2875. }
  2876. } else if (isArray(fn)) {
  2877. last = fn.length - 1;
  2878. assertArgFn(fn[last], 'fn');
  2879. $inject = fn.slice(0, last);
  2880. } else {
  2881. assertArgFn(fn, 'fn', true);
  2882. }
  2883. return $inject;
  2884. }
  2885. ///////////////////////////////////////
  2886. /**
  2887. * @ngdoc service
  2888. * @name $injector
  2889. * @kind function
  2890. *
  2891. * @description
  2892. *
  2893. * `$injector` is used to retrieve object instances as defined by
  2894. * {@link auto.$provide provider}, instantiate types, invoke methods,
  2895. * and load modules.
  2896. *
  2897. * The following always holds true:
  2898. *
  2899. * ```js
  2900. * var $injector = angular.injector();
  2901. * expect($injector.get('$injector')).toBe($injector);
  2902. * expect($injector.invoke(function($injector){
  2903. * return $injector;
  2904. * }).toBe($injector);
  2905. * ```
  2906. *
  2907. * # Injection Function Annotation
  2908. *
  2909. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2910. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2911. *
  2912. * ```js
  2913. * // inferred (only works if code not minified/obfuscated)
  2914. * $injector.invoke(function(serviceA){});
  2915. *
  2916. * // annotated
  2917. * function explicit(serviceA) {};
  2918. * explicit.$inject = ['serviceA'];
  2919. * $injector.invoke(explicit);
  2920. *
  2921. * // inline
  2922. * $injector.invoke(['serviceA', function(serviceA){}]);
  2923. * ```
  2924. *
  2925. * ## Inference
  2926. *
  2927. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2928. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2929. * minification, and obfuscation tools since these tools change the argument names.
  2930. *
  2931. * ## `$inject` Annotation
  2932. * By adding an `$inject` property onto a function the injection parameters can be specified.
  2933. *
  2934. * ## Inline
  2935. * As an array of injection names, where the last item in the array is the function to call.
  2936. */
  2937. /**
  2938. * @ngdoc method
  2939. * @name $injector#get
  2940. *
  2941. * @description
  2942. * Return an instance of the service.
  2943. *
  2944. * @param {string} name The name of the instance to retrieve.
  2945. * @return {*} The instance.
  2946. */
  2947. /**
  2948. * @ngdoc method
  2949. * @name $injector#invoke
  2950. *
  2951. * @description
  2952. * Invoke the method and supply the method arguments from the `$injector`.
  2953. *
  2954. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  2955. * {@link guide/di $inject Annotation} rules.
  2956. * @param {Object=} self The `this` for the invoked method.
  2957. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2958. * object first, before the `$injector` is consulted.
  2959. * @returns {*} the value returned by the invoked `fn` function.
  2960. */
  2961. /**
  2962. * @ngdoc method
  2963. * @name $injector#has
  2964. *
  2965. * @description
  2966. * Allows the user to query if the particular service exists.
  2967. *
  2968. * @param {string} Name of the service to query.
  2969. * @returns {boolean} returns true if injector has given service.
  2970. */
  2971. /**
  2972. * @ngdoc method
  2973. * @name $injector#instantiate
  2974. * @description
  2975. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  2976. * operator, and supplies all of the arguments to the constructor function as specified by the
  2977. * constructor annotation.
  2978. *
  2979. * @param {Function} Type Annotated constructor function.
  2980. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2981. * object first, before the `$injector` is consulted.
  2982. * @returns {Object} new instance of `Type`.
  2983. */
  2984. /**
  2985. * @ngdoc method
  2986. * @name $injector#annotate
  2987. *
  2988. * @description
  2989. * Returns an array of service names which the function is requesting for injection. This API is
  2990. * used by the injector to determine which services need to be injected into the function when the
  2991. * function is invoked. There are three ways in which the function can be annotated with the needed
  2992. * dependencies.
  2993. *
  2994. * # Argument names
  2995. *
  2996. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  2997. * by converting the function into a string using `toString()` method and extracting the argument
  2998. * names.
  2999. * ```js
  3000. * // Given
  3001. * function MyController($scope, $route) {
  3002. * // ...
  3003. * }
  3004. *
  3005. * // Then
  3006. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3007. * ```
  3008. *
  3009. * This method does not work with code minification / obfuscation. For this reason the following
  3010. * annotation strategies are supported.
  3011. *
  3012. * # The `$inject` property
  3013. *
  3014. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3015. * represent names of services to be injected into the function.
  3016. * ```js
  3017. * // Given
  3018. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3019. * // ...
  3020. * }
  3021. * // Define function dependencies
  3022. * MyController['$inject'] = ['$scope', '$route'];
  3023. *
  3024. * // Then
  3025. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3026. * ```
  3027. *
  3028. * # The array notation
  3029. *
  3030. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3031. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3032. * a way that survives minification is a better choice:
  3033. *
  3034. * ```js
  3035. * // We wish to write this (not minification / obfuscation safe)
  3036. * injector.invoke(function($compile, $rootScope) {
  3037. * // ...
  3038. * });
  3039. *
  3040. * // We are forced to write break inlining
  3041. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3042. * // ...
  3043. * };
  3044. * tmpFn.$inject = ['$compile', '$rootScope'];
  3045. * injector.invoke(tmpFn);
  3046. *
  3047. * // To better support inline function the inline annotation is supported
  3048. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3049. * // ...
  3050. * }]);
  3051. *
  3052. * // Therefore
  3053. * expect(injector.annotate(
  3054. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3055. * ).toEqual(['$compile', '$rootScope']);
  3056. * ```
  3057. *
  3058. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3059. * be retrieved as described above.
  3060. *
  3061. * @returns {Array.<string>} The names of the services which the function requires.
  3062. */
  3063. /**
  3064. * @ngdoc object
  3065. * @name $provide
  3066. *
  3067. * @description
  3068. *
  3069. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3070. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3071. * {@link angular.Module}.
  3072. *
  3073. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3074. * factories** are functions which, in turn, are created by a **service provider**.
  3075. * The **service providers** are constructor functions. When instantiated they must contain a
  3076. * property called `$get`, which holds the **service factory** function.
  3077. *
  3078. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3079. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3080. * function to get the instance of the **service**.
  3081. *
  3082. * Often services have no configuration options and there is no need to add methods to the service
  3083. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3084. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3085. * services without specifying a provider.
  3086. *
  3087. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3088. * {@link auto.$injector $injector}
  3089. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3090. * providers and services.
  3091. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3092. * services, not providers.
  3093. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3094. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3095. * given factory function.
  3096. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3097. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3098. * a new object using the given constructor function.
  3099. *
  3100. * See the individual methods for more information and examples.
  3101. */
  3102. /**
  3103. * @ngdoc method
  3104. * @name $provide#provider
  3105. * @description
  3106. *
  3107. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3108. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3109. * service.
  3110. *
  3111. * Service provider names start with the name of the service they provide followed by `Provider`.
  3112. * For example, the {@link ng.$log $log} service has a provider called
  3113. * {@link ng.$logProvider $logProvider}.
  3114. *
  3115. * Service provider objects can have additional methods which allow configuration of the provider
  3116. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3117. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3118. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3119. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3120. * console or not.
  3121. *
  3122. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3123. 'Provider'` key.
  3124. * @param {(Object|function())} provider If the provider is:
  3125. *
  3126. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3127. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3128. * - `Constructor`: a new instance of the provider will be created using
  3129. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3130. *
  3131. * @returns {Object} registered provider instance
  3132. * @example
  3133. *
  3134. * The following example shows how to create a simple event tracking service and register it using
  3135. * {@link auto.$provide#provider $provide.provider()}.
  3136. *
  3137. * ```js
  3138. * // Define the eventTracker provider
  3139. * function EventTrackerProvider() {
  3140. * var trackingUrl = '/track';
  3141. *
  3142. * // A provider method for configuring where the tracked events should been saved
  3143. * this.setTrackingUrl = function(url) {
  3144. * trackingUrl = url;
  3145. * };
  3146. *
  3147. * // The service factory function
  3148. * this.$get = ['$http', function($http) {
  3149. * var trackedEvents = {};
  3150. * return {
  3151. * // Call this to track an event
  3152. * event: function(event) {
  3153. * var count = trackedEvents[event] || 0;
  3154. * count += 1;
  3155. * trackedEvents[event] = count;
  3156. * return count;
  3157. * },
  3158. * // Call this to save the tracked events to the trackingUrl
  3159. * save: function() {
  3160. * $http.post(trackingUrl, trackedEvents);
  3161. * }
  3162. * };
  3163. * }];
  3164. * }
  3165. *
  3166. * describe('eventTracker', function() {
  3167. * var postSpy;
  3168. *
  3169. * beforeEach(module(function($provide) {
  3170. * // Register the eventTracker provider
  3171. * $provide.provider('eventTracker', EventTrackerProvider);
  3172. * }));
  3173. *
  3174. * beforeEach(module(function(eventTrackerProvider) {
  3175. * // Configure eventTracker provider
  3176. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3177. * }));
  3178. *
  3179. * it('tracks events', inject(function(eventTracker) {
  3180. * expect(eventTracker.event('login')).toEqual(1);
  3181. * expect(eventTracker.event('login')).toEqual(2);
  3182. * }));
  3183. *
  3184. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3185. * postSpy = spyOn($http, 'post');
  3186. * eventTracker.event('login');
  3187. * eventTracker.save();
  3188. * expect(postSpy).toHaveBeenCalled();
  3189. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3190. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3191. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3192. * }));
  3193. * });
  3194. * ```
  3195. */
  3196. /**
  3197. * @ngdoc method
  3198. * @name $provide#factory
  3199. * @description
  3200. *
  3201. * Register a **service factory**, which will be called to return the service instance.
  3202. * This is short for registering a service where its provider consists of only a `$get` property,
  3203. * which is the given service factory function.
  3204. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3205. * configure your service in a provider.
  3206. *
  3207. * @param {string} name The name of the instance.
  3208. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3209. * for `$provide.provider(name, {$get: $getFn})`.
  3210. * @returns {Object} registered provider instance
  3211. *
  3212. * @example
  3213. * Here is an example of registering a service
  3214. * ```js
  3215. * $provide.factory('ping', ['$http', function($http) {
  3216. * return function ping() {
  3217. * return $http.send('/ping');
  3218. * };
  3219. * }]);
  3220. * ```
  3221. * You would then inject and use this service like this:
  3222. * ```js
  3223. * someModule.controller('Ctrl', ['ping', function(ping) {
  3224. * ping();
  3225. * }]);
  3226. * ```
  3227. */
  3228. /**
  3229. * @ngdoc method
  3230. * @name $provide#service
  3231. * @description
  3232. *
  3233. * Register a **service constructor**, which will be invoked with `new` to create the service
  3234. * instance.
  3235. * This is short for registering a service where its provider's `$get` property is the service
  3236. * constructor function that will be used to instantiate the service instance.
  3237. *
  3238. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3239. * as a type/class.
  3240. *
  3241. * @param {string} name The name of the instance.
  3242. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3243. * @returns {Object} registered provider instance
  3244. *
  3245. * @example
  3246. * Here is an example of registering a service using
  3247. * {@link auto.$provide#service $provide.service(class)}.
  3248. * ```js
  3249. * var Ping = function($http) {
  3250. * this.$http = $http;
  3251. * };
  3252. *
  3253. * Ping.$inject = ['$http'];
  3254. *
  3255. * Ping.prototype.send = function() {
  3256. * return this.$http.get('/ping');
  3257. * };
  3258. * $provide.service('ping', Ping);
  3259. * ```
  3260. * You would then inject and use this service like this:
  3261. * ```js
  3262. * someModule.controller('Ctrl', ['ping', function(ping) {
  3263. * ping.send();
  3264. * }]);
  3265. * ```
  3266. */
  3267. /**
  3268. * @ngdoc method
  3269. * @name $provide#value
  3270. * @description
  3271. *
  3272. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3273. * number, an array, an object or a function. This is short for registering a service where its
  3274. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3275. * service**.
  3276. *
  3277. * Value services are similar to constant services, except that they cannot be injected into a
  3278. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3279. * an Angular
  3280. * {@link auto.$provide#decorator decorator}.
  3281. *
  3282. * @param {string} name The name of the instance.
  3283. * @param {*} value The value.
  3284. * @returns {Object} registered provider instance
  3285. *
  3286. * @example
  3287. * Here are some examples of creating value services.
  3288. * ```js
  3289. * $provide.value('ADMIN_USER', 'admin');
  3290. *
  3291. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3292. *
  3293. * $provide.value('halfOf', function(value) {
  3294. * return value / 2;
  3295. * });
  3296. * ```
  3297. */
  3298. /**
  3299. * @ngdoc method
  3300. * @name $provide#constant
  3301. * @description
  3302. *
  3303. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3304. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3305. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3306. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3307. *
  3308. * @param {string} name The name of the constant.
  3309. * @param {*} value The constant value.
  3310. * @returns {Object} registered instance
  3311. *
  3312. * @example
  3313. * Here a some examples of creating constants:
  3314. * ```js
  3315. * $provide.constant('SHARD_HEIGHT', 306);
  3316. *
  3317. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3318. *
  3319. * $provide.constant('double', function(value) {
  3320. * return value * 2;
  3321. * });
  3322. * ```
  3323. */
  3324. /**
  3325. * @ngdoc method
  3326. * @name $provide#decorator
  3327. * @description
  3328. *
  3329. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3330. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3331. * service. The object returned by the decorator may be the original service, or a new service
  3332. * object which replaces or wraps and delegates to the original service.
  3333. *
  3334. * @param {string} name The name of the service to decorate.
  3335. * @param {function()} decorator This function will be invoked when the service needs to be
  3336. * instantiated and should return the decorated service instance. The function is called using
  3337. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3338. * Local injection arguments:
  3339. *
  3340. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3341. * decorated or delegated to.
  3342. *
  3343. * @example
  3344. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3345. * calls to {@link ng.$log#error $log.warn()}.
  3346. * ```js
  3347. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3348. * $delegate.warn = $delegate.error;
  3349. * return $delegate;
  3350. * }]);
  3351. * ```
  3352. */
  3353. function createInjector(modulesToLoad) {
  3354. var INSTANTIATING = {},
  3355. providerSuffix = 'Provider',
  3356. path = [],
  3357. loadedModules = new HashMap(),
  3358. providerCache = {
  3359. $provide: {
  3360. provider: supportObject(provider),
  3361. factory: supportObject(factory),
  3362. service: supportObject(service),
  3363. value: supportObject(value),
  3364. constant: supportObject(constant),
  3365. decorator: decorator
  3366. }
  3367. },
  3368. providerInjector = (providerCache.$injector =
  3369. createInternalInjector(providerCache, function() {
  3370. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3371. })),
  3372. instanceCache = {},
  3373. instanceInjector = (instanceCache.$injector =
  3374. createInternalInjector(instanceCache, function(servicename) {
  3375. var provider = providerInjector.get(servicename + providerSuffix);
  3376. return instanceInjector.invoke(provider.$get, provider);
  3377. }));
  3378. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3379. return instanceInjector;
  3380. ////////////////////////////////////
  3381. // $provider
  3382. ////////////////////////////////////
  3383. function supportObject(delegate) {
  3384. return function(key, value) {
  3385. if (isObject(key)) {
  3386. forEach(key, reverseParams(delegate));
  3387. } else {
  3388. return delegate(key, value);
  3389. }
  3390. };
  3391. }
  3392. function provider(name, provider_) {
  3393. assertNotHasOwnProperty(name, 'service');
  3394. if (isFunction(provider_) || isArray(provider_)) {
  3395. provider_ = providerInjector.instantiate(provider_);
  3396. }
  3397. if (!provider_.$get) {
  3398. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3399. }
  3400. return providerCache[name + providerSuffix] = provider_;
  3401. }
  3402. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3403. function service(name, constructor) {
  3404. return factory(name, ['$injector', function($injector) {
  3405. return $injector.instantiate(constructor);
  3406. }]);
  3407. }
  3408. function value(name, val) { return factory(name, valueFn(val)); }
  3409. function constant(name, value) {
  3410. assertNotHasOwnProperty(name, 'constant');
  3411. providerCache[name] = value;
  3412. instanceCache[name] = value;
  3413. }
  3414. function decorator(serviceName, decorFn) {
  3415. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3416. orig$get = origProvider.$get;
  3417. origProvider.$get = function() {
  3418. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3419. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3420. };
  3421. }
  3422. ////////////////////////////////////
  3423. // Module Loading
  3424. ////////////////////////////////////
  3425. function loadModules(modulesToLoad){
  3426. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3427. forEach(modulesToLoad, function(module) {
  3428. if (loadedModules.get(module)) return;
  3429. loadedModules.put(module, true);
  3430. try {
  3431. if (isString(module)) {
  3432. moduleFn = angularModule(module);
  3433. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3434. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3435. var invokeArgs = invokeQueue[i],
  3436. provider = providerInjector.get(invokeArgs[0]);
  3437. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3438. }
  3439. } else if (isFunction(module)) {
  3440. runBlocks.push(providerInjector.invoke(module));
  3441. } else if (isArray(module)) {
  3442. runBlocks.push(providerInjector.invoke(module));
  3443. } else {
  3444. assertArgFn(module, 'module');
  3445. }
  3446. } catch (e) {
  3447. if (isArray(module)) {
  3448. module = module[module.length - 1];
  3449. }
  3450. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3451. // Safari & FF's stack traces don't contain error.message content
  3452. // unlike those of Chrome and IE
  3453. // So if stack doesn't contain message, we create a new string that contains both.
  3454. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3455. /* jshint -W022 */
  3456. e = e.message + '\n' + e.stack;
  3457. }
  3458. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3459. module, e.stack || e.message || e);
  3460. }
  3461. });
  3462. return runBlocks;
  3463. }
  3464. ////////////////////////////////////
  3465. // internal Injector
  3466. ////////////////////////////////////
  3467. function createInternalInjector(cache, factory) {
  3468. function getService(serviceName) {
  3469. if (cache.hasOwnProperty(serviceName)) {
  3470. if (cache[serviceName] === INSTANTIATING) {
  3471. throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
  3472. }
  3473. return cache[serviceName];
  3474. } else {
  3475. try {
  3476. path.unshift(serviceName);
  3477. cache[serviceName] = INSTANTIATING;
  3478. return cache[serviceName] = factory(serviceName);
  3479. } catch (err) {
  3480. if (cache[serviceName] === INSTANTIATING) {
  3481. delete cache[serviceName];
  3482. }
  3483. throw err;
  3484. } finally {
  3485. path.shift();
  3486. }
  3487. }
  3488. }
  3489. function invoke(fn, self, locals){
  3490. var args = [],
  3491. $inject = annotate(fn),
  3492. length, i,
  3493. key;
  3494. for(i = 0, length = $inject.length; i < length; i++) {
  3495. key = $inject[i];
  3496. if (typeof key !== 'string') {
  3497. throw $injectorMinErr('itkn',
  3498. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3499. }
  3500. args.push(
  3501. locals && locals.hasOwnProperty(key)
  3502. ? locals[key]
  3503. : getService(key)
  3504. );
  3505. }
  3506. if (!fn.$inject) {
  3507. // this means that we must be an array.
  3508. fn = fn[length];
  3509. }
  3510. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3511. // #5388
  3512. return fn.apply(self, args);
  3513. }
  3514. function instantiate(Type, locals) {
  3515. var Constructor = function() {},
  3516. instance, returnedValue;
  3517. // Check if Type is annotated and use just the given function at n-1 as parameter
  3518. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3519. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3520. instance = new Constructor();
  3521. returnedValue = invoke(Type, instance, locals);
  3522. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3523. }
  3524. return {
  3525. invoke: invoke,
  3526. instantiate: instantiate,
  3527. get: getService,
  3528. annotate: annotate,
  3529. has: function(name) {
  3530. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3531. }
  3532. };
  3533. }
  3534. }
  3535. /**
  3536. * @ngdoc service
  3537. * @name $anchorScroll
  3538. * @kind function
  3539. * @requires $window
  3540. * @requires $location
  3541. * @requires $rootScope
  3542. *
  3543. * @description
  3544. * When called, it checks current value of `$location.hash()` and scrolls to the related element,
  3545. * according to rules specified in
  3546. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3547. *
  3548. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3549. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3550. *
  3551. * @example
  3552. <example>
  3553. <file name="index.html">
  3554. <div id="scrollArea" ng-controller="ScrollCtrl">
  3555. <a ng-click="gotoBottom()">Go to bottom</a>
  3556. <a id="bottom"></a> You're at the bottom!
  3557. </div>
  3558. </file>
  3559. <file name="script.js">
  3560. function ScrollCtrl($scope, $location, $anchorScroll) {
  3561. $scope.gotoBottom = function (){
  3562. // set the location.hash to the id of
  3563. // the element you wish to scroll to.
  3564. $location.hash('bottom');
  3565. // call $anchorScroll()
  3566. $anchorScroll();
  3567. };
  3568. }
  3569. </file>
  3570. <file name="style.css">
  3571. #scrollArea {
  3572. height: 350px;
  3573. overflow: auto;
  3574. }
  3575. #bottom {
  3576. display: block;
  3577. margin-top: 2000px;
  3578. }
  3579. </file>
  3580. </example>
  3581. */
  3582. function $AnchorScrollProvider() {
  3583. var autoScrollingEnabled = true;
  3584. this.disableAutoScrolling = function() {
  3585. autoScrollingEnabled = false;
  3586. };
  3587. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3588. var document = $window.document;
  3589. // helper function to get first anchor from a NodeList
  3590. // can't use filter.filter, as it accepts only instances of Array
  3591. // and IE can't convert NodeList to an array using [].slice
  3592. // TODO(vojta): use filter if we change it to accept lists as well
  3593. function getFirstAnchor(list) {
  3594. var result = null;
  3595. forEach(list, function(element) {
  3596. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3597. });
  3598. return result;
  3599. }
  3600. function scroll() {
  3601. var hash = $location.hash(), elm;
  3602. // empty hash, scroll to the top of the page
  3603. if (!hash) $window.scrollTo(0, 0);
  3604. // element with given id
  3605. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3606. // first anchor with given name :-D
  3607. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3608. // no element and hash == 'top', scroll to the top of the page
  3609. else if (hash === 'top') $window.scrollTo(0, 0);
  3610. }
  3611. // does not scroll when user clicks on anchor link that is currently on
  3612. // (no url change, no $location.hash() change), browser native does scroll
  3613. if (autoScrollingEnabled) {
  3614. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3615. function autoScrollWatchAction() {
  3616. $rootScope.$evalAsync(scroll);
  3617. });
  3618. }
  3619. return scroll;
  3620. }];
  3621. }
  3622. var $animateMinErr = minErr('$animate');
  3623. /**
  3624. * @ngdoc provider
  3625. * @name $animateProvider
  3626. *
  3627. * @description
  3628. * Default implementation of $animate that doesn't perform any animations, instead just
  3629. * synchronously performs DOM
  3630. * updates and calls done() callbacks.
  3631. *
  3632. * In order to enable animations the ngAnimate module has to be loaded.
  3633. *
  3634. * To see the functional implementation check out src/ngAnimate/animate.js
  3635. */
  3636. var $AnimateProvider = ['$provide', function($provide) {
  3637. this.$$selectors = {};
  3638. /**
  3639. * @ngdoc method
  3640. * @name $animateProvider#register
  3641. *
  3642. * @description
  3643. * Registers a new injectable animation factory function. The factory function produces the
  3644. * animation object which contains callback functions for each event that is expected to be
  3645. * animated.
  3646. *
  3647. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3648. * must be called once the element animation is complete. If a function is returned then the
  3649. * animation service will use this function to cancel the animation whenever a cancel event is
  3650. * triggered.
  3651. *
  3652. *
  3653. * ```js
  3654. * return {
  3655. * eventFn : function(element, done) {
  3656. * //code to run the animation
  3657. * //once complete, then run done()
  3658. * return function cancellationFunction() {
  3659. * //code to cancel the animation
  3660. * }
  3661. * }
  3662. * }
  3663. * ```
  3664. *
  3665. * @param {string} name The name of the animation.
  3666. * @param {Function} factory The factory function that will be executed to return the animation
  3667. * object.
  3668. */
  3669. this.register = function(name, factory) {
  3670. var key = name + '-animation';
  3671. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3672. "Expecting class selector starting with '.' got '{0}'.", name);
  3673. this.$$selectors[name.substr(1)] = key;
  3674. $provide.factory(key, factory);
  3675. };
  3676. /**
  3677. * @ngdoc method
  3678. * @name $animateProvider#classNameFilter
  3679. *
  3680. * @description
  3681. * Sets and/or returns the CSS class regular expression that is checked when performing
  3682. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3683. * therefore enable $animate to attempt to perform an animation on any element.
  3684. * When setting the classNameFilter value, animations will only be performed on elements
  3685. * that successfully match the filter expression. This in turn can boost performance
  3686. * for low-powered devices as well as applications containing a lot of structural operations.
  3687. * @param {RegExp=} expression The className expression which will be checked against all animations
  3688. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3689. */
  3690. this.classNameFilter = function(expression) {
  3691. if(arguments.length === 1) {
  3692. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3693. }
  3694. return this.$$classNameFilter;
  3695. };
  3696. this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
  3697. function async(fn) {
  3698. fn && $$asyncCallback(fn);
  3699. }
  3700. /**
  3701. *
  3702. * @ngdoc service
  3703. * @name $animate
  3704. * @description The $animate service provides rudimentary DOM manipulation functions to
  3705. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3706. * This service is the core service used by the ngAnimate $animator service which provides
  3707. * high-level animation hooks for CSS and JavaScript.
  3708. *
  3709. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3710. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3711. * manipulation operations.
  3712. *
  3713. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3714. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3715. * page}.
  3716. */
  3717. return {
  3718. /**
  3719. *
  3720. * @ngdoc method
  3721. * @name $animate#enter
  3722. * @kind function
  3723. * @description Inserts the element into the DOM either after the `after` element or within
  3724. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3725. * @param {DOMElement} element the element which will be inserted into the DOM
  3726. * @param {DOMElement} parent the parent element which will append the element as
  3727. * a child (if the after element is not present)
  3728. * @param {DOMElement} after the sibling element which will append the element
  3729. * after itself
  3730. * @param {Function=} done callback function that will be called after the element has been
  3731. * inserted into the DOM
  3732. */
  3733. enter : function(element, parent, after, done) {
  3734. if (after) {
  3735. after.after(element);
  3736. } else {
  3737. if (!parent || !parent[0]) {
  3738. parent = after.parent();
  3739. }
  3740. parent.append(element);
  3741. }
  3742. async(done);
  3743. },
  3744. /**
  3745. *
  3746. * @ngdoc method
  3747. * @name $animate#leave
  3748. * @kind function
  3749. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3750. * fired (if provided).
  3751. * @param {DOMElement} element the element which will be removed from the DOM
  3752. * @param {Function=} done callback function that will be called after the element has been
  3753. * removed from the DOM
  3754. */
  3755. leave : function(element, done) {
  3756. element.remove();
  3757. async(done);
  3758. },
  3759. /**
  3760. *
  3761. * @ngdoc method
  3762. * @name $animate#move
  3763. * @kind function
  3764. * @description Moves the position of the provided element within the DOM to be placed
  3765. * either after the `after` element or inside of the `parent` element. Once complete, the
  3766. * done() callback will be fired (if provided).
  3767. *
  3768. * @param {DOMElement} element the element which will be moved around within the
  3769. * DOM
  3770. * @param {DOMElement} parent the parent element where the element will be
  3771. * inserted into (if the after element is not present)
  3772. * @param {DOMElement} after the sibling element where the element will be
  3773. * positioned next to
  3774. * @param {Function=} done the callback function (if provided) that will be fired after the
  3775. * element has been moved to its new position
  3776. */
  3777. move : function(element, parent, after, done) {
  3778. // Do not remove element before insert. Removing will cause data associated with the
  3779. // element to be dropped. Insert will implicitly do the remove.
  3780. this.enter(element, parent, after, done);
  3781. },
  3782. /**
  3783. *
  3784. * @ngdoc method
  3785. * @name $animate#addClass
  3786. * @kind function
  3787. * @description Adds the provided className CSS class value to the provided element. Once
  3788. * complete, the done() callback will be fired (if provided).
  3789. * @param {DOMElement} element the element which will have the className value
  3790. * added to it
  3791. * @param {string} className the CSS class which will be added to the element
  3792. * @param {Function=} done the callback function (if provided) that will be fired after the
  3793. * className value has been added to the element
  3794. */
  3795. addClass : function(element, className, done) {
  3796. className = isString(className) ?
  3797. className :
  3798. isArray(className) ? className.join(' ') : '';
  3799. forEach(element, function (element) {
  3800. jqLiteAddClass(element, className);
  3801. });
  3802. async(done);
  3803. },
  3804. /**
  3805. *
  3806. * @ngdoc method
  3807. * @name $animate#removeClass
  3808. * @kind function
  3809. * @description Removes the provided className CSS class value from the provided element.
  3810. * Once complete, the done() callback will be fired (if provided).
  3811. * @param {DOMElement} element the element which will have the className value
  3812. * removed from it
  3813. * @param {string} className the CSS class which will be removed from the element
  3814. * @param {Function=} done the callback function (if provided) that will be fired after the
  3815. * className value has been removed from the element
  3816. */
  3817. removeClass : function(element, className, done) {
  3818. className = isString(className) ?
  3819. className :
  3820. isArray(className) ? className.join(' ') : '';
  3821. forEach(element, function (element) {
  3822. jqLiteRemoveClass(element, className);
  3823. });
  3824. async(done);
  3825. },
  3826. /**
  3827. *
  3828. * @ngdoc method
  3829. * @name $animate#setClass
  3830. * @kind function
  3831. * @description Adds and/or removes the given CSS classes to and from the element.
  3832. * Once complete, the done() callback will be fired (if provided).
  3833. * @param {DOMElement} element the element which will have its CSS classes changed
  3834. * removed from it
  3835. * @param {string} add the CSS classes which will be added to the element
  3836. * @param {string} remove the CSS class which will be removed from the element
  3837. * @param {Function=} done the callback function (if provided) that will be fired after the
  3838. * CSS classes have been set on the element
  3839. */
  3840. setClass : function(element, add, remove, done) {
  3841. forEach(element, function (element) {
  3842. jqLiteAddClass(element, add);
  3843. jqLiteRemoveClass(element, remove);
  3844. });
  3845. async(done);
  3846. },
  3847. enabled : noop
  3848. };
  3849. }];
  3850. }];
  3851. function $$AsyncCallbackProvider(){
  3852. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  3853. return $$rAF.supported
  3854. ? function(fn) { return $$rAF(fn); }
  3855. : function(fn) {
  3856. return $timeout(fn, 0, false);
  3857. };
  3858. }];
  3859. }
  3860. /**
  3861. * ! This is a private undocumented service !
  3862. *
  3863. * @name $browser
  3864. * @requires $log
  3865. * @description
  3866. * This object has two goals:
  3867. *
  3868. * - hide all the global state in the browser caused by the window object
  3869. * - abstract away all the browser specific features and inconsistencies
  3870. *
  3871. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3872. * service, which can be used for convenient testing of the application without the interaction with
  3873. * the real browser apis.
  3874. */
  3875. /**
  3876. * @param {object} window The global window object.
  3877. * @param {object} document jQuery wrapped document.
  3878. * @param {function()} XHR XMLHttpRequest constructor.
  3879. * @param {object} $log console.log or an object with the same interface.
  3880. * @param {object} $sniffer $sniffer service
  3881. */
  3882. function Browser(window, document, $log, $sniffer) {
  3883. var self = this,
  3884. rawDocument = document[0],
  3885. location = window.location,
  3886. history = window.history,
  3887. setTimeout = window.setTimeout,
  3888. clearTimeout = window.clearTimeout,
  3889. pendingDeferIds = {};
  3890. self.isMock = false;
  3891. var outstandingRequestCount = 0;
  3892. var outstandingRequestCallbacks = [];
  3893. // TODO(vojta): remove this temporary api
  3894. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3895. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3896. /**
  3897. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3898. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3899. */
  3900. function completeOutstandingRequest(fn) {
  3901. try {
  3902. fn.apply(null, sliceArgs(arguments, 1));
  3903. } finally {
  3904. outstandingRequestCount--;
  3905. if (outstandingRequestCount === 0) {
  3906. while(outstandingRequestCallbacks.length) {
  3907. try {
  3908. outstandingRequestCallbacks.pop()();
  3909. } catch (e) {
  3910. $log.error(e);
  3911. }
  3912. }
  3913. }
  3914. }
  3915. }
  3916. /**
  3917. * @private
  3918. * Note: this method is used only by scenario runner
  3919. * TODO(vojta): prefix this method with $$ ?
  3920. * @param {function()} callback Function that will be called when no outstanding request
  3921. */
  3922. self.notifyWhenNoOutstandingRequests = function(callback) {
  3923. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3924. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3925. // regular poller would result in flaky tests.
  3926. forEach(pollFns, function(pollFn){ pollFn(); });
  3927. if (outstandingRequestCount === 0) {
  3928. callback();
  3929. } else {
  3930. outstandingRequestCallbacks.push(callback);
  3931. }
  3932. };
  3933. //////////////////////////////////////////////////////////////
  3934. // Poll Watcher API
  3935. //////////////////////////////////////////////////////////////
  3936. var pollFns = [],
  3937. pollTimeout;
  3938. /**
  3939. * @name $browser#addPollFn
  3940. *
  3941. * @param {function()} fn Poll function to add
  3942. *
  3943. * @description
  3944. * Adds a function to the list of functions that poller periodically executes,
  3945. * and starts polling if not started yet.
  3946. *
  3947. * @returns {function()} the added function
  3948. */
  3949. self.addPollFn = function(fn) {
  3950. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  3951. pollFns.push(fn);
  3952. return fn;
  3953. };
  3954. /**
  3955. * @param {number} interval How often should browser call poll functions (ms)
  3956. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  3957. *
  3958. * @description
  3959. * Configures the poller to run in the specified intervals, using the specified
  3960. * setTimeout fn and kicks it off.
  3961. */
  3962. function startPoller(interval, setTimeout) {
  3963. (function check() {
  3964. forEach(pollFns, function(pollFn){ pollFn(); });
  3965. pollTimeout = setTimeout(check, interval);
  3966. })();
  3967. }
  3968. //////////////////////////////////////////////////////////////
  3969. // URL API
  3970. //////////////////////////////////////////////////////////////
  3971. var lastBrowserUrl = location.href,
  3972. baseElement = document.find('base'),
  3973. newLocation = null;
  3974. /**
  3975. * @name $browser#url
  3976. *
  3977. * @description
  3978. * GETTER:
  3979. * Without any argument, this method just returns current value of location.href.
  3980. *
  3981. * SETTER:
  3982. * With at least one argument, this method sets url to new value.
  3983. * If html5 history api supported, pushState/replaceState is used, otherwise
  3984. * location.href/location.replace is used.
  3985. * Returns its own instance to allow chaining
  3986. *
  3987. * NOTE: this api is intended for use only by the $location service. Please use the
  3988. * {@link ng.$location $location service} to change url.
  3989. *
  3990. * @param {string} url New url (when used as setter)
  3991. * @param {boolean=} replace Should new url replace current history record ?
  3992. */
  3993. self.url = function(url, replace) {
  3994. // Android Browser BFCache causes location, history reference to become stale.
  3995. if (location !== window.location) location = window.location;
  3996. if (history !== window.history) history = window.history;
  3997. // setter
  3998. if (url) {
  3999. if (lastBrowserUrl == url) return;
  4000. lastBrowserUrl = url;
  4001. if ($sniffer.history) {
  4002. if (replace) history.replaceState(null, '', url);
  4003. else {
  4004. history.pushState(null, '', url);
  4005. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  4006. baseElement.attr('href', baseElement.attr('href'));
  4007. }
  4008. } else {
  4009. newLocation = url;
  4010. if (replace) {
  4011. location.replace(url);
  4012. } else {
  4013. location.href = url;
  4014. }
  4015. }
  4016. return self;
  4017. // getter
  4018. } else {
  4019. // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
  4020. // methods not updating location.href synchronously.
  4021. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4022. return newLocation || location.href.replace(/%27/g,"'");
  4023. }
  4024. };
  4025. var urlChangeListeners = [],
  4026. urlChangeInit = false;
  4027. function fireUrlChange() {
  4028. newLocation = null;
  4029. if (lastBrowserUrl == self.url()) return;
  4030. lastBrowserUrl = self.url();
  4031. forEach(urlChangeListeners, function(listener) {
  4032. listener(self.url());
  4033. });
  4034. }
  4035. /**
  4036. * @name $browser#onUrlChange
  4037. *
  4038. * @description
  4039. * Register callback function that will be called, when url changes.
  4040. *
  4041. * It's only called when the url is changed from outside of angular:
  4042. * - user types different url into address bar
  4043. * - user clicks on history (forward/back) button
  4044. * - user clicks on a link
  4045. *
  4046. * It's not called when url is changed by $browser.url() method
  4047. *
  4048. * The listener gets called with new url as parameter.
  4049. *
  4050. * NOTE: this api is intended for use only by the $location service. Please use the
  4051. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4052. *
  4053. * @param {function(string)} listener Listener function to be called when url changes.
  4054. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4055. */
  4056. self.onUrlChange = function(callback) {
  4057. // TODO(vojta): refactor to use node's syntax for events
  4058. if (!urlChangeInit) {
  4059. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4060. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4061. // changed by push/replaceState
  4062. // html5 history api - popstate event
  4063. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  4064. // hashchange event
  4065. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  4066. // polling
  4067. else self.addPollFn(fireUrlChange);
  4068. urlChangeInit = true;
  4069. }
  4070. urlChangeListeners.push(callback);
  4071. return callback;
  4072. };
  4073. //////////////////////////////////////////////////////////////
  4074. // Misc API
  4075. //////////////////////////////////////////////////////////////
  4076. /**
  4077. * @name $browser#baseHref
  4078. *
  4079. * @description
  4080. * Returns current <base href>
  4081. * (always relative - without domain)
  4082. *
  4083. * @returns {string} The current base href
  4084. */
  4085. self.baseHref = function() {
  4086. var href = baseElement.attr('href');
  4087. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4088. };
  4089. //////////////////////////////////////////////////////////////
  4090. // Cookies API
  4091. //////////////////////////////////////////////////////////////
  4092. var lastCookies = {};
  4093. var lastCookieString = '';
  4094. var cookiePath = self.baseHref();
  4095. /**
  4096. * @name $browser#cookies
  4097. *
  4098. * @param {string=} name Cookie name
  4099. * @param {string=} value Cookie value
  4100. *
  4101. * @description
  4102. * The cookies method provides a 'private' low level access to browser cookies.
  4103. * It is not meant to be used directly, use the $cookie service instead.
  4104. *
  4105. * The return values vary depending on the arguments that the method was called with as follows:
  4106. *
  4107. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4108. * it
  4109. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4110. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4111. * way)
  4112. *
  4113. * @returns {Object} Hash of all cookies (if called without any parameter)
  4114. */
  4115. self.cookies = function(name, value) {
  4116. /* global escape: false, unescape: false */
  4117. var cookieLength, cookieArray, cookie, i, index;
  4118. if (name) {
  4119. if (value === undefined) {
  4120. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  4121. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4122. } else {
  4123. if (isString(value)) {
  4124. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  4125. ';path=' + cookiePath).length + 1;
  4126. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4127. // - 300 cookies
  4128. // - 20 cookies per unique domain
  4129. // - 4096 bytes per cookie
  4130. if (cookieLength > 4096) {
  4131. $log.warn("Cookie '"+ name +
  4132. "' possibly not set or overflowed because it was too large ("+
  4133. cookieLength + " > 4096 bytes)!");
  4134. }
  4135. }
  4136. }
  4137. } else {
  4138. if (rawDocument.cookie !== lastCookieString) {
  4139. lastCookieString = rawDocument.cookie;
  4140. cookieArray = lastCookieString.split("; ");
  4141. lastCookies = {};
  4142. for (i = 0; i < cookieArray.length; i++) {
  4143. cookie = cookieArray[i];
  4144. index = cookie.indexOf('=');
  4145. if (index > 0) { //ignore nameless cookies
  4146. name = unescape(cookie.substring(0, index));
  4147. // the first value that is seen for a cookie is the most
  4148. // specific one. values for the same cookie name that
  4149. // follow are for less specific paths.
  4150. if (lastCookies[name] === undefined) {
  4151. lastCookies[name] = unescape(cookie.substring(index + 1));
  4152. }
  4153. }
  4154. }
  4155. }
  4156. return lastCookies;
  4157. }
  4158. };
  4159. /**
  4160. * @name $browser#defer
  4161. * @param {function()} fn A function, who's execution should be deferred.
  4162. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4163. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4164. *
  4165. * @description
  4166. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4167. *
  4168. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4169. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4170. * via `$browser.defer.flush()`.
  4171. *
  4172. */
  4173. self.defer = function(fn, delay) {
  4174. var timeoutId;
  4175. outstandingRequestCount++;
  4176. timeoutId = setTimeout(function() {
  4177. delete pendingDeferIds[timeoutId];
  4178. completeOutstandingRequest(fn);
  4179. }, delay || 0);
  4180. pendingDeferIds[timeoutId] = true;
  4181. return timeoutId;
  4182. };
  4183. /**
  4184. * @name $browser#defer.cancel
  4185. *
  4186. * @description
  4187. * Cancels a deferred task identified with `deferId`.
  4188. *
  4189. * @param {*} deferId Token returned by the `$browser.defer` function.
  4190. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4191. * canceled.
  4192. */
  4193. self.defer.cancel = function(deferId) {
  4194. if (pendingDeferIds[deferId]) {
  4195. delete pendingDeferIds[deferId];
  4196. clearTimeout(deferId);
  4197. completeOutstandingRequest(noop);
  4198. return true;
  4199. }
  4200. return false;
  4201. };
  4202. }
  4203. function $BrowserProvider(){
  4204. this.$get = ['$window', '$log', '$sniffer', '$document',
  4205. function( $window, $log, $sniffer, $document){
  4206. return new Browser($window, $document, $log, $sniffer);
  4207. }];
  4208. }
  4209. /**
  4210. * @ngdoc service
  4211. * @name $cacheFactory
  4212. *
  4213. * @description
  4214. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4215. * them.
  4216. *
  4217. * ```js
  4218. *
  4219. * var cache = $cacheFactory('cacheId');
  4220. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4221. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4222. *
  4223. * cache.put("key", "value");
  4224. * cache.put("another key", "another value");
  4225. *
  4226. * // We've specified no options on creation
  4227. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4228. *
  4229. * ```
  4230. *
  4231. *
  4232. * @param {string} cacheId Name or id of the newly created cache.
  4233. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4234. *
  4235. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4236. *
  4237. * @returns {object} Newly created cache object with the following set of methods:
  4238. *
  4239. * - `{object}` `info()` — Returns id, size, and options of cache.
  4240. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4241. * it.
  4242. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4243. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4244. * - `{void}` `removeAll()` — Removes all cached values.
  4245. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4246. *
  4247. * @example
  4248. <example module="cacheExampleApp">
  4249. <file name="index.html">
  4250. <div ng-controller="CacheController">
  4251. <input ng-model="newCacheKey" placeholder="Key">
  4252. <input ng-model="newCacheValue" placeholder="Value">
  4253. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4254. <p ng-if="keys.length">Cached Values</p>
  4255. <div ng-repeat="key in keys">
  4256. <span ng-bind="key"></span>
  4257. <span>: </span>
  4258. <b ng-bind="cache.get(key)"></b>
  4259. </div>
  4260. <p>Cache Info</p>
  4261. <div ng-repeat="(key, value) in cache.info()">
  4262. <span ng-bind="key"></span>
  4263. <span>: </span>
  4264. <b ng-bind="value"></b>
  4265. </div>
  4266. </div>
  4267. </file>
  4268. <file name="script.js">
  4269. angular.module('cacheExampleApp', []).
  4270. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4271. $scope.keys = [];
  4272. $scope.cache = $cacheFactory('cacheId');
  4273. $scope.put = function(key, value) {
  4274. $scope.cache.put(key, value);
  4275. $scope.keys.push(key);
  4276. };
  4277. }]);
  4278. </file>
  4279. <file name="style.css">
  4280. p {
  4281. margin: 10px 0 3px;
  4282. }
  4283. </file>
  4284. </example>
  4285. */
  4286. function $CacheFactoryProvider() {
  4287. this.$get = function() {
  4288. var caches = {};
  4289. function cacheFactory(cacheId, options) {
  4290. if (cacheId in caches) {
  4291. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4292. }
  4293. var size = 0,
  4294. stats = extend({}, options, {id: cacheId}),
  4295. data = {},
  4296. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4297. lruHash = {},
  4298. freshEnd = null,
  4299. staleEnd = null;
  4300. /**
  4301. * @ngdoc type
  4302. * @name $cacheFactory.Cache
  4303. *
  4304. * @description
  4305. * A cache object used to store and retrieve data, primarily used by
  4306. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4307. * templates and other data.
  4308. *
  4309. * ```js
  4310. * angular.module('superCache')
  4311. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4312. * return $cacheFactory('super-cache');
  4313. * }]);
  4314. * ```
  4315. *
  4316. * Example test:
  4317. *
  4318. * ```js
  4319. * it('should behave like a cache', inject(function(superCache) {
  4320. * superCache.put('key', 'value');
  4321. * superCache.put('another key', 'another value');
  4322. *
  4323. * expect(superCache.info()).toEqual({
  4324. * id: 'super-cache',
  4325. * size: 2
  4326. * });
  4327. *
  4328. * superCache.remove('another key');
  4329. * expect(superCache.get('another key')).toBeUndefined();
  4330. *
  4331. * superCache.removeAll();
  4332. * expect(superCache.info()).toEqual({
  4333. * id: 'super-cache',
  4334. * size: 0
  4335. * });
  4336. * }));
  4337. * ```
  4338. */
  4339. return caches[cacheId] = {
  4340. /**
  4341. * @ngdoc method
  4342. * @name $cacheFactory.Cache#put
  4343. * @kind function
  4344. *
  4345. * @description
  4346. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4347. * retrieved later, and incrementing the size of the cache if the key was not already
  4348. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4349. * entries from the set.
  4350. *
  4351. * It will not insert undefined values into the cache.
  4352. *
  4353. * @param {string} key the key under which the cached data is stored.
  4354. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4355. * will not be stored.
  4356. * @returns {*} the value stored.
  4357. */
  4358. put: function(key, value) {
  4359. if (capacity < Number.MAX_VALUE) {
  4360. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4361. refresh(lruEntry);
  4362. }
  4363. if (isUndefined(value)) return;
  4364. if (!(key in data)) size++;
  4365. data[key] = value;
  4366. if (size > capacity) {
  4367. this.remove(staleEnd.key);
  4368. }
  4369. return value;
  4370. },
  4371. /**
  4372. * @ngdoc method
  4373. * @name $cacheFactory.Cache#get
  4374. * @kind function
  4375. *
  4376. * @description
  4377. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4378. *
  4379. * @param {string} key the key of the data to be retrieved
  4380. * @returns {*} the value stored.
  4381. */
  4382. get: function(key) {
  4383. if (capacity < Number.MAX_VALUE) {
  4384. var lruEntry = lruHash[key];
  4385. if (!lruEntry) return;
  4386. refresh(lruEntry);
  4387. }
  4388. return data[key];
  4389. },
  4390. /**
  4391. * @ngdoc method
  4392. * @name $cacheFactory.Cache#remove
  4393. * @kind function
  4394. *
  4395. * @description
  4396. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4397. *
  4398. * @param {string} key the key of the entry to be removed
  4399. */
  4400. remove: function(key) {
  4401. if (capacity < Number.MAX_VALUE) {
  4402. var lruEntry = lruHash[key];
  4403. if (!lruEntry) return;
  4404. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4405. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4406. link(lruEntry.n,lruEntry.p);
  4407. delete lruHash[key];
  4408. }
  4409. delete data[key];
  4410. size--;
  4411. },
  4412. /**
  4413. * @ngdoc method
  4414. * @name $cacheFactory.Cache#removeAll
  4415. * @kind function
  4416. *
  4417. * @description
  4418. * Clears the cache object of any entries.
  4419. */
  4420. removeAll: function() {
  4421. data = {};
  4422. size = 0;
  4423. lruHash = {};
  4424. freshEnd = staleEnd = null;
  4425. },
  4426. /**
  4427. * @ngdoc method
  4428. * @name $cacheFactory.Cache#destroy
  4429. * @kind function
  4430. *
  4431. * @description
  4432. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4433. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4434. */
  4435. destroy: function() {
  4436. data = null;
  4437. stats = null;
  4438. lruHash = null;
  4439. delete caches[cacheId];
  4440. },
  4441. /**
  4442. * @ngdoc method
  4443. * @name $cacheFactory.Cache#info
  4444. * @kind function
  4445. *
  4446. * @description
  4447. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4448. *
  4449. * @returns {object} an object with the following properties:
  4450. * <ul>
  4451. * <li>**id**: the id of the cache instance</li>
  4452. * <li>**size**: the number of entries kept in the cache instance</li>
  4453. * <li>**...**: any additional properties from the options object when creating the
  4454. * cache.</li>
  4455. * </ul>
  4456. */
  4457. info: function() {
  4458. return extend({}, stats, {size: size});
  4459. }
  4460. };
  4461. /**
  4462. * makes the `entry` the freshEnd of the LRU linked list
  4463. */
  4464. function refresh(entry) {
  4465. if (entry != freshEnd) {
  4466. if (!staleEnd) {
  4467. staleEnd = entry;
  4468. } else if (staleEnd == entry) {
  4469. staleEnd = entry.n;
  4470. }
  4471. link(entry.n, entry.p);
  4472. link(entry, freshEnd);
  4473. freshEnd = entry;
  4474. freshEnd.n = null;
  4475. }
  4476. }
  4477. /**
  4478. * bidirectionally links two entries of the LRU linked list
  4479. */
  4480. function link(nextEntry, prevEntry) {
  4481. if (nextEntry != prevEntry) {
  4482. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4483. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4484. }
  4485. }
  4486. }
  4487. /**
  4488. * @ngdoc method
  4489. * @name $cacheFactory#info
  4490. *
  4491. * @description
  4492. * Get information about all the caches that have been created
  4493. *
  4494. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4495. */
  4496. cacheFactory.info = function() {
  4497. var info = {};
  4498. forEach(caches, function(cache, cacheId) {
  4499. info[cacheId] = cache.info();
  4500. });
  4501. return info;
  4502. };
  4503. /**
  4504. * @ngdoc method
  4505. * @name $cacheFactory#get
  4506. *
  4507. * @description
  4508. * Get access to a cache object by the `cacheId` used when it was created.
  4509. *
  4510. * @param {string} cacheId Name or id of a cache to access.
  4511. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4512. */
  4513. cacheFactory.get = function(cacheId) {
  4514. return caches[cacheId];
  4515. };
  4516. return cacheFactory;
  4517. };
  4518. }
  4519. /**
  4520. * @ngdoc service
  4521. * @name $templateCache
  4522. *
  4523. * @description
  4524. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4525. * can load templates directly into the cache in a `script` tag, or by consuming the
  4526. * `$templateCache` service directly.
  4527. *
  4528. * Adding via the `script` tag:
  4529. *
  4530. * ```html
  4531. * <script type="text/ng-template" id="templateId.html">
  4532. * <p>This is the content of the template</p>
  4533. * </script>
  4534. * ```
  4535. *
  4536. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4537. * the document, but it must be below the `ng-app` definition.
  4538. *
  4539. * Adding via the $templateCache service:
  4540. *
  4541. * ```js
  4542. * var myApp = angular.module('myApp', []);
  4543. * myApp.run(function($templateCache) {
  4544. * $templateCache.put('templateId.html', 'This is the content of the template');
  4545. * });
  4546. * ```
  4547. *
  4548. * To retrieve the template later, simply use it in your HTML:
  4549. * ```html
  4550. * <div ng-include=" 'templateId.html' "></div>
  4551. * ```
  4552. *
  4553. * or get it via Javascript:
  4554. * ```js
  4555. * $templateCache.get('templateId.html')
  4556. * ```
  4557. *
  4558. * See {@link ng.$cacheFactory $cacheFactory}.
  4559. *
  4560. */
  4561. function $TemplateCacheProvider() {
  4562. this.$get = ['$cacheFactory', function($cacheFactory) {
  4563. return $cacheFactory('templates');
  4564. }];
  4565. }
  4566. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4567. *
  4568. * DOM-related variables:
  4569. *
  4570. * - "node" - DOM Node
  4571. * - "element" - DOM Element or Node
  4572. * - "$node" or "$element" - jqLite-wrapped node or element
  4573. *
  4574. *
  4575. * Compiler related stuff:
  4576. *
  4577. * - "linkFn" - linking fn of a single directive
  4578. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4579. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4580. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4581. */
  4582. /**
  4583. * @ngdoc service
  4584. * @name $compile
  4585. * @kind function
  4586. *
  4587. * @description
  4588. * Compiles an HTML string or DOM into a template and produces a template function, which
  4589. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4590. *
  4591. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4592. * {@link ng.$compileProvider#directive directives}.
  4593. *
  4594. * <div class="alert alert-warning">
  4595. * **Note:** This document is an in-depth reference of all directive options.
  4596. * For a gentle introduction to directives with examples of common use cases,
  4597. * see the {@link guide/directive directive guide}.
  4598. * </div>
  4599. *
  4600. * ## Comprehensive Directive API
  4601. *
  4602. * There are many different options for a directive.
  4603. *
  4604. * The difference resides in the return value of the factory function.
  4605. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4606. * or just the `postLink` function (all other properties will have the default values).
  4607. *
  4608. * <div class="alert alert-success">
  4609. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4610. * </div>
  4611. *
  4612. * Here's an example directive declared with a Directive Definition Object:
  4613. *
  4614. * ```js
  4615. * var myModule = angular.module(...);
  4616. *
  4617. * myModule.directive('directiveName', function factory(injectables) {
  4618. * var directiveDefinitionObject = {
  4619. * priority: 0,
  4620. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4621. * // or
  4622. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4623. * transclude: false,
  4624. * restrict: 'A',
  4625. * scope: false,
  4626. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4627. * controllerAs: 'stringAlias',
  4628. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4629. * compile: function compile(tElement, tAttrs, transclude) {
  4630. * return {
  4631. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4632. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4633. * }
  4634. * // or
  4635. * // return function postLink( ... ) { ... }
  4636. * },
  4637. * // or
  4638. * // link: {
  4639. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4640. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4641. * // }
  4642. * // or
  4643. * // link: function postLink( ... ) { ... }
  4644. * };
  4645. * return directiveDefinitionObject;
  4646. * });
  4647. * ```
  4648. *
  4649. * <div class="alert alert-warning">
  4650. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4651. * </div>
  4652. *
  4653. * Therefore the above can be simplified as:
  4654. *
  4655. * ```js
  4656. * var myModule = angular.module(...);
  4657. *
  4658. * myModule.directive('directiveName', function factory(injectables) {
  4659. * var directiveDefinitionObject = {
  4660. * link: function postLink(scope, iElement, iAttrs) { ... }
  4661. * };
  4662. * return directiveDefinitionObject;
  4663. * // or
  4664. * // return function postLink(scope, iElement, iAttrs) { ... }
  4665. * });
  4666. * ```
  4667. *
  4668. *
  4669. *
  4670. * ### Directive Definition Object
  4671. *
  4672. * The directive definition object provides instructions to the {@link ng.$compile
  4673. * compiler}. The attributes are:
  4674. *
  4675. * #### `priority`
  4676. * When there are multiple directives defined on a single DOM element, sometimes it
  4677. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4678. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4679. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4680. * are also run in priority order, but post-link functions are run in reverse order. The order
  4681. * of directives with the same priority is undefined. The default priority is `0`.
  4682. *
  4683. * #### `terminal`
  4684. * If set to true then the current `priority` will be the last set of directives
  4685. * which will execute (any directives at the current priority will still execute
  4686. * as the order of execution on same `priority` is undefined).
  4687. *
  4688. * #### `scope`
  4689. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4690. * same element request a new scope, only one new scope is created. The new scope rule does not
  4691. * apply for the root of the template since the root of the template always gets a new scope.
  4692. *
  4693. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4694. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4695. * when creating reusable components, which should not accidentally read or modify data in the
  4696. * parent scope.
  4697. *
  4698. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4699. * derived from the parent scope. These local properties are useful for aliasing values for
  4700. * templates. Locals definition is a hash of local scope property to its source:
  4701. *
  4702. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4703. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4704. * attribute name is assumed to be the same as the local name.
  4705. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4706. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4707. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4708. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4709. * component scope).
  4710. *
  4711. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4712. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4713. * name is specified then the attribute name is assumed to be the same as the local name.
  4714. * Given `<widget my-attr="parentModel">` and widget definition of
  4715. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4716. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4717. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4718. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4719. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4720. *
  4721. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4722. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4723. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4724. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4725. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4726. * pass data from the isolated scope via an expression and to the parent scope, this can be
  4727. * done by passing a map of local variable names and values into the expression wrapper fn.
  4728. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4729. * by calling the `localFn` as `localFn({amount: 22})`.
  4730. *
  4731. *
  4732. *
  4733. * #### `controller`
  4734. * Controller constructor function. The controller is instantiated before the
  4735. * pre-linking phase and it is shared with other directives (see
  4736. * `require` attribute). This allows the directives to communicate with each other and augment
  4737. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4738. *
  4739. * * `$scope` - Current scope associated with the element
  4740. * * `$element` - Current element
  4741. * * `$attrs` - Current attributes object for the element
  4742. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4743. * The scope can be overridden by an optional first argument.
  4744. * `function([scope], cloneLinkingFn)`.
  4745. *
  4746. *
  4747. * #### `require`
  4748. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4749. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4750. * injected argument will be an array in corresponding order. If no such directive can be
  4751. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4752. *
  4753. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4754. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4755. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  4756. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  4757. * `link` fn if not found.
  4758. *
  4759. *
  4760. * #### `controllerAs`
  4761. * Controller alias at the directive scope. An alias for the controller so it
  4762. * can be referenced at the directive template. The directive needs to define a scope for this
  4763. * configuration to be used. Useful in the case when directive is used as component.
  4764. *
  4765. *
  4766. * #### `restrict`
  4767. * String of subset of `EACM` which restricts the directive to a specific directive
  4768. * declaration style. If omitted, the default (attributes only) is used.
  4769. *
  4770. * * `E` - Element name: `<my-directive></my-directive>`
  4771. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4772. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4773. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4774. *
  4775. *
  4776. * #### `template`
  4777. * replace the current element with the contents of the HTML. The replacement process
  4778. * migrates all of the attributes / classes from the old element to the new one. See the
  4779. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4780. * Directives Guide} for an example.
  4781. *
  4782. * You can specify `template` as a string representing the template or as a function which takes
  4783. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  4784. * returns a string value representing the template.
  4785. *
  4786. *
  4787. * #### `templateUrl`
  4788. * Same as `template` but the template is loaded from the specified URL. Because
  4789. * the template loading is asynchronous the compilation/linking is suspended until the template
  4790. * is loaded.
  4791. *
  4792. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4793. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4794. * a string value representing the url. In either case, the template URL is passed through {@link
  4795. * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4796. *
  4797. *
  4798. * #### `replace` ([*DEPRECATED*!], will be removed in next major release)
  4799. * specify where the template should be inserted. Defaults to `false`.
  4800. *
  4801. * * `true` - the template will replace the current element.
  4802. * * `false` - the template will replace the contents of the current element.
  4803. *
  4804. *
  4805. * #### `transclude`
  4806. * compile the content of the element and make it available to the directive.
  4807. * Typically used with {@link ng.directive:ngTransclude
  4808. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4809. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4810. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4811. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4812. * be bound to the parent (pre-`isolate`) scope.
  4813. *
  4814. * * `true` - transclude the content of the directive.
  4815. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  4816. *
  4817. *
  4818. * #### `compile`
  4819. *
  4820. * ```js
  4821. * function compile(tElement, tAttrs, transclude) { ... }
  4822. * ```
  4823. *
  4824. * The compile function deals with transforming the template DOM. Since most directives do not do
  4825. * template transformation, it is not used often. The compile function takes the following arguments:
  4826. *
  4827. * * `tElement` - template element - The element where the directive has been declared. It is
  4828. * safe to do template transformation on the element and child elements only.
  4829. *
  4830. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4831. * between all directive compile functions.
  4832. *
  4833. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4834. *
  4835. * <div class="alert alert-warning">
  4836. * **Note:** The template instance and the link instance may be different objects if the template has
  4837. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4838. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4839. * should be done in a linking function rather than in a compile function.
  4840. * </div>
  4841. * <div class="alert alert-warning">
  4842. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  4843. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  4844. * stack overflow errors.
  4845. *
  4846. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  4847. * a directive's template instead of relying on automatic template compilation via `template` or
  4848. * `templateUrl` declaration or manual compilation inside the compile function.
  4849. * </div>
  4850. *
  4851. * <div class="alert alert-error">
  4852. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4853. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4854. * to the link function instead.
  4855. * </div>
  4856. * A compile function can have a return value which can be either a function or an object.
  4857. *
  4858. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4859. * `link` property of the config object when the compile function is empty.
  4860. *
  4861. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4862. * control when a linking function should be called during the linking phase. See info about
  4863. * pre-linking and post-linking functions below.
  4864. *
  4865. *
  4866. * #### `link`
  4867. * This property is used only if the `compile` property is not defined.
  4868. *
  4869. * ```js
  4870. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4871. * ```
  4872. *
  4873. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4874. * executed after the template has been cloned. This is where most of the directive logic will be
  4875. * put.
  4876. *
  4877. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  4878. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  4879. *
  4880. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4881. * manipulate the children of the element only in `postLink` function since the children have
  4882. * already been linked.
  4883. *
  4884. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4885. * between all directive linking functions.
  4886. *
  4887. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4888. * element defines a controller. The controller is shared among all the directives, which allows
  4889. * the directives to use the controllers as a communication channel.
  4890. *
  4891. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4892. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4893. * parameter of directive controllers.
  4894. * `function([scope], cloneLinkingFn)`.
  4895. *
  4896. *
  4897. * #### Pre-linking function
  4898. *
  4899. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  4900. * compiler linking function will fail to locate the correct elements for linking.
  4901. *
  4902. * #### Post-linking function
  4903. *
  4904. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  4905. *
  4906. * <a name="Attributes"></a>
  4907. * ### Attributes
  4908. *
  4909. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  4910. * `link()` or `compile()` functions. It has a variety of uses.
  4911. *
  4912. * accessing *Normalized attribute names:*
  4913. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  4914. * the attributes object allows for normalized access to
  4915. * the attributes.
  4916. *
  4917. * * *Directive inter-communication:* All directives share the same instance of the attributes
  4918. * object which allows the directives to use the attributes object as inter directive
  4919. * communication.
  4920. *
  4921. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  4922. * allowing other directives to read the interpolated value.
  4923. *
  4924. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  4925. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  4926. * the only way to easily get the actual value because during the linking phase the interpolation
  4927. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  4928. *
  4929. * ```js
  4930. * function linkingFn(scope, elm, attrs, ctrl) {
  4931. * // get the attribute value
  4932. * console.log(attrs.ngModel);
  4933. *
  4934. * // change the attribute
  4935. * attrs.$set('ngModel', 'new value');
  4936. *
  4937. * // observe changes to interpolated attribute
  4938. * attrs.$observe('ngModel', function(value) {
  4939. * console.log('ngModel has changed value to ' + value);
  4940. * });
  4941. * }
  4942. * ```
  4943. *
  4944. * Below is an example using `$compileProvider`.
  4945. *
  4946. * <div class="alert alert-warning">
  4947. * **Note**: Typically directives are registered with `module.directive`. The example below is
  4948. * to illustrate how `$compile` works.
  4949. * </div>
  4950. *
  4951. <example module="compile">
  4952. <file name="index.html">
  4953. <script>
  4954. angular.module('compile', [], function($compileProvider) {
  4955. // configure new 'compile' directive by passing a directive
  4956. // factory function. The factory function injects the '$compile'
  4957. $compileProvider.directive('compile', function($compile) {
  4958. // directive factory creates a link function
  4959. return function(scope, element, attrs) {
  4960. scope.$watch(
  4961. function(scope) {
  4962. // watch the 'compile' expression for changes
  4963. return scope.$eval(attrs.compile);
  4964. },
  4965. function(value) {
  4966. // when the 'compile' expression changes
  4967. // assign it into the current DOM
  4968. element.html(value);
  4969. // compile the new DOM and link it to the current
  4970. // scope.
  4971. // NOTE: we only compile .childNodes so that
  4972. // we don't get into infinite loop compiling ourselves
  4973. $compile(element.contents())(scope);
  4974. }
  4975. );
  4976. };
  4977. })
  4978. });
  4979. function Ctrl($scope) {
  4980. $scope.name = 'Angular';
  4981. $scope.html = 'Hello {{name}}';
  4982. }
  4983. </script>
  4984. <div ng-controller="Ctrl">
  4985. <input ng-model="name"> <br>
  4986. <textarea ng-model="html"></textarea> <br>
  4987. <div compile="html"></div>
  4988. </div>
  4989. </file>
  4990. <file name="protractor.js" type="protractor">
  4991. it('should auto compile', function() {
  4992. var textarea = $('textarea');
  4993. var output = $('div[compile]');
  4994. // The initial state reads 'Hello Angular'.
  4995. expect(output.getText()).toBe('Hello Angular');
  4996. textarea.clear();
  4997. textarea.sendKeys('{{name}}!');
  4998. expect(output.getText()).toBe('Angular!');
  4999. });
  5000. </file>
  5001. </example>
  5002. *
  5003. *
  5004. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5005. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  5006. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5007. * root element(s), not their children)
  5008. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  5009. * (a DOM element/tree) to a scope. Where:
  5010. *
  5011. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5012. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5013. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5014. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5015. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5016. *
  5017. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5018. * * `scope` - is the current scope with which the linking function is working with.
  5019. *
  5020. * Calling the linking function returns the element of the template. It is either the original
  5021. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5022. *
  5023. * After linking the view is not updated until after a call to $digest which typically is done by
  5024. * Angular automatically.
  5025. *
  5026. * If you need access to the bound view, there are two ways to do it:
  5027. *
  5028. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5029. * before you send them to the compiler and keep this reference around.
  5030. * ```js
  5031. * var element = $compile('<p>{{total}}</p>')(scope);
  5032. * ```
  5033. *
  5034. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5035. * example would not point to the clone, but rather to the original template that was cloned. In
  5036. * this case, you can access the clone via the cloneAttachFn:
  5037. * ```js
  5038. * var templateElement = angular.element('<p>{{total}}</p>'),
  5039. * scope = ....;
  5040. *
  5041. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5042. * //attach the clone to DOM document at the right place
  5043. * });
  5044. *
  5045. * //now we have reference to the cloned DOM via `clonedElement`
  5046. * ```
  5047. *
  5048. *
  5049. * For information on how the compiler works, see the
  5050. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5051. */
  5052. var $compileMinErr = minErr('$compile');
  5053. /**
  5054. * @ngdoc provider
  5055. * @name $compileProvider
  5056. * @kind function
  5057. *
  5058. * @description
  5059. */
  5060. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5061. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5062. var hasDirectives = {},
  5063. Suffix = 'Directive',
  5064. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
  5065. CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/;
  5066. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5067. // The assumption is that future DOM event attribute names will begin with
  5068. // 'on' and be composed of only English letters.
  5069. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5070. /**
  5071. * @ngdoc method
  5072. * @name $compileProvider#directive
  5073. * @kind function
  5074. *
  5075. * @description
  5076. * Register a new directive with the compiler.
  5077. *
  5078. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5079. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5080. * names and the values are the factories.
  5081. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5082. * {@link guide/directive} for more info.
  5083. * @returns {ng.$compileProvider} Self for chaining.
  5084. */
  5085. this.directive = function registerDirective(name, directiveFactory) {
  5086. assertNotHasOwnProperty(name, 'directive');
  5087. if (isString(name)) {
  5088. assertArg(directiveFactory, 'directiveFactory');
  5089. if (!hasDirectives.hasOwnProperty(name)) {
  5090. hasDirectives[name] = [];
  5091. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5092. function($injector, $exceptionHandler) {
  5093. var directives = [];
  5094. forEach(hasDirectives[name], function(directiveFactory, index) {
  5095. try {
  5096. var directive = $injector.invoke(directiveFactory);
  5097. if (isFunction(directive)) {
  5098. directive = { compile: valueFn(directive) };
  5099. } else if (!directive.compile && directive.link) {
  5100. directive.compile = valueFn(directive.link);
  5101. }
  5102. directive.priority = directive.priority || 0;
  5103. directive.index = index;
  5104. directive.name = directive.name || name;
  5105. directive.require = directive.require || (directive.controller && directive.name);
  5106. directive.restrict = directive.restrict || 'A';
  5107. directives.push(directive);
  5108. } catch (e) {
  5109. $exceptionHandler(e);
  5110. }
  5111. });
  5112. return directives;
  5113. }]);
  5114. }
  5115. hasDirectives[name].push(directiveFactory);
  5116. } else {
  5117. forEach(name, reverseParams(registerDirective));
  5118. }
  5119. return this;
  5120. };
  5121. /**
  5122. * @ngdoc method
  5123. * @name $compileProvider#aHrefSanitizationWhitelist
  5124. * @kind function
  5125. *
  5126. * @description
  5127. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5128. * urls during a[href] sanitization.
  5129. *
  5130. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5131. *
  5132. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5133. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5134. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5135. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5136. *
  5137. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5138. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5139. * chaining otherwise.
  5140. */
  5141. this.aHrefSanitizationWhitelist = function(regexp) {
  5142. if (isDefined(regexp)) {
  5143. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5144. return this;
  5145. } else {
  5146. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5147. }
  5148. };
  5149. /**
  5150. * @ngdoc method
  5151. * @name $compileProvider#imgSrcSanitizationWhitelist
  5152. * @kind function
  5153. *
  5154. * @description
  5155. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5156. * urls during img[src] sanitization.
  5157. *
  5158. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5159. *
  5160. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5161. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5162. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5163. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5164. *
  5165. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5166. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5167. * chaining otherwise.
  5168. */
  5169. this.imgSrcSanitizationWhitelist = function(regexp) {
  5170. if (isDefined(regexp)) {
  5171. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5172. return this;
  5173. } else {
  5174. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5175. }
  5176. };
  5177. this.$get = [
  5178. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  5179. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5180. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  5181. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5182. var Attributes = function(element, attr) {
  5183. this.$$element = element;
  5184. this.$attr = attr || {};
  5185. };
  5186. Attributes.prototype = {
  5187. $normalize: directiveNormalize,
  5188. /**
  5189. * @ngdoc method
  5190. * @name $compile.directive.Attributes#$addClass
  5191. * @kind function
  5192. *
  5193. * @description
  5194. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5195. * are enabled then an animation will be triggered for the class addition.
  5196. *
  5197. * @param {string} classVal The className value that will be added to the element
  5198. */
  5199. $addClass : function(classVal) {
  5200. if(classVal && classVal.length > 0) {
  5201. $animate.addClass(this.$$element, classVal);
  5202. }
  5203. },
  5204. /**
  5205. * @ngdoc method
  5206. * @name $compile.directive.Attributes#$removeClass
  5207. * @kind function
  5208. *
  5209. * @description
  5210. * Removes the CSS class value specified by the classVal parameter from the element. If
  5211. * animations are enabled then an animation will be triggered for the class removal.
  5212. *
  5213. * @param {string} classVal The className value that will be removed from the element
  5214. */
  5215. $removeClass : function(classVal) {
  5216. if(classVal && classVal.length > 0) {
  5217. $animate.removeClass(this.$$element, classVal);
  5218. }
  5219. },
  5220. /**
  5221. * @ngdoc method
  5222. * @name $compile.directive.Attributes#$updateClass
  5223. * @kind function
  5224. *
  5225. * @description
  5226. * Adds and removes the appropriate CSS class values to the element based on the difference
  5227. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5228. *
  5229. * @param {string} newClasses The current CSS className value
  5230. * @param {string} oldClasses The former CSS className value
  5231. */
  5232. $updateClass : function(newClasses, oldClasses) {
  5233. var toAdd = tokenDifference(newClasses, oldClasses);
  5234. var toRemove = tokenDifference(oldClasses, newClasses);
  5235. if(toAdd.length === 0) {
  5236. $animate.removeClass(this.$$element, toRemove);
  5237. } else if(toRemove.length === 0) {
  5238. $animate.addClass(this.$$element, toAdd);
  5239. } else {
  5240. $animate.setClass(this.$$element, toAdd, toRemove);
  5241. }
  5242. },
  5243. /**
  5244. * Set a normalized attribute on the element in a way such that all directives
  5245. * can share the attribute. This function properly handles boolean attributes.
  5246. * @param {string} key Normalized key. (ie ngAttribute)
  5247. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5248. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5249. * Defaults to true.
  5250. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5251. */
  5252. $set: function(key, value, writeAttr, attrName) {
  5253. // TODO: decide whether or not to throw an error if "class"
  5254. //is set through this function since it may cause $updateClass to
  5255. //become unstable.
  5256. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5257. normalizedVal,
  5258. nodeName;
  5259. if (booleanKey) {
  5260. this.$$element.prop(key, value);
  5261. attrName = booleanKey;
  5262. }
  5263. this[key] = value;
  5264. // translate normalized key to actual key
  5265. if (attrName) {
  5266. this.$attr[key] = attrName;
  5267. } else {
  5268. attrName = this.$attr[key];
  5269. if (!attrName) {
  5270. this.$attr[key] = attrName = snake_case(key, '-');
  5271. }
  5272. }
  5273. nodeName = nodeName_(this.$$element);
  5274. // sanitize a[href] and img[src] values
  5275. if ((nodeName === 'A' && key === 'href') ||
  5276. (nodeName === 'IMG' && key === 'src')) {
  5277. this[key] = value = $$sanitizeUri(value, key === 'src');
  5278. }
  5279. if (writeAttr !== false) {
  5280. if (value === null || value === undefined) {
  5281. this.$$element.removeAttr(attrName);
  5282. } else {
  5283. this.$$element.attr(attrName, value);
  5284. }
  5285. }
  5286. // fire observers
  5287. var $$observers = this.$$observers;
  5288. $$observers && forEach($$observers[key], function(fn) {
  5289. try {
  5290. fn(value);
  5291. } catch (e) {
  5292. $exceptionHandler(e);
  5293. }
  5294. });
  5295. },
  5296. /**
  5297. * @ngdoc method
  5298. * @name $compile.directive.Attributes#$observe
  5299. * @kind function
  5300. *
  5301. * @description
  5302. * Observes an interpolated attribute.
  5303. *
  5304. * The observer function will be invoked once during the next `$digest` following
  5305. * compilation. The observer is then invoked whenever the interpolated value
  5306. * changes.
  5307. *
  5308. * @param {string} key Normalized key. (ie ngAttribute) .
  5309. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5310. the interpolated value of the attribute changes.
  5311. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5312. * @returns {function()} the `fn` parameter.
  5313. */
  5314. $observe: function(key, fn) {
  5315. var attrs = this,
  5316. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5317. listeners = ($$observers[key] || ($$observers[key] = []));
  5318. listeners.push(fn);
  5319. $rootScope.$evalAsync(function() {
  5320. if (!listeners.$$inter) {
  5321. // no one registered attribute interpolation function, so lets call it manually
  5322. fn(attrs[key]);
  5323. }
  5324. });
  5325. return fn;
  5326. }
  5327. };
  5328. var startSymbol = $interpolate.startSymbol(),
  5329. endSymbol = $interpolate.endSymbol(),
  5330. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5331. ? identity
  5332. : function denormalizeTemplate(template) {
  5333. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5334. },
  5335. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5336. return compile;
  5337. //================================
  5338. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5339. previousCompileContext) {
  5340. if (!($compileNodes instanceof jqLite)) {
  5341. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5342. // modify it.
  5343. $compileNodes = jqLite($compileNodes);
  5344. }
  5345. // We can not compile top level text elements since text nodes can be merged and we will
  5346. // not be able to attach scope data to them, so we will wrap them in <span>
  5347. forEach($compileNodes, function(node, index){
  5348. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5349. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5350. }
  5351. });
  5352. var compositeLinkFn =
  5353. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5354. maxPriority, ignoreDirective, previousCompileContext);
  5355. safeAddClass($compileNodes, 'ng-scope');
  5356. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  5357. assertArg(scope, 'scope');
  5358. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5359. // and sometimes changes the structure of the DOM.
  5360. var $linkNode = cloneConnectFn
  5361. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5362. : $compileNodes;
  5363. forEach(transcludeControllers, function(instance, name) {
  5364. $linkNode.data('$' + name + 'Controller', instance);
  5365. });
  5366. // Attach scope only to non-text nodes.
  5367. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5368. var node = $linkNode[i],
  5369. nodeType = node.nodeType;
  5370. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5371. $linkNode.eq(i).data('$scope', scope);
  5372. }
  5373. }
  5374. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5375. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  5376. return $linkNode;
  5377. };
  5378. }
  5379. function safeAddClass($element, className) {
  5380. try {
  5381. $element.addClass(className);
  5382. } catch(e) {
  5383. // ignore, since it means that we are trying to set class on
  5384. // SVG element, where class name is read-only.
  5385. }
  5386. }
  5387. /**
  5388. * Compile function matches each node in nodeList against the directives. Once all directives
  5389. * for a particular node are collected their compile functions are executed. The compile
  5390. * functions return values - the linking functions - are combined into a composite linking
  5391. * function, which is the a linking function for the node.
  5392. *
  5393. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5394. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5395. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5396. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5397. * the rootElement must be set the jqLite collection of the compile root. This is
  5398. * needed so that the jqLite collection items can be replaced with widgets.
  5399. * @param {number=} maxPriority Max directive priority.
  5400. * @returns {Function} A composite linking function of all of the matched directives or null.
  5401. */
  5402. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5403. previousCompileContext) {
  5404. var linkFns = [],
  5405. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5406. for (var i = 0; i < nodeList.length; i++) {
  5407. attrs = new Attributes();
  5408. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5409. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5410. ignoreDirective);
  5411. nodeLinkFn = (directives.length)
  5412. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5413. null, [], [], previousCompileContext)
  5414. : null;
  5415. if (nodeLinkFn && nodeLinkFn.scope) {
  5416. safeAddClass(jqLite(nodeList[i]), 'ng-scope');
  5417. }
  5418. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5419. !(childNodes = nodeList[i].childNodes) ||
  5420. !childNodes.length)
  5421. ? null
  5422. : compileNodes(childNodes,
  5423. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  5424. linkFns.push(nodeLinkFn, childLinkFn);
  5425. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5426. //use the previous context only for the first element in the virtual group
  5427. previousCompileContext = null;
  5428. }
  5429. // return a linking function if we have found anything, null otherwise
  5430. return linkFnFound ? compositeLinkFn : null;
  5431. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  5432. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  5433. // copy nodeList so that linking doesn't break due to live list updates.
  5434. var nodeListLength = nodeList.length,
  5435. stableNodeList = new Array(nodeListLength);
  5436. for (i = 0; i < nodeListLength; i++) {
  5437. stableNodeList[i] = nodeList[i];
  5438. }
  5439. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5440. node = stableNodeList[n];
  5441. nodeLinkFn = linkFns[i++];
  5442. childLinkFn = linkFns[i++];
  5443. $node = jqLite(node);
  5444. if (nodeLinkFn) {
  5445. if (nodeLinkFn.scope) {
  5446. childScope = scope.$new();
  5447. $node.data('$scope', childScope);
  5448. } else {
  5449. childScope = scope;
  5450. }
  5451. childTranscludeFn = nodeLinkFn.transclude;
  5452. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  5453. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  5454. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  5455. );
  5456. } else {
  5457. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  5458. }
  5459. } else if (childLinkFn) {
  5460. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  5461. }
  5462. }
  5463. }
  5464. }
  5465. function createBoundTranscludeFn(scope, transcludeFn) {
  5466. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  5467. var scopeCreated = false;
  5468. if (!transcludedScope) {
  5469. transcludedScope = scope.$new();
  5470. transcludedScope.$$transcluded = true;
  5471. scopeCreated = true;
  5472. }
  5473. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  5474. if (scopeCreated) {
  5475. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  5476. }
  5477. return clone;
  5478. };
  5479. }
  5480. /**
  5481. * Looks for directives on the given node and adds them to the directive collection which is
  5482. * sorted.
  5483. *
  5484. * @param node Node to search.
  5485. * @param directives An array to which the directives are added to. This array is sorted before
  5486. * the function returns.
  5487. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5488. * @param {number=} maxPriority Max directive priority.
  5489. */
  5490. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5491. var nodeType = node.nodeType,
  5492. attrsMap = attrs.$attr,
  5493. match,
  5494. className;
  5495. switch(nodeType) {
  5496. case 1: /* Element */
  5497. // use the node name: <directive>
  5498. addDirective(directives,
  5499. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5500. // iterate over the attributes
  5501. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  5502. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5503. var attrStartName = false;
  5504. var attrEndName = false;
  5505. attr = nAttrs[j];
  5506. if (!msie || msie >= 8 || attr.specified) {
  5507. name = attr.name;
  5508. // support ngAttr attribute binding
  5509. ngAttrName = directiveNormalize(name);
  5510. if (NG_ATTR_BINDING.test(ngAttrName)) {
  5511. name = snake_case(ngAttrName.substr(6), '-');
  5512. }
  5513. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5514. if (ngAttrName === directiveNName + 'Start') {
  5515. attrStartName = name;
  5516. attrEndName = name.substr(0, name.length - 5) + 'end';
  5517. name = name.substr(0, name.length - 6);
  5518. }
  5519. nName = directiveNormalize(name.toLowerCase());
  5520. attrsMap[nName] = name;
  5521. attrs[nName] = value = trim(attr.value);
  5522. if (getBooleanAttrName(node, nName)) {
  5523. attrs[nName] = true; // presence means true
  5524. }
  5525. addAttrInterpolateDirective(node, directives, value, nName);
  5526. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5527. attrEndName);
  5528. }
  5529. }
  5530. // use class as directive
  5531. className = node.className;
  5532. if (isString(className) && className !== '') {
  5533. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5534. nName = directiveNormalize(match[2]);
  5535. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5536. attrs[nName] = trim(match[3]);
  5537. }
  5538. className = className.substr(match.index + match[0].length);
  5539. }
  5540. }
  5541. break;
  5542. case 3: /* Text Node */
  5543. addTextInterpolateDirective(directives, node.nodeValue);
  5544. break;
  5545. case 8: /* Comment */
  5546. try {
  5547. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5548. if (match) {
  5549. nName = directiveNormalize(match[1]);
  5550. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5551. attrs[nName] = trim(match[2]);
  5552. }
  5553. }
  5554. } catch (e) {
  5555. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5556. // comment's node value.
  5557. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5558. }
  5559. break;
  5560. }
  5561. directives.sort(byPriority);
  5562. return directives;
  5563. }
  5564. /**
  5565. * Given a node with an directive-start it collects all of the siblings until it finds
  5566. * directive-end.
  5567. * @param node
  5568. * @param attrStart
  5569. * @param attrEnd
  5570. * @returns {*}
  5571. */
  5572. function groupScan(node, attrStart, attrEnd) {
  5573. var nodes = [];
  5574. var depth = 0;
  5575. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5576. var startNode = node;
  5577. do {
  5578. if (!node) {
  5579. throw $compileMinErr('uterdir',
  5580. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5581. attrStart, attrEnd);
  5582. }
  5583. if (node.nodeType == 1 /** Element **/) {
  5584. if (node.hasAttribute(attrStart)) depth++;
  5585. if (node.hasAttribute(attrEnd)) depth--;
  5586. }
  5587. nodes.push(node);
  5588. node = node.nextSibling;
  5589. } while (depth > 0);
  5590. } else {
  5591. nodes.push(node);
  5592. }
  5593. return jqLite(nodes);
  5594. }
  5595. /**
  5596. * Wrapper for linking function which converts normal linking function into a grouped
  5597. * linking function.
  5598. * @param linkFn
  5599. * @param attrStart
  5600. * @param attrEnd
  5601. * @returns {Function}
  5602. */
  5603. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5604. return function(scope, element, attrs, controllers, transcludeFn) {
  5605. element = groupScan(element[0], attrStart, attrEnd);
  5606. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5607. };
  5608. }
  5609. /**
  5610. * Once the directives have been collected, their compile functions are executed. This method
  5611. * is responsible for inlining directive templates as well as terminating the application
  5612. * of the directives if the terminal directive has been reached.
  5613. *
  5614. * @param {Array} directives Array of collected directives to execute their compile function.
  5615. * this needs to be pre-sorted by priority order.
  5616. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5617. * @param {Object} templateAttrs The shared attribute function
  5618. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5619. * scope argument is auto-generated to the new
  5620. * child of the transcluded parent scope.
  5621. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5622. * argument has the root jqLite array so that we can replace nodes
  5623. * on it.
  5624. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5625. * compiling the transclusion.
  5626. * @param {Array.<Function>} preLinkFns
  5627. * @param {Array.<Function>} postLinkFns
  5628. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5629. * node
  5630. * @returns {Function} linkFn
  5631. */
  5632. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5633. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5634. previousCompileContext) {
  5635. previousCompileContext = previousCompileContext || {};
  5636. var terminalPriority = -Number.MAX_VALUE,
  5637. newScopeDirective,
  5638. controllerDirectives = previousCompileContext.controllerDirectives,
  5639. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5640. templateDirective = previousCompileContext.templateDirective,
  5641. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5642. hasTranscludeDirective = false,
  5643. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5644. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5645. directive,
  5646. directiveName,
  5647. $template,
  5648. replaceDirective = originalReplaceDirective,
  5649. childTranscludeFn = transcludeFn,
  5650. linkFn,
  5651. directiveValue;
  5652. // executes all directives on the current element
  5653. for(var i = 0, ii = directives.length; i < ii; i++) {
  5654. directive = directives[i];
  5655. var attrStart = directive.$$start;
  5656. var attrEnd = directive.$$end;
  5657. // collect multiblock sections
  5658. if (attrStart) {
  5659. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5660. }
  5661. $template = undefined;
  5662. if (terminalPriority > directive.priority) {
  5663. break; // prevent further processing of directives
  5664. }
  5665. if (directiveValue = directive.scope) {
  5666. newScopeDirective = newScopeDirective || directive;
  5667. // skip the check for directives with async templates, we'll check the derived sync
  5668. // directive when the template arrives
  5669. if (!directive.templateUrl) {
  5670. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5671. $compileNode);
  5672. if (isObject(directiveValue)) {
  5673. newIsolateScopeDirective = directive;
  5674. }
  5675. }
  5676. }
  5677. directiveName = directive.name;
  5678. if (!directive.templateUrl && directive.controller) {
  5679. directiveValue = directive.controller;
  5680. controllerDirectives = controllerDirectives || {};
  5681. assertNoDuplicate("'" + directiveName + "' controller",
  5682. controllerDirectives[directiveName], directive, $compileNode);
  5683. controllerDirectives[directiveName] = directive;
  5684. }
  5685. if (directiveValue = directive.transclude) {
  5686. hasTranscludeDirective = true;
  5687. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5688. // This option should only be used by directives that know how to safely handle element transclusion,
  5689. // where the transcluded nodes are added or replaced after linking.
  5690. if (!directive.$$tlb) {
  5691. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5692. nonTlbTranscludeDirective = directive;
  5693. }
  5694. if (directiveValue == 'element') {
  5695. hasElementTranscludeDirective = true;
  5696. terminalPriority = directive.priority;
  5697. $template = groupScan(compileNode, attrStart, attrEnd);
  5698. $compileNode = templateAttrs.$$element =
  5699. jqLite(document.createComment(' ' + directiveName + ': ' +
  5700. templateAttrs[directiveName] + ' '));
  5701. compileNode = $compileNode[0];
  5702. replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
  5703. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5704. replaceDirective && replaceDirective.name, {
  5705. // Don't pass in:
  5706. // - controllerDirectives - otherwise we'll create duplicates controllers
  5707. // - newIsolateScopeDirective or templateDirective - combining templates with
  5708. // element transclusion doesn't make sense.
  5709. //
  5710. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5711. // on the same element more than once.
  5712. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5713. });
  5714. } else {
  5715. $template = jqLite(jqLiteClone(compileNode)).contents();
  5716. $compileNode.empty(); // clear contents
  5717. childTranscludeFn = compile($template, transcludeFn);
  5718. }
  5719. }
  5720. if (directive.template) {
  5721. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5722. templateDirective = directive;
  5723. directiveValue = (isFunction(directive.template))
  5724. ? directive.template($compileNode, templateAttrs)
  5725. : directive.template;
  5726. directiveValue = denormalizeTemplate(directiveValue);
  5727. if (directive.replace) {
  5728. replaceDirective = directive;
  5729. if (jqLiteIsTextNode(directiveValue)) {
  5730. $template = [];
  5731. } else {
  5732. $template = jqLite(trim(directiveValue));
  5733. }
  5734. compileNode = $template[0];
  5735. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5736. throw $compileMinErr('tplrt',
  5737. "Template for directive '{0}' must have exactly one root element. {1}",
  5738. directiveName, '');
  5739. }
  5740. replaceWith(jqCollection, $compileNode, compileNode);
  5741. var newTemplateAttrs = {$attr: {}};
  5742. // combine directives from the original node and from the template:
  5743. // - take the array of directives for this element
  5744. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5745. // - collect directives from the template and sort them by priority
  5746. // - combine directives as: processed + template + unprocessed
  5747. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5748. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5749. if (newIsolateScopeDirective) {
  5750. markDirectivesAsIsolate(templateDirectives);
  5751. }
  5752. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5753. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5754. ii = directives.length;
  5755. } else {
  5756. $compileNode.html(directiveValue);
  5757. }
  5758. }
  5759. if (directive.templateUrl) {
  5760. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5761. templateDirective = directive;
  5762. if (directive.replace) {
  5763. replaceDirective = directive;
  5764. }
  5765. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5766. templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
  5767. controllerDirectives: controllerDirectives,
  5768. newIsolateScopeDirective: newIsolateScopeDirective,
  5769. templateDirective: templateDirective,
  5770. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5771. });
  5772. ii = directives.length;
  5773. } else if (directive.compile) {
  5774. try {
  5775. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5776. if (isFunction(linkFn)) {
  5777. addLinkFns(null, linkFn, attrStart, attrEnd);
  5778. } else if (linkFn) {
  5779. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5780. }
  5781. } catch (e) {
  5782. $exceptionHandler(e, startingTag($compileNode));
  5783. }
  5784. }
  5785. if (directive.terminal) {
  5786. nodeLinkFn.terminal = true;
  5787. terminalPriority = Math.max(terminalPriority, directive.priority);
  5788. }
  5789. }
  5790. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5791. nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
  5792. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5793. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5794. return nodeLinkFn;
  5795. ////////////////////
  5796. function addLinkFns(pre, post, attrStart, attrEnd) {
  5797. if (pre) {
  5798. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5799. pre.require = directive.require;
  5800. pre.directiveName = directiveName;
  5801. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5802. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5803. }
  5804. preLinkFns.push(pre);
  5805. }
  5806. if (post) {
  5807. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5808. post.require = directive.require;
  5809. post.directiveName = directiveName;
  5810. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5811. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5812. }
  5813. postLinkFns.push(post);
  5814. }
  5815. }
  5816. function getControllers(directiveName, require, $element, elementControllers) {
  5817. var value, retrievalMethod = 'data', optional = false;
  5818. if (isString(require)) {
  5819. while((value = require.charAt(0)) == '^' || value == '?') {
  5820. require = require.substr(1);
  5821. if (value == '^') {
  5822. retrievalMethod = 'inheritedData';
  5823. }
  5824. optional = optional || value == '?';
  5825. }
  5826. value = null;
  5827. if (elementControllers && retrievalMethod === 'data') {
  5828. value = elementControllers[require];
  5829. }
  5830. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5831. if (!value && !optional) {
  5832. throw $compileMinErr('ctreq',
  5833. "Controller '{0}', required by directive '{1}', can't be found!",
  5834. require, directiveName);
  5835. }
  5836. return value;
  5837. } else if (isArray(require)) {
  5838. value = [];
  5839. forEach(require, function(require) {
  5840. value.push(getControllers(directiveName, require, $element, elementControllers));
  5841. });
  5842. }
  5843. return value;
  5844. }
  5845. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5846. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5847. if (compileNode === linkNode) {
  5848. attrs = templateAttrs;
  5849. } else {
  5850. attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5851. }
  5852. $element = attrs.$$element;
  5853. if (newIsolateScopeDirective) {
  5854. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5855. var $linkNode = jqLite(linkNode);
  5856. isolateScope = scope.$new(true);
  5857. if (templateDirective && (templateDirective === newIsolateScopeDirective ||
  5858. templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5859. $linkNode.data('$isolateScope', isolateScope) ;
  5860. } else {
  5861. $linkNode.data('$isolateScopeNoTemplate', isolateScope);
  5862. }
  5863. safeAddClass($linkNode, 'ng-isolate-scope');
  5864. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5865. var match = definition.match(LOCAL_REGEXP) || [],
  5866. attrName = match[3] || scopeName,
  5867. optional = (match[2] == '?'),
  5868. mode = match[1], // @, =, or &
  5869. lastValue,
  5870. parentGet, parentSet, compare;
  5871. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5872. switch (mode) {
  5873. case '@':
  5874. attrs.$observe(attrName, function(value) {
  5875. isolateScope[scopeName] = value;
  5876. });
  5877. attrs.$$observers[attrName].$$scope = scope;
  5878. if( attrs[attrName] ) {
  5879. // If the attribute has been provided then we trigger an interpolation to ensure
  5880. // the value is there for use in the link fn
  5881. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5882. }
  5883. break;
  5884. case '=':
  5885. if (optional && !attrs[attrName]) {
  5886. return;
  5887. }
  5888. parentGet = $parse(attrs[attrName]);
  5889. if (parentGet.literal) {
  5890. compare = equals;
  5891. } else {
  5892. compare = function(a,b) { return a === b; };
  5893. }
  5894. parentSet = parentGet.assign || function() {
  5895. // reset the change, or we will throw this exception on every $digest
  5896. lastValue = isolateScope[scopeName] = parentGet(scope);
  5897. throw $compileMinErr('nonassign',
  5898. "Expression '{0}' used with directive '{1}' is non-assignable!",
  5899. attrs[attrName], newIsolateScopeDirective.name);
  5900. };
  5901. lastValue = isolateScope[scopeName] = parentGet(scope);
  5902. isolateScope.$watch(function parentValueWatch() {
  5903. var parentValue = parentGet(scope);
  5904. if (!compare(parentValue, isolateScope[scopeName])) {
  5905. // we are out of sync and need to copy
  5906. if (!compare(parentValue, lastValue)) {
  5907. // parent changed and it has precedence
  5908. isolateScope[scopeName] = parentValue;
  5909. } else {
  5910. // if the parent can be assigned then do so
  5911. parentSet(scope, parentValue = isolateScope[scopeName]);
  5912. }
  5913. }
  5914. return lastValue = parentValue;
  5915. }, null, parentGet.literal);
  5916. break;
  5917. case '&':
  5918. parentGet = $parse(attrs[attrName]);
  5919. isolateScope[scopeName] = function(locals) {
  5920. return parentGet(scope, locals);
  5921. };
  5922. break;
  5923. default:
  5924. throw $compileMinErr('iscp',
  5925. "Invalid isolate scope definition for directive '{0}'." +
  5926. " Definition: {... {1}: '{2}' ...}",
  5927. newIsolateScopeDirective.name, scopeName, definition);
  5928. }
  5929. });
  5930. }
  5931. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  5932. if (controllerDirectives) {
  5933. forEach(controllerDirectives, function(directive) {
  5934. var locals = {
  5935. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  5936. $element: $element,
  5937. $attrs: attrs,
  5938. $transclude: transcludeFn
  5939. }, controllerInstance;
  5940. controller = directive.controller;
  5941. if (controller == '@') {
  5942. controller = attrs[directive.name];
  5943. }
  5944. controllerInstance = $controller(controller, locals);
  5945. // For directives with element transclusion the element is a comment,
  5946. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  5947. // clean up (http://bugs.jquery.com/ticket/8335).
  5948. // Instead, we save the controllers for the element in a local hash and attach to .data
  5949. // later, once we have the actual element.
  5950. elementControllers[directive.name] = controllerInstance;
  5951. if (!hasElementTranscludeDirective) {
  5952. $element.data('$' + directive.name + 'Controller', controllerInstance);
  5953. }
  5954. if (directive.controllerAs) {
  5955. locals.$scope[directive.controllerAs] = controllerInstance;
  5956. }
  5957. });
  5958. }
  5959. // PRELINKING
  5960. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  5961. try {
  5962. linkFn = preLinkFns[i];
  5963. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5964. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  5965. } catch (e) {
  5966. $exceptionHandler(e, startingTag($element));
  5967. }
  5968. }
  5969. // RECURSION
  5970. // We only pass the isolate scope, if the isolate directive has a template,
  5971. // otherwise the child elements do not belong to the isolate directive.
  5972. var scopeToChild = scope;
  5973. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  5974. scopeToChild = isolateScope;
  5975. }
  5976. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  5977. // POSTLINKING
  5978. for(i = postLinkFns.length - 1; i >= 0; i--) {
  5979. try {
  5980. linkFn = postLinkFns[i];
  5981. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5982. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  5983. } catch (e) {
  5984. $exceptionHandler(e, startingTag($element));
  5985. }
  5986. }
  5987. // This is the function that is injected as `$transclude`.
  5988. function controllersBoundTransclude(scope, cloneAttachFn) {
  5989. var transcludeControllers;
  5990. // no scope passed
  5991. if (arguments.length < 2) {
  5992. cloneAttachFn = scope;
  5993. scope = undefined;
  5994. }
  5995. if (hasElementTranscludeDirective) {
  5996. transcludeControllers = elementControllers;
  5997. }
  5998. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  5999. }
  6000. }
  6001. }
  6002. function markDirectivesAsIsolate(directives) {
  6003. // mark all directives as needing isolate scope.
  6004. for (var j = 0, jj = directives.length; j < jj; j++) {
  6005. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6006. }
  6007. }
  6008. /**
  6009. * looks up the directive and decorates it with exception handling and proper parameters. We
  6010. * call this the boundDirective.
  6011. *
  6012. * @param {string} name name of the directive to look up.
  6013. * @param {string} location The directive must be found in specific format.
  6014. * String containing any of theses characters:
  6015. *
  6016. * * `E`: element name
  6017. * * `A': attribute
  6018. * * `C`: class
  6019. * * `M`: comment
  6020. * @returns {boolean} true if directive was added.
  6021. */
  6022. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6023. endAttrName) {
  6024. if (name === ignoreDirective) return null;
  6025. var match = null;
  6026. if (hasDirectives.hasOwnProperty(name)) {
  6027. for(var directive, directives = $injector.get(name + Suffix),
  6028. i = 0, ii = directives.length; i<ii; i++) {
  6029. try {
  6030. directive = directives[i];
  6031. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6032. directive.restrict.indexOf(location) != -1) {
  6033. if (startAttrName) {
  6034. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6035. }
  6036. tDirectives.push(directive);
  6037. match = directive;
  6038. }
  6039. } catch(e) { $exceptionHandler(e); }
  6040. }
  6041. }
  6042. return match;
  6043. }
  6044. /**
  6045. * When the element is replaced with HTML template then the new attributes
  6046. * on the template need to be merged with the existing attributes in the DOM.
  6047. * The desired effect is to have both of the attributes present.
  6048. *
  6049. * @param {object} dst destination attributes (original DOM)
  6050. * @param {object} src source attributes (from the directive template)
  6051. */
  6052. function mergeTemplateAttributes(dst, src) {
  6053. var srcAttr = src.$attr,
  6054. dstAttr = dst.$attr,
  6055. $element = dst.$$element;
  6056. // reapply the old attributes to the new element
  6057. forEach(dst, function(value, key) {
  6058. if (key.charAt(0) != '$') {
  6059. if (src[key] && src[key] !== value) {
  6060. value += (key === 'style' ? ';' : ' ') + src[key];
  6061. }
  6062. dst.$set(key, value, true, srcAttr[key]);
  6063. }
  6064. });
  6065. // copy the new attributes on the old attrs object
  6066. forEach(src, function(value, key) {
  6067. if (key == 'class') {
  6068. safeAddClass($element, value);
  6069. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6070. } else if (key == 'style') {
  6071. $element.attr('style', $element.attr('style') + ';' + value);
  6072. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6073. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6074. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6075. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6076. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6077. dst[key] = value;
  6078. dstAttr[key] = srcAttr[key];
  6079. }
  6080. });
  6081. }
  6082. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6083. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6084. var linkQueue = [],
  6085. afterTemplateNodeLinkFn,
  6086. afterTemplateChildLinkFn,
  6087. beforeTemplateCompileNode = $compileNode[0],
  6088. origAsyncDirective = directives.shift(),
  6089. // The fact that we have to copy and patch the directive seems wrong!
  6090. derivedSyncDirective = extend({}, origAsyncDirective, {
  6091. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6092. }),
  6093. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6094. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6095. : origAsyncDirective.templateUrl;
  6096. $compileNode.empty();
  6097. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6098. success(function(content) {
  6099. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6100. content = denormalizeTemplate(content);
  6101. if (origAsyncDirective.replace) {
  6102. if (jqLiteIsTextNode(content)) {
  6103. $template = [];
  6104. } else {
  6105. $template = jqLite(trim(content));
  6106. }
  6107. compileNode = $template[0];
  6108. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6109. throw $compileMinErr('tplrt',
  6110. "Template for directive '{0}' must have exactly one root element. {1}",
  6111. origAsyncDirective.name, templateUrl);
  6112. }
  6113. tempTemplateAttrs = {$attr: {}};
  6114. replaceWith($rootElement, $compileNode, compileNode);
  6115. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6116. if (isObject(origAsyncDirective.scope)) {
  6117. markDirectivesAsIsolate(templateDirectives);
  6118. }
  6119. directives = templateDirectives.concat(directives);
  6120. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6121. } else {
  6122. compileNode = beforeTemplateCompileNode;
  6123. $compileNode.html(content);
  6124. }
  6125. directives.unshift(derivedSyncDirective);
  6126. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6127. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6128. previousCompileContext);
  6129. forEach($rootElement, function(node, i) {
  6130. if (node == compileNode) {
  6131. $rootElement[i] = $compileNode[0];
  6132. }
  6133. });
  6134. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6135. while(linkQueue.length) {
  6136. var scope = linkQueue.shift(),
  6137. beforeTemplateLinkNode = linkQueue.shift(),
  6138. linkRootElement = linkQueue.shift(),
  6139. boundTranscludeFn = linkQueue.shift(),
  6140. linkNode = $compileNode[0];
  6141. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6142. var oldClasses = beforeTemplateLinkNode.className;
  6143. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6144. origAsyncDirective.replace)) {
  6145. // it was cloned therefore we have to clone as well.
  6146. linkNode = jqLiteClone(compileNode);
  6147. }
  6148. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6149. // Copy in CSS classes from original node
  6150. safeAddClass(jqLite(linkNode), oldClasses);
  6151. }
  6152. if (afterTemplateNodeLinkFn.transclude) {
  6153. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
  6154. } else {
  6155. childBoundTranscludeFn = boundTranscludeFn;
  6156. }
  6157. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6158. childBoundTranscludeFn);
  6159. }
  6160. linkQueue = null;
  6161. }).
  6162. error(function(response, code, headers, config) {
  6163. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6164. });
  6165. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6166. if (linkQueue) {
  6167. linkQueue.push(scope);
  6168. linkQueue.push(node);
  6169. linkQueue.push(rootElement);
  6170. linkQueue.push(boundTranscludeFn);
  6171. } else {
  6172. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
  6173. }
  6174. };
  6175. }
  6176. /**
  6177. * Sorting function for bound directives.
  6178. */
  6179. function byPriority(a, b) {
  6180. var diff = b.priority - a.priority;
  6181. if (diff !== 0) return diff;
  6182. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6183. return a.index - b.index;
  6184. }
  6185. function assertNoDuplicate(what, previousDirective, directive, element) {
  6186. if (previousDirective) {
  6187. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6188. previousDirective.name, directive.name, what, startingTag(element));
  6189. }
  6190. }
  6191. function addTextInterpolateDirective(directives, text) {
  6192. var interpolateFn = $interpolate(text, true);
  6193. if (interpolateFn) {
  6194. directives.push({
  6195. priority: 0,
  6196. compile: valueFn(function textInterpolateLinkFn(scope, node) {
  6197. var parent = node.parent(),
  6198. bindings = parent.data('$binding') || [];
  6199. bindings.push(interpolateFn);
  6200. safeAddClass(parent.data('$binding', bindings), 'ng-binding');
  6201. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6202. node[0].nodeValue = value;
  6203. });
  6204. })
  6205. });
  6206. }
  6207. }
  6208. function getTrustedContext(node, attrNormalizedName) {
  6209. if (attrNormalizedName == "srcdoc") {
  6210. return $sce.HTML;
  6211. }
  6212. var tag = nodeName_(node);
  6213. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6214. if (attrNormalizedName == "xlinkHref" ||
  6215. (tag == "FORM" && attrNormalizedName == "action") ||
  6216. (tag != "IMG" && (attrNormalizedName == "src" ||
  6217. attrNormalizedName == "ngSrc"))) {
  6218. return $sce.RESOURCE_URL;
  6219. }
  6220. }
  6221. function addAttrInterpolateDirective(node, directives, value, name) {
  6222. var interpolateFn = $interpolate(value, true);
  6223. // no interpolation found -> ignore
  6224. if (!interpolateFn) return;
  6225. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6226. throw $compileMinErr("selmulti",
  6227. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6228. startingTag(node));
  6229. }
  6230. directives.push({
  6231. priority: 100,
  6232. compile: function() {
  6233. return {
  6234. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6235. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6236. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6237. throw $compileMinErr('nodomevents',
  6238. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6239. "ng- versions (such as ng-click instead of onclick) instead.");
  6240. }
  6241. // we need to interpolate again, in case the attribute value has been updated
  6242. // (e.g. by another directive's compile function)
  6243. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6244. // if attribute was updated so that there is no interpolation going on we don't want to
  6245. // register any observers
  6246. if (!interpolateFn) return;
  6247. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6248. // actual attr value
  6249. attr[name] = interpolateFn(scope);
  6250. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6251. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6252. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6253. //special case for class attribute addition + removal
  6254. //so that class changes can tap into the animation
  6255. //hooks provided by the $animate service. Be sure to
  6256. //skip animations when the first digest occurs (when
  6257. //both the new and the old values are the same) since
  6258. //the CSS classes are the non-interpolated values
  6259. if(name === 'class' && newValue != oldValue) {
  6260. attr.$updateClass(newValue, oldValue);
  6261. } else {
  6262. attr.$set(name, newValue);
  6263. }
  6264. });
  6265. }
  6266. };
  6267. }
  6268. });
  6269. }
  6270. /**
  6271. * This is a special jqLite.replaceWith, which can replace items which
  6272. * have no parents, provided that the containing jqLite collection is provided.
  6273. *
  6274. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6275. * in the root of the tree.
  6276. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6277. * the shell, but replace its DOM node reference.
  6278. * @param {Node} newNode The new DOM node.
  6279. */
  6280. function replaceWith($rootElement, elementsToRemove, newNode) {
  6281. var firstElementToRemove = elementsToRemove[0],
  6282. removeCount = elementsToRemove.length,
  6283. parent = firstElementToRemove.parentNode,
  6284. i, ii;
  6285. if ($rootElement) {
  6286. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6287. if ($rootElement[i] == firstElementToRemove) {
  6288. $rootElement[i++] = newNode;
  6289. for (var j = i, j2 = j + removeCount - 1,
  6290. jj = $rootElement.length;
  6291. j < jj; j++, j2++) {
  6292. if (j2 < jj) {
  6293. $rootElement[j] = $rootElement[j2];
  6294. } else {
  6295. delete $rootElement[j];
  6296. }
  6297. }
  6298. $rootElement.length -= removeCount - 1;
  6299. break;
  6300. }
  6301. }
  6302. }
  6303. if (parent) {
  6304. parent.replaceChild(newNode, firstElementToRemove);
  6305. }
  6306. var fragment = document.createDocumentFragment();
  6307. fragment.appendChild(firstElementToRemove);
  6308. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6309. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6310. var element = elementsToRemove[k];
  6311. jqLite(element).remove(); // must do this way to clean up expando
  6312. fragment.appendChild(element);
  6313. delete elementsToRemove[k];
  6314. }
  6315. elementsToRemove[0] = newNode;
  6316. elementsToRemove.length = 1;
  6317. }
  6318. function cloneAndAnnotateFn(fn, annotation) {
  6319. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6320. }
  6321. }];
  6322. }
  6323. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6324. /**
  6325. * Converts all accepted directives format into proper directive name.
  6326. * All of these will become 'myDirective':
  6327. * my:Directive
  6328. * my-directive
  6329. * x-my-directive
  6330. * data-my:directive
  6331. *
  6332. * Also there is special case for Moz prefix starting with upper case letter.
  6333. * @param name Name to normalize
  6334. */
  6335. function directiveNormalize(name) {
  6336. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6337. }
  6338. /**
  6339. * @ngdoc type
  6340. * @name $compile.directive.Attributes
  6341. *
  6342. * @description
  6343. * A shared object between directive compile / linking functions which contains normalized DOM
  6344. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6345. * needed since all of these are treated as equivalent in Angular:
  6346. *
  6347. * ```
  6348. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6349. * ```
  6350. */
  6351. /**
  6352. * @ngdoc property
  6353. * @name $compile.directive.Attributes#$attr
  6354. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  6355. * needed to do reverse lookup from normalized name back to actual name.
  6356. */
  6357. /**
  6358. * @ngdoc method
  6359. * @name $compile.directive.Attributes#$set
  6360. * @kind function
  6361. *
  6362. * @description
  6363. * Set DOM element attribute value.
  6364. *
  6365. *
  6366. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6367. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6368. * property to the original name.
  6369. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6370. */
  6371. /**
  6372. * Closure compiler type information
  6373. */
  6374. function nodesetLinkingFn(
  6375. /* angular.Scope */ scope,
  6376. /* NodeList */ nodeList,
  6377. /* Element */ rootElement,
  6378. /* function(Function) */ boundTranscludeFn
  6379. ){}
  6380. function directiveLinkingFn(
  6381. /* nodesetLinkingFn */ nodesetLinkingFn,
  6382. /* angular.Scope */ scope,
  6383. /* Node */ node,
  6384. /* Element */ rootElement,
  6385. /* function(Function) */ boundTranscludeFn
  6386. ){}
  6387. function tokenDifference(str1, str2) {
  6388. var values = '',
  6389. tokens1 = str1.split(/\s+/),
  6390. tokens2 = str2.split(/\s+/);
  6391. outer:
  6392. for(var i = 0; i < tokens1.length; i++) {
  6393. var token = tokens1[i];
  6394. for(var j = 0; j < tokens2.length; j++) {
  6395. if(token == tokens2[j]) continue outer;
  6396. }
  6397. values += (values.length > 0 ? ' ' : '') + token;
  6398. }
  6399. return values;
  6400. }
  6401. /**
  6402. * @ngdoc provider
  6403. * @name $controllerProvider
  6404. * @description
  6405. * The {@link ng.$controller $controller service} is used by Angular to create new
  6406. * controllers.
  6407. *
  6408. * This provider allows controller registration via the
  6409. * {@link ng.$controllerProvider#register register} method.
  6410. */
  6411. function $ControllerProvider() {
  6412. var controllers = {},
  6413. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6414. /**
  6415. * @ngdoc method
  6416. * @name $controllerProvider#register
  6417. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6418. * the names and the values are the constructors.
  6419. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6420. * annotations in the array notation).
  6421. */
  6422. this.register = function(name, constructor) {
  6423. assertNotHasOwnProperty(name, 'controller');
  6424. if (isObject(name)) {
  6425. extend(controllers, name);
  6426. } else {
  6427. controllers[name] = constructor;
  6428. }
  6429. };
  6430. this.$get = ['$injector', '$window', function($injector, $window) {
  6431. /**
  6432. * @ngdoc service
  6433. * @name $controller
  6434. * @requires $injector
  6435. *
  6436. * @param {Function|string} constructor If called with a function then it's considered to be the
  6437. * controller constructor function. Otherwise it's considered to be a string which is used
  6438. * to retrieve the controller constructor using the following steps:
  6439. *
  6440. * * check if a controller with given name is registered via `$controllerProvider`
  6441. * * check if evaluating the string on the current scope returns a constructor
  6442. * * check `window[constructor]` on the global `window` object
  6443. *
  6444. * @param {Object} locals Injection locals for Controller.
  6445. * @return {Object} Instance of given controller.
  6446. *
  6447. * @description
  6448. * `$controller` service is responsible for instantiating controllers.
  6449. *
  6450. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6451. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6452. */
  6453. return function(expression, locals) {
  6454. var instance, match, constructor, identifier;
  6455. if(isString(expression)) {
  6456. match = expression.match(CNTRL_REG),
  6457. constructor = match[1],
  6458. identifier = match[3];
  6459. expression = controllers.hasOwnProperty(constructor)
  6460. ? controllers[constructor]
  6461. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6462. assertArgFn(expression, constructor, true);
  6463. }
  6464. instance = $injector.instantiate(expression, locals);
  6465. if (identifier) {
  6466. if (!(locals && typeof locals.$scope == 'object')) {
  6467. throw minErr('$controller')('noscp',
  6468. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6469. constructor || expression.name, identifier);
  6470. }
  6471. locals.$scope[identifier] = instance;
  6472. }
  6473. return instance;
  6474. };
  6475. }];
  6476. }
  6477. /**
  6478. * @ngdoc service
  6479. * @name $document
  6480. * @requires $window
  6481. *
  6482. * @description
  6483. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6484. *
  6485. * @example
  6486. <example>
  6487. <file name="index.html">
  6488. <div ng-controller="MainCtrl">
  6489. <p>$document title: <b ng-bind="title"></b></p>
  6490. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6491. </div>
  6492. </file>
  6493. <file name="script.js">
  6494. function MainCtrl($scope, $document) {
  6495. $scope.title = $document[0].title;
  6496. $scope.windowTitle = angular.element(window.document)[0].title;
  6497. }
  6498. </file>
  6499. </example>
  6500. */
  6501. function $DocumentProvider(){
  6502. this.$get = ['$window', function(window){
  6503. return jqLite(window.document);
  6504. }];
  6505. }
  6506. /**
  6507. * @ngdoc service
  6508. * @name $exceptionHandler
  6509. * @requires ng.$log
  6510. *
  6511. * @description
  6512. * Any uncaught exception in angular expressions is delegated to this service.
  6513. * The default implementation simply delegates to `$log.error` which logs it into
  6514. * the browser console.
  6515. *
  6516. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6517. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6518. *
  6519. * ## Example:
  6520. *
  6521. * ```js
  6522. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6523. * return function (exception, cause) {
  6524. * exception.message += ' (caused by "' + cause + '")';
  6525. * throw exception;
  6526. * };
  6527. * });
  6528. * ```
  6529. *
  6530. * This example will override the normal action of `$exceptionHandler`, to make angular
  6531. * exceptions fail hard when they happen, instead of just logging to the console.
  6532. *
  6533. * @param {Error} exception Exception associated with the error.
  6534. * @param {string=} cause optional information about the context in which
  6535. * the error was thrown.
  6536. *
  6537. */
  6538. function $ExceptionHandlerProvider() {
  6539. this.$get = ['$log', function($log) {
  6540. return function(exception, cause) {
  6541. $log.error.apply($log, arguments);
  6542. };
  6543. }];
  6544. }
  6545. /**
  6546. * Parse headers into key value object
  6547. *
  6548. * @param {string} headers Raw headers as a string
  6549. * @returns {Object} Parsed headers as key value object
  6550. */
  6551. function parseHeaders(headers) {
  6552. var parsed = {}, key, val, i;
  6553. if (!headers) return parsed;
  6554. forEach(headers.split('\n'), function(line) {
  6555. i = line.indexOf(':');
  6556. key = lowercase(trim(line.substr(0, i)));
  6557. val = trim(line.substr(i + 1));
  6558. if (key) {
  6559. if (parsed[key]) {
  6560. parsed[key] += ', ' + val;
  6561. } else {
  6562. parsed[key] = val;
  6563. }
  6564. }
  6565. });
  6566. return parsed;
  6567. }
  6568. /**
  6569. * Returns a function that provides access to parsed headers.
  6570. *
  6571. * Headers are lazy parsed when first requested.
  6572. * @see parseHeaders
  6573. *
  6574. * @param {(string|Object)} headers Headers to provide access to.
  6575. * @returns {function(string=)} Returns a getter function which if called with:
  6576. *
  6577. * - if called with single an argument returns a single header value or null
  6578. * - if called with no arguments returns an object containing all headers.
  6579. */
  6580. function headersGetter(headers) {
  6581. var headersObj = isObject(headers) ? headers : undefined;
  6582. return function(name) {
  6583. if (!headersObj) headersObj = parseHeaders(headers);
  6584. if (name) {
  6585. return headersObj[lowercase(name)] || null;
  6586. }
  6587. return headersObj;
  6588. };
  6589. }
  6590. /**
  6591. * Chain all given functions
  6592. *
  6593. * This function is used for both request and response transforming
  6594. *
  6595. * @param {*} data Data to transform.
  6596. * @param {function(string=)} headers Http headers getter fn.
  6597. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6598. * @returns {*} Transformed data.
  6599. */
  6600. function transformData(data, headers, fns) {
  6601. if (isFunction(fns))
  6602. return fns(data, headers);
  6603. forEach(fns, function(fn) {
  6604. data = fn(data, headers);
  6605. });
  6606. return data;
  6607. }
  6608. function isSuccess(status) {
  6609. return 200 <= status && status < 300;
  6610. }
  6611. function $HttpProvider() {
  6612. var JSON_START = /^\s*(\[|\{[^\{])/,
  6613. JSON_END = /[\}\]]\s*$/,
  6614. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6615. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6616. var defaults = this.defaults = {
  6617. // transform incoming response data
  6618. transformResponse: [function(data) {
  6619. if (isString(data)) {
  6620. // strip json vulnerability protection prefix
  6621. data = data.replace(PROTECTION_PREFIX, '');
  6622. if (JSON_START.test(data) && JSON_END.test(data))
  6623. data = fromJson(data);
  6624. }
  6625. return data;
  6626. }],
  6627. // transform outgoing request data
  6628. transformRequest: [function(d) {
  6629. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6630. }],
  6631. // default headers
  6632. headers: {
  6633. common: {
  6634. 'Accept': 'application/json, text/plain, */*'
  6635. },
  6636. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6637. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6638. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  6639. },
  6640. xsrfCookieName: 'XSRF-TOKEN',
  6641. xsrfHeaderName: 'X-XSRF-TOKEN'
  6642. };
  6643. /**
  6644. * Are ordered by request, i.e. they are applied in the same order as the
  6645. * array, on request, but reverse order, on response.
  6646. */
  6647. var interceptorFactories = this.interceptors = [];
  6648. /**
  6649. * For historical reasons, response interceptors are ordered by the order in which
  6650. * they are applied to the response. (This is the opposite of interceptorFactories)
  6651. */
  6652. var responseInterceptorFactories = this.responseInterceptors = [];
  6653. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6654. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6655. var defaultCache = $cacheFactory('$http');
  6656. /**
  6657. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6658. * The reversal is needed so that we can build up the interception chain around the
  6659. * server request.
  6660. */
  6661. var reversedInterceptors = [];
  6662. forEach(interceptorFactories, function(interceptorFactory) {
  6663. reversedInterceptors.unshift(isString(interceptorFactory)
  6664. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6665. });
  6666. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6667. var responseFn = isString(interceptorFactory)
  6668. ? $injector.get(interceptorFactory)
  6669. : $injector.invoke(interceptorFactory);
  6670. /**
  6671. * Response interceptors go before "around" interceptors (no real reason, just
  6672. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6673. * the splice.
  6674. */
  6675. reversedInterceptors.splice(index, 0, {
  6676. response: function(response) {
  6677. return responseFn($q.when(response));
  6678. },
  6679. responseError: function(response) {
  6680. return responseFn($q.reject(response));
  6681. }
  6682. });
  6683. });
  6684. /**
  6685. * @ngdoc service
  6686. * @kind function
  6687. * @name $http
  6688. * @requires ng.$httpBackend
  6689. * @requires $cacheFactory
  6690. * @requires $rootScope
  6691. * @requires $q
  6692. * @requires $injector
  6693. *
  6694. * @description
  6695. * The `$http` service is a core Angular service that facilitates communication with the remote
  6696. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6697. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6698. *
  6699. * For unit testing applications that use `$http` service, see
  6700. * {@link ngMock.$httpBackend $httpBackend mock}.
  6701. *
  6702. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6703. * $resource} service.
  6704. *
  6705. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6706. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6707. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6708. *
  6709. *
  6710. * # General usage
  6711. * The `$http` service is a function which takes a single argument — a configuration object —
  6712. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6713. * with two $http specific methods: `success` and `error`.
  6714. *
  6715. * ```js
  6716. * $http({method: 'GET', url: '/someUrl'}).
  6717. * success(function(data, status, headers, config) {
  6718. * // this callback will be called asynchronously
  6719. * // when the response is available
  6720. * }).
  6721. * error(function(data, status, headers, config) {
  6722. * // called asynchronously if an error occurs
  6723. * // or server returns response with an error status.
  6724. * });
  6725. * ```
  6726. *
  6727. * Since the returned value of calling the $http function is a `promise`, you can also use
  6728. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6729. * an object representing the response. See the API signature and type info below for more
  6730. * details.
  6731. *
  6732. * A response status code between 200 and 299 is considered a success status and
  6733. * will result in the success callback being called. Note that if the response is a redirect,
  6734. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6735. * called for such responses.
  6736. *
  6737. * # Writing Unit Tests that use $http
  6738. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6739. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6740. * request using trained responses.
  6741. *
  6742. * ```
  6743. * $httpBackend.expectGET(...);
  6744. * $http.get(...);
  6745. * $httpBackend.flush();
  6746. * ```
  6747. *
  6748. * # Shortcut methods
  6749. *
  6750. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6751. * request data must be passed in for POST/PUT requests.
  6752. *
  6753. * ```js
  6754. * $http.get('/someUrl').success(successCallback);
  6755. * $http.post('/someUrl', data).success(successCallback);
  6756. * ```
  6757. *
  6758. * Complete list of shortcut methods:
  6759. *
  6760. * - {@link ng.$http#get $http.get}
  6761. * - {@link ng.$http#head $http.head}
  6762. * - {@link ng.$http#post $http.post}
  6763. * - {@link ng.$http#put $http.put}
  6764. * - {@link ng.$http#delete $http.delete}
  6765. * - {@link ng.$http#jsonp $http.jsonp}
  6766. *
  6767. *
  6768. * # Setting HTTP Headers
  6769. *
  6770. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6771. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6772. * object, which currently contains this default configuration:
  6773. *
  6774. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6775. * - `Accept: application/json, text/plain, * / *`
  6776. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6777. * - `Content-Type: application/json`
  6778. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6779. * - `Content-Type: application/json`
  6780. *
  6781. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6782. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6783. * with the lowercased HTTP method name as the key, e.g.
  6784. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6785. *
  6786. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6787. * fashion. For example:
  6788. *
  6789. * ```
  6790. * module.run(function($http) {
  6791. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6792. * });
  6793. * ```
  6794. *
  6795. * In addition, you can supply a `headers` property in the config object passed when
  6796. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6797. *
  6798. *
  6799. * # Transforming Requests and Responses
  6800. *
  6801. * Both requests and responses can be transformed using transform functions. By default, Angular
  6802. * applies these transformations:
  6803. *
  6804. * Request transformations:
  6805. *
  6806. * - If the `data` property of the request configuration object contains an object, serialize it
  6807. * into JSON format.
  6808. *
  6809. * Response transformations:
  6810. *
  6811. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6812. * - If JSON response is detected, deserialize it using a JSON parser.
  6813. *
  6814. * To globally augment or override the default transforms, modify the
  6815. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6816. * properties. These properties are by default an array of transform functions, which allows you
  6817. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6818. * also decide to completely override any default transformations by assigning your
  6819. * transformation functions to these properties directly without the array wrapper. These defaults
  6820. * are again available on the $http factory at run-time, which may be useful if you have run-time
  6821. * services you wish to be involved in your transformations.
  6822. *
  6823. * Similarly, to locally override the request/response transforms, augment the
  6824. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6825. * into `$http`.
  6826. *
  6827. *
  6828. * # Caching
  6829. *
  6830. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6831. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6832. * When the cache is enabled, `$http` stores the response from the server in the specified
  6833. * cache. The next time the same request is made, the response is served from the cache without
  6834. * sending a request to the server.
  6835. *
  6836. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6837. * the same way that real requests are.
  6838. *
  6839. * If there are multiple GET requests for the same URL that should be cached using the same
  6840. * cache, but the cache is not populated yet, only one request to the server will be made and
  6841. * the remaining requests will be fulfilled using the response from the first request.
  6842. *
  6843. * You can change the default cache to a new object (built with
  6844. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  6845. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  6846. * their `cache` property to `true` will now use this cache object.
  6847. *
  6848. * If you set the default cache to `false` then only requests that specify their own custom
  6849. * cache object will be cached.
  6850. *
  6851. * # Interceptors
  6852. *
  6853. * Before you start creating interceptors, be sure to understand the
  6854. * {@link ng.$q $q and deferred/promise APIs}.
  6855. *
  6856. * For purposes of global error handling, authentication, or any kind of synchronous or
  6857. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  6858. * able to intercept requests before they are handed to the server and
  6859. * responses before they are handed over to the application code that
  6860. * initiated these requests. The interceptors leverage the {@link ng.$q
  6861. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  6862. *
  6863. * The interceptors are service factories that are registered with the `$httpProvider` by
  6864. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  6865. * injected with dependencies (if specified) and returns the interceptor.
  6866. *
  6867. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  6868. *
  6869. * * `request`: interceptors get called with a http `config` object. The function is free to
  6870. * modify the `config` object or create a new one. The function needs to return the `config`
  6871. * object directly, or a promise containing the `config` or a new `config` object.
  6872. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  6873. * resolved with a rejection.
  6874. * * `response`: interceptors get called with http `response` object. The function is free to
  6875. * modify the `response` object or create a new one. The function needs to return the `response`
  6876. * object directly, or as a promise containing the `response` or a new `response` object.
  6877. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  6878. * resolved with a rejection.
  6879. *
  6880. *
  6881. * ```js
  6882. * // register the interceptor as a service
  6883. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6884. * return {
  6885. * // optional method
  6886. * 'request': function(config) {
  6887. * // do something on success
  6888. * return config;
  6889. * },
  6890. *
  6891. * // optional method
  6892. * 'requestError': function(rejection) {
  6893. * // do something on error
  6894. * if (canRecover(rejection)) {
  6895. * return responseOrNewPromise
  6896. * }
  6897. * return $q.reject(rejection);
  6898. * },
  6899. *
  6900. *
  6901. *
  6902. * // optional method
  6903. * 'response': function(response) {
  6904. * // do something on success
  6905. * return response;
  6906. * },
  6907. *
  6908. * // optional method
  6909. * 'responseError': function(rejection) {
  6910. * // do something on error
  6911. * if (canRecover(rejection)) {
  6912. * return responseOrNewPromise
  6913. * }
  6914. * return $q.reject(rejection);
  6915. * }
  6916. * };
  6917. * });
  6918. *
  6919. * $httpProvider.interceptors.push('myHttpInterceptor');
  6920. *
  6921. *
  6922. * // alternatively, register the interceptor via an anonymous factory
  6923. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  6924. * return {
  6925. * 'request': function(config) {
  6926. * // same as above
  6927. * },
  6928. *
  6929. * 'response': function(response) {
  6930. * // same as above
  6931. * }
  6932. * };
  6933. * });
  6934. * ```
  6935. *
  6936. * # Response interceptors (DEPRECATED)
  6937. *
  6938. * Before you start creating interceptors, be sure to understand the
  6939. * {@link ng.$q $q and deferred/promise APIs}.
  6940. *
  6941. * For purposes of global error handling, authentication or any kind of synchronous or
  6942. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  6943. * responses for http requests before they are handed over to the application code that
  6944. * initiated these requests. The response interceptors leverage the {@link ng.$q
  6945. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  6946. *
  6947. * The interceptors are service factories that are registered with the $httpProvider by
  6948. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  6949. * injected with dependencies (if specified) and returns the interceptor — a function that
  6950. * takes a {@link ng.$q promise} and returns the original or a new promise.
  6951. *
  6952. * ```js
  6953. * // register the interceptor as a service
  6954. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6955. * return function(promise) {
  6956. * return promise.then(function(response) {
  6957. * // do something on success
  6958. * return response;
  6959. * }, function(response) {
  6960. * // do something on error
  6961. * if (canRecover(response)) {
  6962. * return responseOrNewPromise
  6963. * }
  6964. * return $q.reject(response);
  6965. * });
  6966. * }
  6967. * });
  6968. *
  6969. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  6970. *
  6971. *
  6972. * // register the interceptor via an anonymous factory
  6973. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  6974. * return function(promise) {
  6975. * // same as above
  6976. * }
  6977. * });
  6978. * ```
  6979. *
  6980. *
  6981. * # Security Considerations
  6982. *
  6983. * When designing web applications, consider security threats from:
  6984. *
  6985. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  6986. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  6987. *
  6988. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  6989. * pre-configured with strategies that address these issues, but for this to work backend server
  6990. * cooperation is required.
  6991. *
  6992. * ## JSON Vulnerability Protection
  6993. *
  6994. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  6995. * allows third party website to turn your JSON resource URL into
  6996. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  6997. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  6998. * Angular will automatically strip the prefix before processing it as JSON.
  6999. *
  7000. * For example if your server needs to return:
  7001. * ```js
  7002. * ['one','two']
  7003. * ```
  7004. *
  7005. * which is vulnerable to attack, your server can return:
  7006. * ```js
  7007. * )]}',
  7008. * ['one','two']
  7009. * ```
  7010. *
  7011. * Angular will strip the prefix, before processing the JSON.
  7012. *
  7013. *
  7014. * ## Cross Site Request Forgery (XSRF) Protection
  7015. *
  7016. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  7017. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  7018. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  7019. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  7020. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  7021. * the XHR came from JavaScript running on your domain. The header will not be set for
  7022. * cross-domain requests.
  7023. *
  7024. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7025. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7026. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7027. * that only JavaScript running on your domain could have sent the request. The token must be
  7028. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7029. * making up its own tokens). We recommend that the token is a digest of your site's
  7030. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
  7031. * for added security.
  7032. *
  7033. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7034. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7035. * or the per-request config object.
  7036. *
  7037. *
  7038. * @param {object} config Object describing the request to be made and how it should be
  7039. * processed. The object has following properties:
  7040. *
  7041. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7042. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7043. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7044. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7045. * JSONified.
  7046. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7047. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7048. * HTTP headers to send to the server. If the return value of a function is null, the
  7049. * header will not be sent.
  7050. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7051. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7052. * - **transformRequest** –
  7053. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7054. * transform function or an array of such functions. The transform function takes the http
  7055. * request body and headers and returns its transformed (typically serialized) version.
  7056. * - **transformResponse** –
  7057. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7058. * transform function or an array of such functions. The transform function takes the http
  7059. * response body and headers and returns its transformed (typically deserialized) version.
  7060. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7061. * GET request, otherwise if a cache instance built with
  7062. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7063. * caching.
  7064. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7065. * that should abort the request when resolved.
  7066. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  7067. * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5
  7068. * for more information.
  7069. * - **responseType** - `{string}` - see
  7070. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7071. *
  7072. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7073. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7074. * method takes two arguments a success and an error callback which will be called with a
  7075. * response object. The `success` and `error` methods take a single argument - a function that
  7076. * will be called when the request succeeds or fails respectively. The arguments passed into
  7077. * these functions are destructured representation of the response object passed into the
  7078. * `then` method. The response object has these properties:
  7079. *
  7080. * - **data** – `{string|Object}` – The response body transformed with the transform
  7081. * functions.
  7082. * - **status** – `{number}` – HTTP status code of the response.
  7083. * - **headers** – `{function([headerName])}` – Header getter function.
  7084. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7085. * - **statusText** – `{string}` – HTTP status text of the response.
  7086. *
  7087. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7088. * requests. This is primarily meant to be used for debugging purposes.
  7089. *
  7090. *
  7091. * @example
  7092. <example>
  7093. <file name="index.html">
  7094. <div ng-controller="FetchCtrl">
  7095. <select ng-model="method">
  7096. <option>GET</option>
  7097. <option>JSONP</option>
  7098. </select>
  7099. <input type="text" ng-model="url" size="80"/>
  7100. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7101. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7102. <button id="samplejsonpbtn"
  7103. ng-click="updateModel('JSONP',
  7104. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7105. Sample JSONP
  7106. </button>
  7107. <button id="invalidjsonpbtn"
  7108. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7109. Invalid JSONP
  7110. </button>
  7111. <pre>http status code: {{status}}</pre>
  7112. <pre>http response data: {{data}}</pre>
  7113. </div>
  7114. </file>
  7115. <file name="script.js">
  7116. function FetchCtrl($scope, $http, $templateCache) {
  7117. $scope.method = 'GET';
  7118. $scope.url = 'http-hello.html';
  7119. $scope.fetch = function() {
  7120. $scope.code = null;
  7121. $scope.response = null;
  7122. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7123. success(function(data, status) {
  7124. $scope.status = status;
  7125. $scope.data = data;
  7126. }).
  7127. error(function(data, status) {
  7128. $scope.data = data || "Request failed";
  7129. $scope.status = status;
  7130. });
  7131. };
  7132. $scope.updateModel = function(method, url) {
  7133. $scope.method = method;
  7134. $scope.url = url;
  7135. };
  7136. }
  7137. </file>
  7138. <file name="http-hello.html">
  7139. Hello, $http!
  7140. </file>
  7141. <file name="protractor.js" type="protractor">
  7142. var status = element(by.binding('status'));
  7143. var data = element(by.binding('data'));
  7144. var fetchBtn = element(by.id('fetchbtn'));
  7145. var sampleGetBtn = element(by.id('samplegetbtn'));
  7146. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7147. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7148. it('should make an xhr GET request', function() {
  7149. sampleGetBtn.click();
  7150. fetchBtn.click();
  7151. expect(status.getText()).toMatch('200');
  7152. expect(data.getText()).toMatch(/Hello, \$http!/);
  7153. });
  7154. it('should make a JSONP request to angularjs.org', function() {
  7155. sampleJsonpBtn.click();
  7156. fetchBtn.click();
  7157. expect(status.getText()).toMatch('200');
  7158. expect(data.getText()).toMatch(/Super Hero!/);
  7159. });
  7160. it('should make JSONP request to invalid URL and invoke the error handler',
  7161. function() {
  7162. invalidJsonpBtn.click();
  7163. fetchBtn.click();
  7164. expect(status.getText()).toMatch('0');
  7165. expect(data.getText()).toMatch('Request failed');
  7166. });
  7167. </file>
  7168. </example>
  7169. */
  7170. function $http(requestConfig) {
  7171. var config = {
  7172. method: 'get',
  7173. transformRequest: defaults.transformRequest,
  7174. transformResponse: defaults.transformResponse
  7175. };
  7176. var headers = mergeHeaders(requestConfig);
  7177. extend(config, requestConfig);
  7178. config.headers = headers;
  7179. config.method = uppercase(config.method);
  7180. var xsrfValue = urlIsSameOrigin(config.url)
  7181. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7182. : undefined;
  7183. if (xsrfValue) {
  7184. headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7185. }
  7186. var serverRequest = function(config) {
  7187. headers = config.headers;
  7188. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7189. // strip content-type if data is undefined
  7190. if (isUndefined(config.data)) {
  7191. forEach(headers, function(value, header) {
  7192. if (lowercase(header) === 'content-type') {
  7193. delete headers[header];
  7194. }
  7195. });
  7196. }
  7197. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7198. config.withCredentials = defaults.withCredentials;
  7199. }
  7200. // send request
  7201. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7202. };
  7203. var chain = [serverRequest, undefined];
  7204. var promise = $q.when(config);
  7205. // apply interceptors
  7206. forEach(reversedInterceptors, function(interceptor) {
  7207. if (interceptor.request || interceptor.requestError) {
  7208. chain.unshift(interceptor.request, interceptor.requestError);
  7209. }
  7210. if (interceptor.response || interceptor.responseError) {
  7211. chain.push(interceptor.response, interceptor.responseError);
  7212. }
  7213. });
  7214. while(chain.length) {
  7215. var thenFn = chain.shift();
  7216. var rejectFn = chain.shift();
  7217. promise = promise.then(thenFn, rejectFn);
  7218. }
  7219. promise.success = function(fn) {
  7220. promise.then(function(response) {
  7221. fn(response.data, response.status, response.headers, config);
  7222. });
  7223. return promise;
  7224. };
  7225. promise.error = function(fn) {
  7226. promise.then(null, function(response) {
  7227. fn(response.data, response.status, response.headers, config);
  7228. });
  7229. return promise;
  7230. };
  7231. return promise;
  7232. function transformResponse(response) {
  7233. // make a copy since the response must be cacheable
  7234. var resp = extend({}, response, {
  7235. data: transformData(response.data, response.headers, config.transformResponse)
  7236. });
  7237. return (isSuccess(response.status))
  7238. ? resp
  7239. : $q.reject(resp);
  7240. }
  7241. function mergeHeaders(config) {
  7242. var defHeaders = defaults.headers,
  7243. reqHeaders = extend({}, config.headers),
  7244. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7245. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7246. // execute if header value is function
  7247. execHeaders(defHeaders);
  7248. execHeaders(reqHeaders);
  7249. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7250. defaultHeadersIteration:
  7251. for (defHeaderName in defHeaders) {
  7252. lowercaseDefHeaderName = lowercase(defHeaderName);
  7253. for (reqHeaderName in reqHeaders) {
  7254. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7255. continue defaultHeadersIteration;
  7256. }
  7257. }
  7258. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7259. }
  7260. return reqHeaders;
  7261. function execHeaders(headers) {
  7262. var headerContent;
  7263. forEach(headers, function(headerFn, header) {
  7264. if (isFunction(headerFn)) {
  7265. headerContent = headerFn();
  7266. if (headerContent != null) {
  7267. headers[header] = headerContent;
  7268. } else {
  7269. delete headers[header];
  7270. }
  7271. }
  7272. });
  7273. }
  7274. }
  7275. }
  7276. $http.pendingRequests = [];
  7277. /**
  7278. * @ngdoc method
  7279. * @name $http#get
  7280. *
  7281. * @description
  7282. * Shortcut method to perform `GET` request.
  7283. *
  7284. * @param {string} url Relative or absolute URL specifying the destination of the request
  7285. * @param {Object=} config Optional configuration object
  7286. * @returns {HttpPromise} Future object
  7287. */
  7288. /**
  7289. * @ngdoc method
  7290. * @name $http#delete
  7291. *
  7292. * @description
  7293. * Shortcut method to perform `DELETE` request.
  7294. *
  7295. * @param {string} url Relative or absolute URL specifying the destination of the request
  7296. * @param {Object=} config Optional configuration object
  7297. * @returns {HttpPromise} Future object
  7298. */
  7299. /**
  7300. * @ngdoc method
  7301. * @name $http#head
  7302. *
  7303. * @description
  7304. * Shortcut method to perform `HEAD` request.
  7305. *
  7306. * @param {string} url Relative or absolute URL specifying the destination of the request
  7307. * @param {Object=} config Optional configuration object
  7308. * @returns {HttpPromise} Future object
  7309. */
  7310. /**
  7311. * @ngdoc method
  7312. * @name $http#jsonp
  7313. *
  7314. * @description
  7315. * Shortcut method to perform `JSONP` request.
  7316. *
  7317. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7318. * Should contain `JSON_CALLBACK` string.
  7319. * @param {Object=} config Optional configuration object
  7320. * @returns {HttpPromise} Future object
  7321. */
  7322. createShortMethods('get', 'delete', 'head', 'jsonp');
  7323. /**
  7324. * @ngdoc method
  7325. * @name $http#post
  7326. *
  7327. * @description
  7328. * Shortcut method to perform `POST` request.
  7329. *
  7330. * @param {string} url Relative or absolute URL specifying the destination of the request
  7331. * @param {*} data Request content
  7332. * @param {Object=} config Optional configuration object
  7333. * @returns {HttpPromise} Future object
  7334. */
  7335. /**
  7336. * @ngdoc method
  7337. * @name $http#put
  7338. *
  7339. * @description
  7340. * Shortcut method to perform `PUT` request.
  7341. *
  7342. * @param {string} url Relative or absolute URL specifying the destination of the request
  7343. * @param {*} data Request content
  7344. * @param {Object=} config Optional configuration object
  7345. * @returns {HttpPromise} Future object
  7346. */
  7347. createShortMethodsWithData('post', 'put');
  7348. /**
  7349. * @ngdoc property
  7350. * @name $http#defaults
  7351. *
  7352. * @description
  7353. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7354. * default headers, withCredentials as well as request and response transformations.
  7355. *
  7356. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7357. */
  7358. $http.defaults = defaults;
  7359. return $http;
  7360. function createShortMethods(names) {
  7361. forEach(arguments, function(name) {
  7362. $http[name] = function(url, config) {
  7363. return $http(extend(config || {}, {
  7364. method: name,
  7365. url: url
  7366. }));
  7367. };
  7368. });
  7369. }
  7370. function createShortMethodsWithData(name) {
  7371. forEach(arguments, function(name) {
  7372. $http[name] = function(url, data, config) {
  7373. return $http(extend(config || {}, {
  7374. method: name,
  7375. url: url,
  7376. data: data
  7377. }));
  7378. };
  7379. });
  7380. }
  7381. /**
  7382. * Makes the request.
  7383. *
  7384. * !!! ACCESSES CLOSURE VARS:
  7385. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7386. */
  7387. function sendReq(config, reqData, reqHeaders) {
  7388. var deferred = $q.defer(),
  7389. promise = deferred.promise,
  7390. cache,
  7391. cachedResp,
  7392. url = buildUrl(config.url, config.params);
  7393. $http.pendingRequests.push(config);
  7394. promise.then(removePendingReq, removePendingReq);
  7395. if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
  7396. cache = isObject(config.cache) ? config.cache
  7397. : isObject(defaults.cache) ? defaults.cache
  7398. : defaultCache;
  7399. }
  7400. if (cache) {
  7401. cachedResp = cache.get(url);
  7402. if (isDefined(cachedResp)) {
  7403. if (cachedResp.then) {
  7404. // cached request has already been sent, but there is no response yet
  7405. cachedResp.then(removePendingReq, removePendingReq);
  7406. return cachedResp;
  7407. } else {
  7408. // serving from cache
  7409. if (isArray(cachedResp)) {
  7410. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  7411. } else {
  7412. resolvePromise(cachedResp, 200, {}, 'OK');
  7413. }
  7414. }
  7415. } else {
  7416. // put the promise for the non-transformed response into cache as a placeholder
  7417. cache.put(url, promise);
  7418. }
  7419. }
  7420. // if we won't have the response in cache, send the request to the backend
  7421. if (isUndefined(cachedResp)) {
  7422. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7423. config.withCredentials, config.responseType);
  7424. }
  7425. return promise;
  7426. /**
  7427. * Callback registered to $httpBackend():
  7428. * - caches the response if desired
  7429. * - resolves the raw $http promise
  7430. * - calls $apply
  7431. */
  7432. function done(status, response, headersString, statusText) {
  7433. if (cache) {
  7434. if (isSuccess(status)) {
  7435. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7436. } else {
  7437. // remove promise from the cache
  7438. cache.remove(url);
  7439. }
  7440. }
  7441. resolvePromise(response, status, headersString, statusText);
  7442. if (!$rootScope.$$phase) $rootScope.$apply();
  7443. }
  7444. /**
  7445. * Resolves the raw $http promise.
  7446. */
  7447. function resolvePromise(response, status, headers, statusText) {
  7448. // normalize internal statuses to 0
  7449. status = Math.max(status, 0);
  7450. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7451. data: response,
  7452. status: status,
  7453. headers: headersGetter(headers),
  7454. config: config,
  7455. statusText : statusText
  7456. });
  7457. }
  7458. function removePendingReq() {
  7459. var idx = indexOf($http.pendingRequests, config);
  7460. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7461. }
  7462. }
  7463. function buildUrl(url, params) {
  7464. if (!params) return url;
  7465. var parts = [];
  7466. forEachSorted(params, function(value, key) {
  7467. if (value === null || isUndefined(value)) return;
  7468. if (!isArray(value)) value = [value];
  7469. forEach(value, function(v) {
  7470. if (isObject(v)) {
  7471. v = toJson(v);
  7472. }
  7473. parts.push(encodeUriQuery(key) + '=' +
  7474. encodeUriQuery(v));
  7475. });
  7476. });
  7477. if(parts.length > 0) {
  7478. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7479. }
  7480. return url;
  7481. }
  7482. }];
  7483. }
  7484. function createXhr(method) {
  7485. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7486. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7487. //if it is available
  7488. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7489. !window.XMLHttpRequest)) {
  7490. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7491. } else if (window.XMLHttpRequest) {
  7492. return new window.XMLHttpRequest();
  7493. }
  7494. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7495. }
  7496. /**
  7497. * @ngdoc service
  7498. * @name $httpBackend
  7499. * @requires $window
  7500. * @requires $document
  7501. *
  7502. * @description
  7503. * HTTP backend used by the {@link ng.$http service} that delegates to
  7504. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7505. *
  7506. * You should never need to use this service directly, instead use the higher-level abstractions:
  7507. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7508. *
  7509. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7510. * $httpBackend} which can be trained with responses.
  7511. */
  7512. function $HttpBackendProvider() {
  7513. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7514. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7515. }];
  7516. }
  7517. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7518. var ABORTED = -1;
  7519. // TODO(vojta): fix the signature
  7520. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7521. var status;
  7522. $browser.$$incOutstandingRequestCount();
  7523. url = url || $browser.url();
  7524. if (lowercase(method) == 'jsonp') {
  7525. var callbackId = '_' + (callbacks.counter++).toString(36);
  7526. callbacks[callbackId] = function(data) {
  7527. callbacks[callbackId].data = data;
  7528. callbacks[callbackId].called = true;
  7529. };
  7530. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7531. callbackId, function(status, text) {
  7532. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  7533. callbacks[callbackId] = noop;
  7534. });
  7535. } else {
  7536. var xhr = createXhr(method);
  7537. xhr.open(method, url, true);
  7538. forEach(headers, function(value, key) {
  7539. if (isDefined(value)) {
  7540. xhr.setRequestHeader(key, value);
  7541. }
  7542. });
  7543. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7544. // response is in the cache. the promise api will ensure that to the app code the api is
  7545. // always async
  7546. xhr.onreadystatechange = function() {
  7547. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7548. // xhrs that are resolved while the app is in the background (see #5426).
  7549. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7550. // continuing
  7551. //
  7552. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7553. // Safari respectively.
  7554. if (xhr && xhr.readyState == 4) {
  7555. var responseHeaders = null,
  7556. response = null;
  7557. if(status !== ABORTED) {
  7558. responseHeaders = xhr.getAllResponseHeaders();
  7559. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7560. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7561. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7562. }
  7563. completeRequest(callback,
  7564. status || xhr.status,
  7565. response,
  7566. responseHeaders,
  7567. xhr.statusText || '');
  7568. }
  7569. };
  7570. if (withCredentials) {
  7571. xhr.withCredentials = true;
  7572. }
  7573. if (responseType) {
  7574. try {
  7575. xhr.responseType = responseType;
  7576. } catch (e) {
  7577. // WebKit added support for the json responseType value on 09/03/2013
  7578. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7579. // known to throw when setting the value "json" as the response type. Other older
  7580. // browsers implementing the responseType
  7581. //
  7582. // The json response type can be ignored if not supported, because JSON payloads are
  7583. // parsed on the client-side regardless.
  7584. if (responseType !== 'json') {
  7585. throw e;
  7586. }
  7587. }
  7588. }
  7589. xhr.send(post || null);
  7590. }
  7591. if (timeout > 0) {
  7592. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7593. } else if (timeout && timeout.then) {
  7594. timeout.then(timeoutRequest);
  7595. }
  7596. function timeoutRequest() {
  7597. status = ABORTED;
  7598. jsonpDone && jsonpDone();
  7599. xhr && xhr.abort();
  7600. }
  7601. function completeRequest(callback, status, response, headersString, statusText) {
  7602. // cancel timeout and subsequent timeout promise resolution
  7603. timeoutId && $browserDefer.cancel(timeoutId);
  7604. jsonpDone = xhr = null;
  7605. // fix status code when it is 0 (0 status is undocumented).
  7606. // Occurs when accessing file resources or on Android 4.1 stock browser
  7607. // while retrieving files from application cache.
  7608. if (status === 0) {
  7609. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7610. }
  7611. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7612. status = status === 1223 ? 204 : status;
  7613. statusText = statusText || '';
  7614. callback(status, response, headersString, statusText);
  7615. $browser.$$completeOutstandingRequest(noop);
  7616. }
  7617. };
  7618. function jsonpReq(url, callbackId, done) {
  7619. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7620. // - fetches local scripts via XHR and evals them
  7621. // - adds and immediately removes script elements from the document
  7622. var script = rawDocument.createElement('script'), callback = null;
  7623. script.type = "text/javascript";
  7624. script.src = url;
  7625. script.async = true;
  7626. callback = function(event) {
  7627. removeEventListenerFn(script, "load", callback);
  7628. removeEventListenerFn(script, "error", callback);
  7629. rawDocument.body.removeChild(script);
  7630. script = null;
  7631. var status = -1;
  7632. var text = "unknown";
  7633. if (event) {
  7634. if (event.type === "load" && !callbacks[callbackId].called) {
  7635. event = { type: "error" };
  7636. }
  7637. text = event.type;
  7638. status = event.type === "error" ? 404 : 200;
  7639. }
  7640. if (done) {
  7641. done(status, text);
  7642. }
  7643. };
  7644. addEventListenerFn(script, "load", callback);
  7645. addEventListenerFn(script, "error", callback);
  7646. if (msie <= 8) {
  7647. script.onreadystatechange = function() {
  7648. if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) {
  7649. script.onreadystatechange = null;
  7650. callback({
  7651. type: 'load'
  7652. });
  7653. }
  7654. };
  7655. }
  7656. rawDocument.body.appendChild(script);
  7657. return callback;
  7658. }
  7659. }
  7660. var $interpolateMinErr = minErr('$interpolate');
  7661. /**
  7662. * @ngdoc provider
  7663. * @name $interpolateProvider
  7664. * @kind function
  7665. *
  7666. * @description
  7667. *
  7668. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7669. *
  7670. * @example
  7671. <example module="customInterpolationApp">
  7672. <file name="index.html">
  7673. <script>
  7674. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7675. customInterpolationApp.config(function($interpolateProvider) {
  7676. $interpolateProvider.startSymbol('//');
  7677. $interpolateProvider.endSymbol('//');
  7678. });
  7679. customInterpolationApp.controller('DemoController', function() {
  7680. this.label = "This binding is brought you by // interpolation symbols.";
  7681. });
  7682. </script>
  7683. <div ng-app="App" ng-controller="DemoController as demo">
  7684. //demo.label//
  7685. </div>
  7686. </file>
  7687. <file name="protractor.js" type="protractor">
  7688. it('should interpolate binding with custom symbols', function() {
  7689. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7690. });
  7691. </file>
  7692. </example>
  7693. */
  7694. function $InterpolateProvider() {
  7695. var startSymbol = '{{';
  7696. var endSymbol = '}}';
  7697. /**
  7698. * @ngdoc method
  7699. * @name $interpolateProvider#startSymbol
  7700. * @description
  7701. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7702. *
  7703. * @param {string=} value new value to set the starting symbol to.
  7704. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7705. */
  7706. this.startSymbol = function(value){
  7707. if (value) {
  7708. startSymbol = value;
  7709. return this;
  7710. } else {
  7711. return startSymbol;
  7712. }
  7713. };
  7714. /**
  7715. * @ngdoc method
  7716. * @name $interpolateProvider#endSymbol
  7717. * @description
  7718. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7719. *
  7720. * @param {string=} value new value to set the ending symbol to.
  7721. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7722. */
  7723. this.endSymbol = function(value){
  7724. if (value) {
  7725. endSymbol = value;
  7726. return this;
  7727. } else {
  7728. return endSymbol;
  7729. }
  7730. };
  7731. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7732. var startSymbolLength = startSymbol.length,
  7733. endSymbolLength = endSymbol.length;
  7734. /**
  7735. * @ngdoc service
  7736. * @name $interpolate
  7737. * @kind function
  7738. *
  7739. * @requires $parse
  7740. * @requires $sce
  7741. *
  7742. * @description
  7743. *
  7744. * Compiles a string with markup into an interpolation function. This service is used by the
  7745. * HTML {@link ng.$compile $compile} service for data binding. See
  7746. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7747. * interpolation markup.
  7748. *
  7749. *
  7750. * ```js
  7751. * var $interpolate = ...; // injected
  7752. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7753. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7754. * ```
  7755. *
  7756. *
  7757. * @param {string} text The text with markup to interpolate.
  7758. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7759. * embedded expression in order to return an interpolation function. Strings with no
  7760. * embedded expression will return null for the interpolation function.
  7761. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7762. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7763. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7764. * provides Strict Contextual Escaping for details.
  7765. * @returns {function(context)} an interpolation function which is used to compute the
  7766. * interpolated string. The function has these parameters:
  7767. *
  7768. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7769. * against.
  7770. *
  7771. */
  7772. function $interpolate(text, mustHaveExpression, trustedContext) {
  7773. var startIndex,
  7774. endIndex,
  7775. index = 0,
  7776. parts = [],
  7777. length = text.length,
  7778. hasInterpolation = false,
  7779. fn,
  7780. exp,
  7781. concat = [];
  7782. while(index < length) {
  7783. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7784. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7785. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7786. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7787. fn.exp = exp;
  7788. index = endIndex + endSymbolLength;
  7789. hasInterpolation = true;
  7790. } else {
  7791. // we did not find anything, so we have to add the remainder to the parts array
  7792. (index != length) && parts.push(text.substring(index));
  7793. index = length;
  7794. }
  7795. }
  7796. if (!(length = parts.length)) {
  7797. // we added, nothing, must have been an empty string.
  7798. parts.push('');
  7799. length = 1;
  7800. }
  7801. // Concatenating expressions makes it hard to reason about whether some combination of
  7802. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7803. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7804. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7805. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7806. // the load when auditing for XSS issues.
  7807. if (trustedContext && parts.length > 1) {
  7808. throw $interpolateMinErr('noconcat',
  7809. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7810. "interpolations that concatenate multiple expressions when a trusted value is " +
  7811. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7812. }
  7813. if (!mustHaveExpression || hasInterpolation) {
  7814. concat.length = length;
  7815. fn = function(context) {
  7816. try {
  7817. for(var i = 0, ii = length, part; i<ii; i++) {
  7818. if (typeof (part = parts[i]) == 'function') {
  7819. part = part(context);
  7820. if (trustedContext) {
  7821. part = $sce.getTrusted(trustedContext, part);
  7822. } else {
  7823. part = $sce.valueOf(part);
  7824. }
  7825. if (part == null) { // null || undefined
  7826. part = '';
  7827. } else {
  7828. switch (typeof part) {
  7829. case 'string':
  7830. {
  7831. break;
  7832. }
  7833. case 'number':
  7834. {
  7835. part = '' + part;
  7836. break;
  7837. }
  7838. default:
  7839. {
  7840. part = toJson(part);
  7841. }
  7842. }
  7843. }
  7844. }
  7845. concat[i] = part;
  7846. }
  7847. return concat.join('');
  7848. }
  7849. catch(err) {
  7850. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  7851. err.toString());
  7852. $exceptionHandler(newErr);
  7853. }
  7854. };
  7855. fn.exp = text;
  7856. fn.parts = parts;
  7857. return fn;
  7858. }
  7859. }
  7860. /**
  7861. * @ngdoc method
  7862. * @name $interpolate#startSymbol
  7863. * @description
  7864. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  7865. *
  7866. * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
  7867. * the symbol.
  7868. *
  7869. * @returns {string} start symbol.
  7870. */
  7871. $interpolate.startSymbol = function() {
  7872. return startSymbol;
  7873. };
  7874. /**
  7875. * @ngdoc method
  7876. * @name $interpolate#endSymbol
  7877. * @description
  7878. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7879. *
  7880. * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
  7881. * the symbol.
  7882. *
  7883. * @returns {string} end symbol.
  7884. */
  7885. $interpolate.endSymbol = function() {
  7886. return endSymbol;
  7887. };
  7888. return $interpolate;
  7889. }];
  7890. }
  7891. function $IntervalProvider() {
  7892. this.$get = ['$rootScope', '$window', '$q',
  7893. function($rootScope, $window, $q) {
  7894. var intervals = {};
  7895. /**
  7896. * @ngdoc service
  7897. * @name $interval
  7898. *
  7899. * @description
  7900. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  7901. * milliseconds.
  7902. *
  7903. * The return value of registering an interval function is a promise. This promise will be
  7904. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  7905. * run indefinitely if `count` is not defined. The value of the notification will be the
  7906. * number of iterations that have run.
  7907. * To cancel an interval, call `$interval.cancel(promise)`.
  7908. *
  7909. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  7910. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  7911. * time.
  7912. *
  7913. * <div class="alert alert-warning">
  7914. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  7915. * with them. In particular they are not automatically destroyed when a controller's scope or a
  7916. * directive's element are destroyed.
  7917. * You should take this into consideration and make sure to always cancel the interval at the
  7918. * appropriate moment. See the example below for more details on how and when to do this.
  7919. * </div>
  7920. *
  7921. * @param {function()} fn A function that should be called repeatedly.
  7922. * @param {number} delay Number of milliseconds between each function call.
  7923. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  7924. * indefinitely.
  7925. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  7926. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  7927. * @returns {promise} A promise which will be notified on each iteration.
  7928. *
  7929. * @example
  7930. * <example module="time">
  7931. * <file name="index.html">
  7932. * <script>
  7933. * function Ctrl2($scope,$interval) {
  7934. * $scope.format = 'M/d/yy h:mm:ss a';
  7935. * $scope.blood_1 = 100;
  7936. * $scope.blood_2 = 120;
  7937. *
  7938. * var stop;
  7939. * $scope.fight = function() {
  7940. * // Don't start a new fight if we are already fighting
  7941. * if ( angular.isDefined(stop) ) return;
  7942. *
  7943. * stop = $interval(function() {
  7944. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  7945. * $scope.blood_1 = $scope.blood_1 - 3;
  7946. * $scope.blood_2 = $scope.blood_2 - 4;
  7947. * } else {
  7948. * $scope.stopFight();
  7949. * }
  7950. * }, 100);
  7951. * };
  7952. *
  7953. * $scope.stopFight = function() {
  7954. * if (angular.isDefined(stop)) {
  7955. * $interval.cancel(stop);
  7956. * stop = undefined;
  7957. * }
  7958. * };
  7959. *
  7960. * $scope.resetFight = function() {
  7961. * $scope.blood_1 = 100;
  7962. * $scope.blood_2 = 120;
  7963. * }
  7964. *
  7965. * $scope.$on('$destroy', function() {
  7966. * // Make sure that the interval is destroyed too
  7967. * $scope.stopFight();
  7968. * });
  7969. * }
  7970. *
  7971. * angular.module('time', [])
  7972. * // Register the 'myCurrentTime' directive factory method.
  7973. * // We inject $interval and dateFilter service since the factory method is DI.
  7974. * .directive('myCurrentTime', function($interval, dateFilter) {
  7975. * // return the directive link function. (compile function not needed)
  7976. * return function(scope, element, attrs) {
  7977. * var format, // date format
  7978. * stopTime; // so that we can cancel the time updates
  7979. *
  7980. * // used to update the UI
  7981. * function updateTime() {
  7982. * element.text(dateFilter(new Date(), format));
  7983. * }
  7984. *
  7985. * // watch the expression, and update the UI on change.
  7986. * scope.$watch(attrs.myCurrentTime, function(value) {
  7987. * format = value;
  7988. * updateTime();
  7989. * });
  7990. *
  7991. * stopTime = $interval(updateTime, 1000);
  7992. *
  7993. * // listen on DOM destroy (removal) event, and cancel the next UI update
  7994. * // to prevent updating time ofter the DOM element was removed.
  7995. * element.bind('$destroy', function() {
  7996. * $interval.cancel(stopTime);
  7997. * });
  7998. * }
  7999. * });
  8000. * </script>
  8001. *
  8002. * <div>
  8003. * <div ng-controller="Ctrl2">
  8004. * Date format: <input ng-model="format"> <hr/>
  8005. * Current time is: <span my-current-time="format"></span>
  8006. * <hr/>
  8007. * Blood 1 : <font color='red'>{{blood_1}}</font>
  8008. * Blood 2 : <font color='red'>{{blood_2}}</font>
  8009. * <button type="button" data-ng-click="fight()">Fight</button>
  8010. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  8011. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  8012. * </div>
  8013. * </div>
  8014. *
  8015. * </file>
  8016. * </example>
  8017. */
  8018. function interval(fn, delay, count, invokeApply) {
  8019. var setInterval = $window.setInterval,
  8020. clearInterval = $window.clearInterval,
  8021. deferred = $q.defer(),
  8022. promise = deferred.promise,
  8023. iteration = 0,
  8024. skipApply = (isDefined(invokeApply) && !invokeApply);
  8025. count = isDefined(count) ? count : 0;
  8026. promise.then(null, null, fn);
  8027. promise.$$intervalId = setInterval(function tick() {
  8028. deferred.notify(iteration++);
  8029. if (count > 0 && iteration >= count) {
  8030. deferred.resolve(iteration);
  8031. clearInterval(promise.$$intervalId);
  8032. delete intervals[promise.$$intervalId];
  8033. }
  8034. if (!skipApply) $rootScope.$apply();
  8035. }, delay);
  8036. intervals[promise.$$intervalId] = deferred;
  8037. return promise;
  8038. }
  8039. /**
  8040. * @ngdoc method
  8041. * @name $interval#cancel
  8042. *
  8043. * @description
  8044. * Cancels a task associated with the `promise`.
  8045. *
  8046. * @param {promise} promise returned by the `$interval` function.
  8047. * @returns {boolean} Returns `true` if the task was successfully canceled.
  8048. */
  8049. interval.cancel = function(promise) {
  8050. if (promise && promise.$$intervalId in intervals) {
  8051. intervals[promise.$$intervalId].reject('canceled');
  8052. clearInterval(promise.$$intervalId);
  8053. delete intervals[promise.$$intervalId];
  8054. return true;
  8055. }
  8056. return false;
  8057. };
  8058. return interval;
  8059. }];
  8060. }
  8061. /**
  8062. * @ngdoc service
  8063. * @name $locale
  8064. *
  8065. * @description
  8066. * $locale service provides localization rules for various Angular components. As of right now the
  8067. * only public api is:
  8068. *
  8069. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8070. */
  8071. function $LocaleProvider(){
  8072. this.$get = function() {
  8073. return {
  8074. id: 'en-us',
  8075. NUMBER_FORMATS: {
  8076. DECIMAL_SEP: '.',
  8077. GROUP_SEP: ',',
  8078. PATTERNS: [
  8079. { // Decimal Pattern
  8080. minInt: 1,
  8081. minFrac: 0,
  8082. maxFrac: 3,
  8083. posPre: '',
  8084. posSuf: '',
  8085. negPre: '-',
  8086. negSuf: '',
  8087. gSize: 3,
  8088. lgSize: 3
  8089. },{ //Currency Pattern
  8090. minInt: 1,
  8091. minFrac: 2,
  8092. maxFrac: 2,
  8093. posPre: '\u00A4',
  8094. posSuf: '',
  8095. negPre: '(\u00A4',
  8096. negSuf: ')',
  8097. gSize: 3,
  8098. lgSize: 3
  8099. }
  8100. ],
  8101. CURRENCY_SYM: '$'
  8102. },
  8103. DATETIME_FORMATS: {
  8104. MONTH:
  8105. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8106. .split(','),
  8107. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8108. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8109. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8110. AMPMS: ['AM','PM'],
  8111. medium: 'MMM d, y h:mm:ss a',
  8112. short: 'M/d/yy h:mm a',
  8113. fullDate: 'EEEE, MMMM d, y',
  8114. longDate: 'MMMM d, y',
  8115. mediumDate: 'MMM d, y',
  8116. shortDate: 'M/d/yy',
  8117. mediumTime: 'h:mm:ss a',
  8118. shortTime: 'h:mm a'
  8119. },
  8120. pluralCat: function(num) {
  8121. if (num === 1) {
  8122. return 'one';
  8123. }
  8124. return 'other';
  8125. }
  8126. };
  8127. };
  8128. }
  8129. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8130. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8131. var $locationMinErr = minErr('$location');
  8132. /**
  8133. * Encode path using encodeUriSegment, ignoring forward slashes
  8134. *
  8135. * @param {string} path Path to encode
  8136. * @returns {string}
  8137. */
  8138. function encodePath(path) {
  8139. var segments = path.split('/'),
  8140. i = segments.length;
  8141. while (i--) {
  8142. segments[i] = encodeUriSegment(segments[i]);
  8143. }
  8144. return segments.join('/');
  8145. }
  8146. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8147. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8148. locationObj.$$protocol = parsedUrl.protocol;
  8149. locationObj.$$host = parsedUrl.hostname;
  8150. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8151. }
  8152. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8153. var prefixed = (relativeUrl.charAt(0) !== '/');
  8154. if (prefixed) {
  8155. relativeUrl = '/' + relativeUrl;
  8156. }
  8157. var match = urlResolve(relativeUrl, appBase);
  8158. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8159. match.pathname.substring(1) : match.pathname);
  8160. locationObj.$$search = parseKeyValue(match.search);
  8161. locationObj.$$hash = decodeURIComponent(match.hash);
  8162. // make sure path starts with '/';
  8163. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8164. locationObj.$$path = '/' + locationObj.$$path;
  8165. }
  8166. }
  8167. /**
  8168. *
  8169. * @param {string} begin
  8170. * @param {string} whole
  8171. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8172. * expected string.
  8173. */
  8174. function beginsWith(begin, whole) {
  8175. if (whole.indexOf(begin) === 0) {
  8176. return whole.substr(begin.length);
  8177. }
  8178. }
  8179. function stripHash(url) {
  8180. var index = url.indexOf('#');
  8181. return index == -1 ? url : url.substr(0, index);
  8182. }
  8183. function stripFile(url) {
  8184. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8185. }
  8186. /* return the server only (scheme://host:port) */
  8187. function serverBase(url) {
  8188. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8189. }
  8190. /**
  8191. * LocationHtml5Url represents an url
  8192. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8193. *
  8194. * @constructor
  8195. * @param {string} appBase application base URL
  8196. * @param {string} basePrefix url path prefix
  8197. */
  8198. function LocationHtml5Url(appBase, basePrefix) {
  8199. this.$$html5 = true;
  8200. basePrefix = basePrefix || '';
  8201. var appBaseNoFile = stripFile(appBase);
  8202. parseAbsoluteUrl(appBase, this, appBase);
  8203. /**
  8204. * Parse given html5 (regular) url string into properties
  8205. * @param {string} newAbsoluteUrl HTML5 url
  8206. * @private
  8207. */
  8208. this.$$parse = function(url) {
  8209. var pathUrl = beginsWith(appBaseNoFile, url);
  8210. if (!isString(pathUrl)) {
  8211. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8212. appBaseNoFile);
  8213. }
  8214. parseAppUrl(pathUrl, this, appBase);
  8215. if (!this.$$path) {
  8216. this.$$path = '/';
  8217. }
  8218. this.$$compose();
  8219. };
  8220. /**
  8221. * Compose url and update `absUrl` property
  8222. * @private
  8223. */
  8224. this.$$compose = function() {
  8225. var search = toKeyValue(this.$$search),
  8226. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8227. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8228. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8229. };
  8230. this.$$rewrite = function(url) {
  8231. var appUrl, prevAppUrl;
  8232. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8233. prevAppUrl = appUrl;
  8234. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8235. return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8236. } else {
  8237. return appBase + prevAppUrl;
  8238. }
  8239. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8240. return appBaseNoFile + appUrl;
  8241. } else if (appBaseNoFile == url + '/') {
  8242. return appBaseNoFile;
  8243. }
  8244. };
  8245. }
  8246. /**
  8247. * LocationHashbangUrl represents url
  8248. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8249. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8250. *
  8251. * @constructor
  8252. * @param {string} appBase application base URL
  8253. * @param {string} hashPrefix hashbang prefix
  8254. */
  8255. function LocationHashbangUrl(appBase, hashPrefix) {
  8256. var appBaseNoFile = stripFile(appBase);
  8257. parseAbsoluteUrl(appBase, this, appBase);
  8258. /**
  8259. * Parse given hashbang url into properties
  8260. * @param {string} url Hashbang url
  8261. * @private
  8262. */
  8263. this.$$parse = function(url) {
  8264. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8265. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8266. ? beginsWith(hashPrefix, withoutBaseUrl)
  8267. : (this.$$html5)
  8268. ? withoutBaseUrl
  8269. : '';
  8270. if (!isString(withoutHashUrl)) {
  8271. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8272. hashPrefix);
  8273. }
  8274. parseAppUrl(withoutHashUrl, this, appBase);
  8275. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8276. this.$$compose();
  8277. /*
  8278. * In Windows, on an anchor node on documents loaded from
  8279. * the filesystem, the browser will return a pathname
  8280. * prefixed with the drive name ('/C:/path') when a
  8281. * pathname without a drive is set:
  8282. * * a.setAttribute('href', '/foo')
  8283. * * a.pathname === '/C:/foo' //true
  8284. *
  8285. * Inside of Angular, we're always using pathnames that
  8286. * do not include drive names for routing.
  8287. */
  8288. function removeWindowsDriveName (path, url, base) {
  8289. /*
  8290. Matches paths for file protocol on windows,
  8291. such as /C:/foo/bar, and captures only /foo/bar.
  8292. */
  8293. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  8294. var firstPathSegmentMatch;
  8295. //Get the relative path from the input URL.
  8296. if (url.indexOf(base) === 0) {
  8297. url = url.replace(base, '');
  8298. }
  8299. // The input URL intentionally contains a first path segment that ends with a colon.
  8300. if (windowsFilePathExp.exec(url)) {
  8301. return path;
  8302. }
  8303. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8304. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8305. }
  8306. };
  8307. /**
  8308. * Compose hashbang url and update `absUrl` property
  8309. * @private
  8310. */
  8311. this.$$compose = function() {
  8312. var search = toKeyValue(this.$$search),
  8313. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8314. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8315. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8316. };
  8317. this.$$rewrite = function(url) {
  8318. if(stripHash(appBase) == stripHash(url)) {
  8319. return url;
  8320. }
  8321. };
  8322. }
  8323. /**
  8324. * LocationHashbangUrl represents url
  8325. * This object is exposed as $location service when html5 history api is enabled but the browser
  8326. * does not support it.
  8327. *
  8328. * @constructor
  8329. * @param {string} appBase application base URL
  8330. * @param {string} hashPrefix hashbang prefix
  8331. */
  8332. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8333. this.$$html5 = true;
  8334. LocationHashbangUrl.apply(this, arguments);
  8335. var appBaseNoFile = stripFile(appBase);
  8336. this.$$rewrite = function(url) {
  8337. var appUrl;
  8338. if ( appBase == stripHash(url) ) {
  8339. return url;
  8340. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8341. return appBase + hashPrefix + appUrl;
  8342. } else if ( appBaseNoFile === url + '/') {
  8343. return appBaseNoFile;
  8344. }
  8345. };
  8346. this.$$compose = function() {
  8347. var search = toKeyValue(this.$$search),
  8348. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8349. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8350. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  8351. this.$$absUrl = appBase + hashPrefix + this.$$url;
  8352. };
  8353. }
  8354. LocationHashbangInHtml5Url.prototype =
  8355. LocationHashbangUrl.prototype =
  8356. LocationHtml5Url.prototype = {
  8357. /**
  8358. * Are we in html5 mode?
  8359. * @private
  8360. */
  8361. $$html5: false,
  8362. /**
  8363. * Has any change been replacing ?
  8364. * @private
  8365. */
  8366. $$replace: false,
  8367. /**
  8368. * @ngdoc method
  8369. * @name $location#absUrl
  8370. *
  8371. * @description
  8372. * This method is getter only.
  8373. *
  8374. * Return full url representation with all segments encoded according to rules specified in
  8375. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8376. *
  8377. * @return {string} full url
  8378. */
  8379. absUrl: locationGetter('$$absUrl'),
  8380. /**
  8381. * @ngdoc method
  8382. * @name $location#url
  8383. *
  8384. * @description
  8385. * This method is getter / setter.
  8386. *
  8387. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8388. *
  8389. * Change path, search and hash, when called with parameter and return `$location`.
  8390. *
  8391. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8392. * @param {string=} replace The path that will be changed
  8393. * @return {string} url
  8394. */
  8395. url: function(url, replace) {
  8396. if (isUndefined(url))
  8397. return this.$$url;
  8398. var match = PATH_MATCH.exec(url);
  8399. if (match[1]) this.path(decodeURIComponent(match[1]));
  8400. if (match[2] || match[1]) this.search(match[3] || '');
  8401. this.hash(match[5] || '', replace);
  8402. return this;
  8403. },
  8404. /**
  8405. * @ngdoc method
  8406. * @name $location#protocol
  8407. *
  8408. * @description
  8409. * This method is getter only.
  8410. *
  8411. * Return protocol of current url.
  8412. *
  8413. * @return {string} protocol of current url
  8414. */
  8415. protocol: locationGetter('$$protocol'),
  8416. /**
  8417. * @ngdoc method
  8418. * @name $location#host
  8419. *
  8420. * @description
  8421. * This method is getter only.
  8422. *
  8423. * Return host of current url.
  8424. *
  8425. * @return {string} host of current url.
  8426. */
  8427. host: locationGetter('$$host'),
  8428. /**
  8429. * @ngdoc method
  8430. * @name $location#port
  8431. *
  8432. * @description
  8433. * This method is getter only.
  8434. *
  8435. * Return port of current url.
  8436. *
  8437. * @return {Number} port
  8438. */
  8439. port: locationGetter('$$port'),
  8440. /**
  8441. * @ngdoc method
  8442. * @name $location#path
  8443. *
  8444. * @description
  8445. * This method is getter / setter.
  8446. *
  8447. * Return path of current url when called without any parameter.
  8448. *
  8449. * Change path when called with parameter and return `$location`.
  8450. *
  8451. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8452. * if it is missing.
  8453. *
  8454. * @param {string=} path New path
  8455. * @return {string} path
  8456. */
  8457. path: locationGetterSetter('$$path', function(path) {
  8458. return path.charAt(0) == '/' ? path : '/' + path;
  8459. }),
  8460. /**
  8461. * @ngdoc method
  8462. * @name $location#search
  8463. *
  8464. * @description
  8465. * This method is getter / setter.
  8466. *
  8467. * Return search part (as object) of current url when called without any parameter.
  8468. *
  8469. * Change search part when called with parameter and return `$location`.
  8470. *
  8471. *
  8472. * ```js
  8473. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  8474. * var searchObject = $location.search();
  8475. * // => {foo: 'bar', baz: 'xoxo'}
  8476. *
  8477. *
  8478. * // set foo to 'yipee'
  8479. * $location.search('foo', 'yipee');
  8480. * // => $location
  8481. * ```
  8482. *
  8483. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8484. * hash object.
  8485. *
  8486. * When called with a single argument the method acts as a setter, setting the `search` component
  8487. * of `$location` to the specified value.
  8488. *
  8489. * If the argument is a hash object containing an array of values, these values will be encoded
  8490. * as duplicate search parameters in the url.
  8491. *
  8492. * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will
  8493. * override only a single search property.
  8494. *
  8495. * If `paramValue` is an array, it will override the property of the `search` component of
  8496. * `$location` specified via the first argument.
  8497. *
  8498. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  8499. *
  8500. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  8501. * one or more arguments returns `$location` object itself.
  8502. */
  8503. search: function(search, paramValue) {
  8504. switch (arguments.length) {
  8505. case 0:
  8506. return this.$$search;
  8507. case 1:
  8508. if (isString(search)) {
  8509. this.$$search = parseKeyValue(search);
  8510. } else if (isObject(search)) {
  8511. this.$$search = search;
  8512. } else {
  8513. throw $locationMinErr('isrcharg',
  8514. 'The first argument of the `$location#search()` call must be a string or an object.');
  8515. }
  8516. break;
  8517. default:
  8518. if (isUndefined(paramValue) || paramValue === null) {
  8519. delete this.$$search[search];
  8520. } else {
  8521. this.$$search[search] = paramValue;
  8522. }
  8523. }
  8524. this.$$compose();
  8525. return this;
  8526. },
  8527. /**
  8528. * @ngdoc method
  8529. * @name $location#hash
  8530. *
  8531. * @description
  8532. * This method is getter / setter.
  8533. *
  8534. * Return hash fragment when called without any parameter.
  8535. *
  8536. * Change hash fragment when called with parameter and return `$location`.
  8537. *
  8538. * @param {string=} hash New hash fragment
  8539. * @return {string} hash
  8540. */
  8541. hash: locationGetterSetter('$$hash', identity),
  8542. /**
  8543. * @ngdoc method
  8544. * @name $location#replace
  8545. *
  8546. * @description
  8547. * If called, all changes to $location during current `$digest` will be replacing current history
  8548. * record, instead of adding new one.
  8549. */
  8550. replace: function() {
  8551. this.$$replace = true;
  8552. return this;
  8553. }
  8554. };
  8555. function locationGetter(property) {
  8556. return function() {
  8557. return this[property];
  8558. };
  8559. }
  8560. function locationGetterSetter(property, preprocess) {
  8561. return function(value) {
  8562. if (isUndefined(value))
  8563. return this[property];
  8564. this[property] = preprocess(value);
  8565. this.$$compose();
  8566. return this;
  8567. };
  8568. }
  8569. /**
  8570. * @ngdoc service
  8571. * @name $location
  8572. *
  8573. * @requires $rootElement
  8574. *
  8575. * @description
  8576. * The $location service parses the URL in the browser address bar (based on the
  8577. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8578. * available to your application. Changes to the URL in the address bar are reflected into
  8579. * $location service and changes to $location are reflected into the browser address bar.
  8580. *
  8581. * **The $location service:**
  8582. *
  8583. * - Exposes the current URL in the browser address bar, so you can
  8584. * - Watch and observe the URL.
  8585. * - Change the URL.
  8586. * - Synchronizes the URL with the browser when the user
  8587. * - Changes the address bar.
  8588. * - Clicks the back or forward button (or clicks a History link).
  8589. * - Clicks on a link.
  8590. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8591. *
  8592. * For more information see {@link guide/$location Developer Guide: Using $location}
  8593. */
  8594. /**
  8595. * @ngdoc provider
  8596. * @name $locationProvider
  8597. * @description
  8598. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8599. */
  8600. function $LocationProvider(){
  8601. var hashPrefix = '',
  8602. html5Mode = false;
  8603. /**
  8604. * @ngdoc property
  8605. * @name $locationProvider#hashPrefix
  8606. * @description
  8607. * @param {string=} prefix Prefix for hash part (containing path and search)
  8608. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8609. */
  8610. this.hashPrefix = function(prefix) {
  8611. if (isDefined(prefix)) {
  8612. hashPrefix = prefix;
  8613. return this;
  8614. } else {
  8615. return hashPrefix;
  8616. }
  8617. };
  8618. /**
  8619. * @ngdoc property
  8620. * @name $locationProvider#html5Mode
  8621. * @description
  8622. * @param {boolean=} mode Use HTML5 strategy if available.
  8623. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8624. */
  8625. this.html5Mode = function(mode) {
  8626. if (isDefined(mode)) {
  8627. html5Mode = mode;
  8628. return this;
  8629. } else {
  8630. return html5Mode;
  8631. }
  8632. };
  8633. /**
  8634. * @ngdoc event
  8635. * @name $location#$locationChangeStart
  8636. * @eventType broadcast on root scope
  8637. * @description
  8638. * Broadcasted before a URL will change. This change can be prevented by calling
  8639. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8640. * details about event object. Upon successful change
  8641. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8642. *
  8643. * @param {Object} angularEvent Synthetic event object.
  8644. * @param {string} newUrl New URL
  8645. * @param {string=} oldUrl URL that was before it was changed.
  8646. */
  8647. /**
  8648. * @ngdoc event
  8649. * @name $location#$locationChangeSuccess
  8650. * @eventType broadcast on root scope
  8651. * @description
  8652. * Broadcasted after a URL was changed.
  8653. *
  8654. * @param {Object} angularEvent Synthetic event object.
  8655. * @param {string} newUrl New URL
  8656. * @param {string=} oldUrl URL that was before it was changed.
  8657. */
  8658. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8659. function( $rootScope, $browser, $sniffer, $rootElement) {
  8660. var $location,
  8661. LocationMode,
  8662. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8663. initialUrl = $browser.url(),
  8664. appBase;
  8665. if (html5Mode) {
  8666. appBase = serverBase(initialUrl) + (baseHref || '/');
  8667. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8668. } else {
  8669. appBase = stripHash(initialUrl);
  8670. LocationMode = LocationHashbangUrl;
  8671. }
  8672. $location = new LocationMode(appBase, '#' + hashPrefix);
  8673. $location.$$parse($location.$$rewrite(initialUrl));
  8674. $rootElement.on('click', function(event) {
  8675. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8676. // currently we open nice url link and redirect then
  8677. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8678. var elm = jqLite(event.target);
  8679. // traverse the DOM up to find first A tag
  8680. while (lowercase(elm[0].nodeName) !== 'a') {
  8681. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8682. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8683. }
  8684. var absHref = elm.prop('href');
  8685. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8686. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8687. // an animation.
  8688. absHref = urlResolve(absHref.animVal).href;
  8689. }
  8690. // Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9)
  8691. // The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or
  8692. // somewhere#anchor or http://example.com/somewhere
  8693. if (LocationMode === LocationHashbangInHtml5Url) {
  8694. // get the actual href attribute - see
  8695. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  8696. var href = elm.attr('href') || elm.attr('xlink:href');
  8697. if (href.indexOf('://') < 0) { // Ignore absolute URLs
  8698. var prefix = '#' + hashPrefix;
  8699. if (href[0] == '/') {
  8700. // absolute path - replace old path
  8701. absHref = appBase + prefix + href;
  8702. } else if (href[0] == '#') {
  8703. // local anchor
  8704. absHref = appBase + prefix + ($location.path() || '/') + href;
  8705. } else {
  8706. // relative path - join with current path
  8707. var stack = $location.path().split("/"),
  8708. parts = href.split("/");
  8709. for (var i=0; i<parts.length; i++) {
  8710. if (parts[i] == ".")
  8711. continue;
  8712. else if (parts[i] == "..")
  8713. stack.pop();
  8714. else if (parts[i].length)
  8715. stack.push(parts[i]);
  8716. }
  8717. absHref = appBase + prefix + stack.join('/');
  8718. }
  8719. }
  8720. }
  8721. var rewrittenUrl = $location.$$rewrite(absHref);
  8722. if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
  8723. event.preventDefault();
  8724. if (rewrittenUrl != $browser.url()) {
  8725. // update location manually
  8726. $location.$$parse(rewrittenUrl);
  8727. $rootScope.$apply();
  8728. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8729. window.angular['ff-684208-preventDefault'] = true;
  8730. }
  8731. }
  8732. });
  8733. // rewrite hashbang url <> html5 url
  8734. if ($location.absUrl() != initialUrl) {
  8735. $browser.url($location.absUrl(), true);
  8736. }
  8737. // update $location when $browser url changes
  8738. $browser.onUrlChange(function(newUrl) {
  8739. if ($location.absUrl() != newUrl) {
  8740. $rootScope.$evalAsync(function() {
  8741. var oldUrl = $location.absUrl();
  8742. $location.$$parse(newUrl);
  8743. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8744. oldUrl).defaultPrevented) {
  8745. $location.$$parse(oldUrl);
  8746. $browser.url(oldUrl);
  8747. } else {
  8748. afterLocationChange(oldUrl);
  8749. }
  8750. });
  8751. if (!$rootScope.$$phase) $rootScope.$digest();
  8752. }
  8753. });
  8754. // update browser
  8755. var changeCounter = 0;
  8756. $rootScope.$watch(function $locationWatch() {
  8757. var oldUrl = $browser.url();
  8758. var currentReplace = $location.$$replace;
  8759. if (!changeCounter || oldUrl != $location.absUrl()) {
  8760. changeCounter++;
  8761. $rootScope.$evalAsync(function() {
  8762. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8763. defaultPrevented) {
  8764. $location.$$parse(oldUrl);
  8765. } else {
  8766. $browser.url($location.absUrl(), currentReplace);
  8767. afterLocationChange(oldUrl);
  8768. }
  8769. });
  8770. }
  8771. $location.$$replace = false;
  8772. return changeCounter;
  8773. });
  8774. return $location;
  8775. function afterLocationChange(oldUrl) {
  8776. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8777. }
  8778. }];
  8779. }
  8780. /**
  8781. * @ngdoc service
  8782. * @name $log
  8783. * @requires $window
  8784. *
  8785. * @description
  8786. * Simple service for logging. Default implementation safely writes the message
  8787. * into the browser's console (if present).
  8788. *
  8789. * The main purpose of this service is to simplify debugging and troubleshooting.
  8790. *
  8791. * The default is to log `debug` messages. You can use
  8792. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8793. *
  8794. * @example
  8795. <example>
  8796. <file name="script.js">
  8797. function LogCtrl($scope, $log) {
  8798. $scope.$log = $log;
  8799. $scope.message = 'Hello World!';
  8800. }
  8801. </file>
  8802. <file name="index.html">
  8803. <div ng-controller="LogCtrl">
  8804. <p>Reload this page with open console, enter text and hit the log button...</p>
  8805. Message:
  8806. <input type="text" ng-model="message"/>
  8807. <button ng-click="$log.log(message)">log</button>
  8808. <button ng-click="$log.warn(message)">warn</button>
  8809. <button ng-click="$log.info(message)">info</button>
  8810. <button ng-click="$log.error(message)">error</button>
  8811. </div>
  8812. </file>
  8813. </example>
  8814. */
  8815. /**
  8816. * @ngdoc provider
  8817. * @name $logProvider
  8818. * @description
  8819. * Use the `$logProvider` to configure how the application logs messages
  8820. */
  8821. function $LogProvider(){
  8822. var debug = true,
  8823. self = this;
  8824. /**
  8825. * @ngdoc property
  8826. * @name $logProvider#debugEnabled
  8827. * @description
  8828. * @param {boolean=} flag enable or disable debug level messages
  8829. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8830. */
  8831. this.debugEnabled = function(flag) {
  8832. if (isDefined(flag)) {
  8833. debug = flag;
  8834. return this;
  8835. } else {
  8836. return debug;
  8837. }
  8838. };
  8839. this.$get = ['$window', function($window){
  8840. return {
  8841. /**
  8842. * @ngdoc method
  8843. * @name $log#log
  8844. *
  8845. * @description
  8846. * Write a log message
  8847. */
  8848. log: consoleLog('log'),
  8849. /**
  8850. * @ngdoc method
  8851. * @name $log#info
  8852. *
  8853. * @description
  8854. * Write an information message
  8855. */
  8856. info: consoleLog('info'),
  8857. /**
  8858. * @ngdoc method
  8859. * @name $log#warn
  8860. *
  8861. * @description
  8862. * Write a warning message
  8863. */
  8864. warn: consoleLog('warn'),
  8865. /**
  8866. * @ngdoc method
  8867. * @name $log#error
  8868. *
  8869. * @description
  8870. * Write an error message
  8871. */
  8872. error: consoleLog('error'),
  8873. /**
  8874. * @ngdoc method
  8875. * @name $log#debug
  8876. *
  8877. * @description
  8878. * Write a debug message
  8879. */
  8880. debug: (function () {
  8881. var fn = consoleLog('debug');
  8882. return function() {
  8883. if (debug) {
  8884. fn.apply(self, arguments);
  8885. }
  8886. };
  8887. }())
  8888. };
  8889. function formatError(arg) {
  8890. if (arg instanceof Error) {
  8891. if (arg.stack) {
  8892. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  8893. ? 'Error: ' + arg.message + '\n' + arg.stack
  8894. : arg.stack;
  8895. } else if (arg.sourceURL) {
  8896. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  8897. }
  8898. }
  8899. return arg;
  8900. }
  8901. function consoleLog(type) {
  8902. var console = $window.console || {},
  8903. logFn = console[type] || console.log || noop,
  8904. hasApply = false;
  8905. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  8906. // The reason behind this is that console.log has type "object" in IE8...
  8907. try {
  8908. hasApply = !!logFn.apply;
  8909. } catch (e) {}
  8910. if (hasApply) {
  8911. return function() {
  8912. var args = [];
  8913. forEach(arguments, function(arg) {
  8914. args.push(formatError(arg));
  8915. });
  8916. return logFn.apply(console, args);
  8917. };
  8918. }
  8919. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  8920. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  8921. return function(arg1, arg2) {
  8922. logFn(arg1, arg2 == null ? '' : arg2);
  8923. };
  8924. }
  8925. }];
  8926. }
  8927. var $parseMinErr = minErr('$parse');
  8928. var promiseWarningCache = {};
  8929. var promiseWarning;
  8930. // Sandboxing Angular Expressions
  8931. // ------------------------------
  8932. // Angular expressions are generally considered safe because these expressions only have direct
  8933. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  8934. // obtaining a reference to native JS functions such as the Function constructor.
  8935. //
  8936. // As an example, consider the following Angular expression:
  8937. //
  8938. // {}.toString.constructor(alert("evil JS code"))
  8939. //
  8940. // We want to prevent this type of access. For the sake of performance, during the lexing phase we
  8941. // disallow any "dotted" access to any member named "constructor".
  8942. //
  8943. // For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
  8944. // while evaluating the expression, which is a stronger but more expensive test. Since reflective
  8945. // calls are expensive anyway, this is not such a big deal compared to static dereferencing.
  8946. //
  8947. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  8948. // against the expression language, but not to prevent exploits that were enabled by exposing
  8949. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  8950. // practice and therefore we are not even trying to protect against interaction with an object
  8951. // explicitly exposed in this way.
  8952. //
  8953. // A developer could foil the name check by aliasing the Function constructor under a different
  8954. // name on the scope.
  8955. //
  8956. // In general, it is not possible to access a Window object from an angular expression unless a
  8957. // window or some DOM object that has a reference to window is published onto a Scope.
  8958. function ensureSafeMemberName(name, fullExpression) {
  8959. if (name === "constructor") {
  8960. throw $parseMinErr('isecfld',
  8961. 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
  8962. fullExpression);
  8963. }
  8964. return name;
  8965. }
  8966. function ensureSafeObject(obj, fullExpression) {
  8967. // nifty check if obj is Function that is fast and works across iframes and other contexts
  8968. if (obj) {
  8969. if (obj.constructor === obj) {
  8970. throw $parseMinErr('isecfn',
  8971. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  8972. fullExpression);
  8973. } else if (// isWindow(obj)
  8974. obj.document && obj.location && obj.alert && obj.setInterval) {
  8975. throw $parseMinErr('isecwindow',
  8976. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  8977. fullExpression);
  8978. } else if (// isElement(obj)
  8979. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  8980. throw $parseMinErr('isecdom',
  8981. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  8982. fullExpression);
  8983. }
  8984. }
  8985. return obj;
  8986. }
  8987. var OPERATORS = {
  8988. /* jshint bitwise : false */
  8989. 'null':function(){return null;},
  8990. 'true':function(){return true;},
  8991. 'false':function(){return false;},
  8992. undefined:noop,
  8993. '+':function(self, locals, a,b){
  8994. a=a(self, locals); b=b(self, locals);
  8995. if (isDefined(a)) {
  8996. if (isDefined(b)) {
  8997. return a + b;
  8998. }
  8999. return a;
  9000. }
  9001. return isDefined(b)?b:undefined;},
  9002. '-':function(self, locals, a,b){
  9003. a=a(self, locals); b=b(self, locals);
  9004. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  9005. },
  9006. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  9007. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  9008. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  9009. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  9010. '=':noop,
  9011. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  9012. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  9013. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  9014. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  9015. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  9016. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  9017. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  9018. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  9019. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  9020. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  9021. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  9022. // '|':function(self, locals, a,b){return a|b;},
  9023. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  9024. '!':function(self, locals, a){return !a(self, locals);}
  9025. };
  9026. /* jshint bitwise: true */
  9027. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  9028. /////////////////////////////////////////
  9029. /**
  9030. * @constructor
  9031. */
  9032. var Lexer = function (options) {
  9033. this.options = options;
  9034. };
  9035. Lexer.prototype = {
  9036. constructor: Lexer,
  9037. lex: function (text) {
  9038. this.text = text;
  9039. this.index = 0;
  9040. this.ch = undefined;
  9041. this.lastCh = ':'; // can start regexp
  9042. this.tokens = [];
  9043. while (this.index < this.text.length) {
  9044. this.ch = this.text.charAt(this.index);
  9045. if (this.is('"\'')) {
  9046. this.readString(this.ch);
  9047. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  9048. this.readNumber();
  9049. } else if (this.isIdent(this.ch)) {
  9050. this.readIdent();
  9051. } else if (this.is('(){}[].,;:?')) {
  9052. this.tokens.push({
  9053. index: this.index,
  9054. text: this.ch
  9055. });
  9056. this.index++;
  9057. } else if (this.isWhitespace(this.ch)) {
  9058. this.index++;
  9059. continue;
  9060. } else {
  9061. var ch2 = this.ch + this.peek();
  9062. var ch3 = ch2 + this.peek(2);
  9063. var fn = OPERATORS[this.ch];
  9064. var fn2 = OPERATORS[ch2];
  9065. var fn3 = OPERATORS[ch3];
  9066. if (fn3) {
  9067. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  9068. this.index += 3;
  9069. } else if (fn2) {
  9070. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  9071. this.index += 2;
  9072. } else if (fn) {
  9073. this.tokens.push({
  9074. index: this.index,
  9075. text: this.ch,
  9076. fn: fn
  9077. });
  9078. this.index += 1;
  9079. } else {
  9080. this.throwError('Unexpected next character ', this.index, this.index + 1);
  9081. }
  9082. }
  9083. this.lastCh = this.ch;
  9084. }
  9085. return this.tokens;
  9086. },
  9087. is: function(chars) {
  9088. return chars.indexOf(this.ch) !== -1;
  9089. },
  9090. was: function(chars) {
  9091. return chars.indexOf(this.lastCh) !== -1;
  9092. },
  9093. peek: function(i) {
  9094. var num = i || 1;
  9095. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  9096. },
  9097. isNumber: function(ch) {
  9098. return ('0' <= ch && ch <= '9');
  9099. },
  9100. isWhitespace: function(ch) {
  9101. // IE treats non-breaking space as \u00A0
  9102. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9103. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9104. },
  9105. isIdent: function(ch) {
  9106. return ('a' <= ch && ch <= 'z' ||
  9107. 'A' <= ch && ch <= 'Z' ||
  9108. '_' === ch || ch === '$');
  9109. },
  9110. isExpOperator: function(ch) {
  9111. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9112. },
  9113. throwError: function(error, start, end) {
  9114. end = end || this.index;
  9115. var colStr = (isDefined(start)
  9116. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9117. : ' ' + end);
  9118. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9119. error, colStr, this.text);
  9120. },
  9121. readNumber: function() {
  9122. var number = '';
  9123. var start = this.index;
  9124. while (this.index < this.text.length) {
  9125. var ch = lowercase(this.text.charAt(this.index));
  9126. if (ch == '.' || this.isNumber(ch)) {
  9127. number += ch;
  9128. } else {
  9129. var peekCh = this.peek();
  9130. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9131. number += ch;
  9132. } else if (this.isExpOperator(ch) &&
  9133. peekCh && this.isNumber(peekCh) &&
  9134. number.charAt(number.length - 1) == 'e') {
  9135. number += ch;
  9136. } else if (this.isExpOperator(ch) &&
  9137. (!peekCh || !this.isNumber(peekCh)) &&
  9138. number.charAt(number.length - 1) == 'e') {
  9139. this.throwError('Invalid exponent');
  9140. } else {
  9141. break;
  9142. }
  9143. }
  9144. this.index++;
  9145. }
  9146. number = 1 * number;
  9147. this.tokens.push({
  9148. index: start,
  9149. text: number,
  9150. literal: true,
  9151. constant: true,
  9152. fn: function() { return number; }
  9153. });
  9154. },
  9155. readIdent: function() {
  9156. var parser = this;
  9157. var ident = '';
  9158. var start = this.index;
  9159. var lastDot, peekIndex, methodName, ch;
  9160. while (this.index < this.text.length) {
  9161. ch = this.text.charAt(this.index);
  9162. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9163. if (ch === '.') lastDot = this.index;
  9164. ident += ch;
  9165. } else {
  9166. break;
  9167. }
  9168. this.index++;
  9169. }
  9170. //check if this is not a method invocation and if it is back out to last dot
  9171. if (lastDot) {
  9172. peekIndex = this.index;
  9173. while (peekIndex < this.text.length) {
  9174. ch = this.text.charAt(peekIndex);
  9175. if (ch === '(') {
  9176. methodName = ident.substr(lastDot - start + 1);
  9177. ident = ident.substr(0, lastDot - start);
  9178. this.index = peekIndex;
  9179. break;
  9180. }
  9181. if (this.isWhitespace(ch)) {
  9182. peekIndex++;
  9183. } else {
  9184. break;
  9185. }
  9186. }
  9187. }
  9188. var token = {
  9189. index: start,
  9190. text: ident
  9191. };
  9192. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9193. if (OPERATORS.hasOwnProperty(ident)) {
  9194. token.fn = OPERATORS[ident];
  9195. token.literal = true;
  9196. token.constant = true;
  9197. } else {
  9198. var getter = getterFn(ident, this.options, this.text);
  9199. token.fn = extend(function(self, locals) {
  9200. return (getter(self, locals));
  9201. }, {
  9202. assign: function(self, value) {
  9203. return setter(self, ident, value, parser.text, parser.options);
  9204. }
  9205. });
  9206. }
  9207. this.tokens.push(token);
  9208. if (methodName) {
  9209. this.tokens.push({
  9210. index:lastDot,
  9211. text: '.'
  9212. });
  9213. this.tokens.push({
  9214. index: lastDot + 1,
  9215. text: methodName
  9216. });
  9217. }
  9218. },
  9219. readString: function(quote) {
  9220. var start = this.index;
  9221. this.index++;
  9222. var string = '';
  9223. var rawString = quote;
  9224. var escape = false;
  9225. while (this.index < this.text.length) {
  9226. var ch = this.text.charAt(this.index);
  9227. rawString += ch;
  9228. if (escape) {
  9229. if (ch === 'u') {
  9230. var hex = this.text.substring(this.index + 1, this.index + 5);
  9231. if (!hex.match(/[\da-f]{4}/i))
  9232. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9233. this.index += 4;
  9234. string += String.fromCharCode(parseInt(hex, 16));
  9235. } else {
  9236. var rep = ESCAPE[ch];
  9237. if (rep) {
  9238. string += rep;
  9239. } else {
  9240. string += ch;
  9241. }
  9242. }
  9243. escape = false;
  9244. } else if (ch === '\\') {
  9245. escape = true;
  9246. } else if (ch === quote) {
  9247. this.index++;
  9248. this.tokens.push({
  9249. index: start,
  9250. text: rawString,
  9251. string: string,
  9252. literal: true,
  9253. constant: true,
  9254. fn: function() { return string; }
  9255. });
  9256. return;
  9257. } else {
  9258. string += ch;
  9259. }
  9260. this.index++;
  9261. }
  9262. this.throwError('Unterminated quote', start);
  9263. }
  9264. };
  9265. /**
  9266. * @constructor
  9267. */
  9268. var Parser = function (lexer, $filter, options) {
  9269. this.lexer = lexer;
  9270. this.$filter = $filter;
  9271. this.options = options;
  9272. };
  9273. Parser.ZERO = extend(function () {
  9274. return 0;
  9275. }, {
  9276. constant: true
  9277. });
  9278. Parser.prototype = {
  9279. constructor: Parser,
  9280. parse: function (text) {
  9281. this.text = text;
  9282. this.tokens = this.lexer.lex(text);
  9283. var value = this.statements();
  9284. if (this.tokens.length !== 0) {
  9285. this.throwError('is an unexpected token', this.tokens[0]);
  9286. }
  9287. value.literal = !!value.literal;
  9288. value.constant = !!value.constant;
  9289. return value;
  9290. },
  9291. primary: function () {
  9292. var primary;
  9293. if (this.expect('(')) {
  9294. primary = this.filterChain();
  9295. this.consume(')');
  9296. } else if (this.expect('[')) {
  9297. primary = this.arrayDeclaration();
  9298. } else if (this.expect('{')) {
  9299. primary = this.object();
  9300. } else {
  9301. var token = this.expect();
  9302. primary = token.fn;
  9303. if (!primary) {
  9304. this.throwError('not a primary expression', token);
  9305. }
  9306. primary.literal = !!token.literal;
  9307. primary.constant = !!token.constant;
  9308. }
  9309. var next, context;
  9310. while ((next = this.expect('(', '[', '.'))) {
  9311. if (next.text === '(') {
  9312. primary = this.functionCall(primary, context);
  9313. context = null;
  9314. } else if (next.text === '[') {
  9315. context = primary;
  9316. primary = this.objectIndex(primary);
  9317. } else if (next.text === '.') {
  9318. context = primary;
  9319. primary = this.fieldAccess(primary);
  9320. } else {
  9321. this.throwError('IMPOSSIBLE');
  9322. }
  9323. }
  9324. return primary;
  9325. },
  9326. throwError: function(msg, token) {
  9327. throw $parseMinErr('syntax',
  9328. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9329. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9330. },
  9331. peekToken: function() {
  9332. if (this.tokens.length === 0)
  9333. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9334. return this.tokens[0];
  9335. },
  9336. peek: function(e1, e2, e3, e4) {
  9337. if (this.tokens.length > 0) {
  9338. var token = this.tokens[0];
  9339. var t = token.text;
  9340. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9341. (!e1 && !e2 && !e3 && !e4)) {
  9342. return token;
  9343. }
  9344. }
  9345. return false;
  9346. },
  9347. expect: function(e1, e2, e3, e4){
  9348. var token = this.peek(e1, e2, e3, e4);
  9349. if (token) {
  9350. this.tokens.shift();
  9351. return token;
  9352. }
  9353. return false;
  9354. },
  9355. consume: function(e1){
  9356. if (!this.expect(e1)) {
  9357. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9358. }
  9359. },
  9360. unaryFn: function(fn, right) {
  9361. return extend(function(self, locals) {
  9362. return fn(self, locals, right);
  9363. }, {
  9364. constant:right.constant
  9365. });
  9366. },
  9367. ternaryFn: function(left, middle, right){
  9368. return extend(function(self, locals){
  9369. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9370. }, {
  9371. constant: left.constant && middle.constant && right.constant
  9372. });
  9373. },
  9374. binaryFn: function(left, fn, right) {
  9375. return extend(function(self, locals) {
  9376. return fn(self, locals, left, right);
  9377. }, {
  9378. constant:left.constant && right.constant
  9379. });
  9380. },
  9381. statements: function() {
  9382. var statements = [];
  9383. while (true) {
  9384. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9385. statements.push(this.filterChain());
  9386. if (!this.expect(';')) {
  9387. // optimize for the common case where there is only one statement.
  9388. // TODO(size): maybe we should not support multiple statements?
  9389. return (statements.length === 1)
  9390. ? statements[0]
  9391. : function(self, locals) {
  9392. var value;
  9393. for (var i = 0; i < statements.length; i++) {
  9394. var statement = statements[i];
  9395. if (statement) {
  9396. value = statement(self, locals);
  9397. }
  9398. }
  9399. return value;
  9400. };
  9401. }
  9402. }
  9403. },
  9404. filterChain: function() {
  9405. var left = this.expression();
  9406. var token;
  9407. while (true) {
  9408. if ((token = this.expect('|'))) {
  9409. left = this.binaryFn(left, token.fn, this.filter());
  9410. } else {
  9411. return left;
  9412. }
  9413. }
  9414. },
  9415. filter: function() {
  9416. var token = this.expect();
  9417. var fn = this.$filter(token.text);
  9418. var argsFn = [];
  9419. while (true) {
  9420. if ((token = this.expect(':'))) {
  9421. argsFn.push(this.expression());
  9422. } else {
  9423. var fnInvoke = function(self, locals, input) {
  9424. var args = [input];
  9425. for (var i = 0; i < argsFn.length; i++) {
  9426. args.push(argsFn[i](self, locals));
  9427. }
  9428. return fn.apply(self, args);
  9429. };
  9430. return function() {
  9431. return fnInvoke;
  9432. };
  9433. }
  9434. }
  9435. },
  9436. expression: function() {
  9437. return this.assignment();
  9438. },
  9439. assignment: function() {
  9440. var left = this.ternary();
  9441. var right;
  9442. var token;
  9443. if ((token = this.expect('='))) {
  9444. if (!left.assign) {
  9445. this.throwError('implies assignment but [' +
  9446. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9447. }
  9448. right = this.ternary();
  9449. return function(scope, locals) {
  9450. return left.assign(scope, right(scope, locals), locals);
  9451. };
  9452. }
  9453. return left;
  9454. },
  9455. ternary: function() {
  9456. var left = this.logicalOR();
  9457. var middle;
  9458. var token;
  9459. if ((token = this.expect('?'))) {
  9460. middle = this.ternary();
  9461. if ((token = this.expect(':'))) {
  9462. return this.ternaryFn(left, middle, this.ternary());
  9463. } else {
  9464. this.throwError('expected :', token);
  9465. }
  9466. } else {
  9467. return left;
  9468. }
  9469. },
  9470. logicalOR: function() {
  9471. var left = this.logicalAND();
  9472. var token;
  9473. while (true) {
  9474. if ((token = this.expect('||'))) {
  9475. left = this.binaryFn(left, token.fn, this.logicalAND());
  9476. } else {
  9477. return left;
  9478. }
  9479. }
  9480. },
  9481. logicalAND: function() {
  9482. var left = this.equality();
  9483. var token;
  9484. if ((token = this.expect('&&'))) {
  9485. left = this.binaryFn(left, token.fn, this.logicalAND());
  9486. }
  9487. return left;
  9488. },
  9489. equality: function() {
  9490. var left = this.relational();
  9491. var token;
  9492. if ((token = this.expect('==','!=','===','!=='))) {
  9493. left = this.binaryFn(left, token.fn, this.equality());
  9494. }
  9495. return left;
  9496. },
  9497. relational: function() {
  9498. var left = this.additive();
  9499. var token;
  9500. if ((token = this.expect('<', '>', '<=', '>='))) {
  9501. left = this.binaryFn(left, token.fn, this.relational());
  9502. }
  9503. return left;
  9504. },
  9505. additive: function() {
  9506. var left = this.multiplicative();
  9507. var token;
  9508. while ((token = this.expect('+','-'))) {
  9509. left = this.binaryFn(left, token.fn, this.multiplicative());
  9510. }
  9511. return left;
  9512. },
  9513. multiplicative: function() {
  9514. var left = this.unary();
  9515. var token;
  9516. while ((token = this.expect('*','/','%'))) {
  9517. left = this.binaryFn(left, token.fn, this.unary());
  9518. }
  9519. return left;
  9520. },
  9521. unary: function() {
  9522. var token;
  9523. if (this.expect('+')) {
  9524. return this.primary();
  9525. } else if ((token = this.expect('-'))) {
  9526. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9527. } else if ((token = this.expect('!'))) {
  9528. return this.unaryFn(token.fn, this.unary());
  9529. } else {
  9530. return this.primary();
  9531. }
  9532. },
  9533. fieldAccess: function(object) {
  9534. var parser = this;
  9535. var field = this.expect().text;
  9536. var getter = getterFn(field, this.options, this.text);
  9537. return extend(function(scope, locals, self) {
  9538. return getter(self || object(scope, locals));
  9539. }, {
  9540. assign: function(scope, value, locals) {
  9541. return setter(object(scope, locals), field, value, parser.text, parser.options);
  9542. }
  9543. });
  9544. },
  9545. objectIndex: function(obj) {
  9546. var parser = this;
  9547. var indexFn = this.expression();
  9548. this.consume(']');
  9549. return extend(function(self, locals) {
  9550. var o = obj(self, locals),
  9551. i = indexFn(self, locals),
  9552. v, p;
  9553. if (!o) return undefined;
  9554. v = ensureSafeObject(o[i], parser.text);
  9555. if (v && v.then && parser.options.unwrapPromises) {
  9556. p = v;
  9557. if (!('$$v' in v)) {
  9558. p.$$v = undefined;
  9559. p.then(function(val) { p.$$v = val; });
  9560. }
  9561. v = v.$$v;
  9562. }
  9563. return v;
  9564. }, {
  9565. assign: function(self, value, locals) {
  9566. var key = indexFn(self, locals);
  9567. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9568. var safe = ensureSafeObject(obj(self, locals), parser.text);
  9569. return safe[key] = value;
  9570. }
  9571. });
  9572. },
  9573. functionCall: function(fn, contextGetter) {
  9574. var argsFn = [];
  9575. if (this.peekToken().text !== ')') {
  9576. do {
  9577. argsFn.push(this.expression());
  9578. } while (this.expect(','));
  9579. }
  9580. this.consume(')');
  9581. var parser = this;
  9582. return function(scope, locals) {
  9583. var args = [];
  9584. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9585. for (var i = 0; i < argsFn.length; i++) {
  9586. args.push(argsFn[i](scope, locals));
  9587. }
  9588. var fnPtr = fn(scope, locals, context) || noop;
  9589. ensureSafeObject(context, parser.text);
  9590. ensureSafeObject(fnPtr, parser.text);
  9591. // IE stupidity! (IE doesn't have apply for some native functions)
  9592. var v = fnPtr.apply
  9593. ? fnPtr.apply(context, args)
  9594. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9595. return ensureSafeObject(v, parser.text);
  9596. };
  9597. },
  9598. // This is used with json array declaration
  9599. arrayDeclaration: function () {
  9600. var elementFns = [];
  9601. var allConstant = true;
  9602. if (this.peekToken().text !== ']') {
  9603. do {
  9604. if (this.peek(']')) {
  9605. // Support trailing commas per ES5.1.
  9606. break;
  9607. }
  9608. var elementFn = this.expression();
  9609. elementFns.push(elementFn);
  9610. if (!elementFn.constant) {
  9611. allConstant = false;
  9612. }
  9613. } while (this.expect(','));
  9614. }
  9615. this.consume(']');
  9616. return extend(function(self, locals) {
  9617. var array = [];
  9618. for (var i = 0; i < elementFns.length; i++) {
  9619. array.push(elementFns[i](self, locals));
  9620. }
  9621. return array;
  9622. }, {
  9623. literal: true,
  9624. constant: allConstant
  9625. });
  9626. },
  9627. object: function () {
  9628. var keyValues = [];
  9629. var allConstant = true;
  9630. if (this.peekToken().text !== '}') {
  9631. do {
  9632. if (this.peek('}')) {
  9633. // Support trailing commas per ES5.1.
  9634. break;
  9635. }
  9636. var token = this.expect(),
  9637. key = token.string || token.text;
  9638. this.consume(':');
  9639. var value = this.expression();
  9640. keyValues.push({key: key, value: value});
  9641. if (!value.constant) {
  9642. allConstant = false;
  9643. }
  9644. } while (this.expect(','));
  9645. }
  9646. this.consume('}');
  9647. return extend(function(self, locals) {
  9648. var object = {};
  9649. for (var i = 0; i < keyValues.length; i++) {
  9650. var keyValue = keyValues[i];
  9651. object[keyValue.key] = keyValue.value(self, locals);
  9652. }
  9653. return object;
  9654. }, {
  9655. literal: true,
  9656. constant: allConstant
  9657. });
  9658. }
  9659. };
  9660. //////////////////////////////////////////////////
  9661. // Parser helper functions
  9662. //////////////////////////////////////////////////
  9663. function setter(obj, path, setValue, fullExp, options) {
  9664. //needed?
  9665. options = options || {};
  9666. var element = path.split('.'), key;
  9667. for (var i = 0; element.length > 1; i++) {
  9668. key = ensureSafeMemberName(element.shift(), fullExp);
  9669. var propertyObj = obj[key];
  9670. if (!propertyObj) {
  9671. propertyObj = {};
  9672. obj[key] = propertyObj;
  9673. }
  9674. obj = propertyObj;
  9675. if (obj.then && options.unwrapPromises) {
  9676. promiseWarning(fullExp);
  9677. if (!("$$v" in obj)) {
  9678. (function(promise) {
  9679. promise.then(function(val) { promise.$$v = val; }); }
  9680. )(obj);
  9681. }
  9682. if (obj.$$v === undefined) {
  9683. obj.$$v = {};
  9684. }
  9685. obj = obj.$$v;
  9686. }
  9687. }
  9688. key = ensureSafeMemberName(element.shift(), fullExp);
  9689. obj[key] = setValue;
  9690. return setValue;
  9691. }
  9692. var getterFnCache = {};
  9693. /**
  9694. * Implementation of the "Black Hole" variant from:
  9695. * - http://jsperf.com/angularjs-parse-getter/4
  9696. * - http://jsperf.com/path-evaluation-simplified/7
  9697. */
  9698. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9699. ensureSafeMemberName(key0, fullExp);
  9700. ensureSafeMemberName(key1, fullExp);
  9701. ensureSafeMemberName(key2, fullExp);
  9702. ensureSafeMemberName(key3, fullExp);
  9703. ensureSafeMemberName(key4, fullExp);
  9704. return !options.unwrapPromises
  9705. ? function cspSafeGetter(scope, locals) {
  9706. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9707. if (pathVal == null) return pathVal;
  9708. pathVal = pathVal[key0];
  9709. if (!key1) return pathVal;
  9710. if (pathVal == null) return undefined;
  9711. pathVal = pathVal[key1];
  9712. if (!key2) return pathVal;
  9713. if (pathVal == null) return undefined;
  9714. pathVal = pathVal[key2];
  9715. if (!key3) return pathVal;
  9716. if (pathVal == null) return undefined;
  9717. pathVal = pathVal[key3];
  9718. if (!key4) return pathVal;
  9719. if (pathVal == null) return undefined;
  9720. pathVal = pathVal[key4];
  9721. return pathVal;
  9722. }
  9723. : function cspSafePromiseEnabledGetter(scope, locals) {
  9724. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9725. promise;
  9726. if (pathVal == null) return pathVal;
  9727. pathVal = pathVal[key0];
  9728. if (pathVal && pathVal.then) {
  9729. promiseWarning(fullExp);
  9730. if (!("$$v" in pathVal)) {
  9731. promise = pathVal;
  9732. promise.$$v = undefined;
  9733. promise.then(function(val) { promise.$$v = val; });
  9734. }
  9735. pathVal = pathVal.$$v;
  9736. }
  9737. if (!key1) return pathVal;
  9738. if (pathVal == null) return undefined;
  9739. pathVal = pathVal[key1];
  9740. if (pathVal && pathVal.then) {
  9741. promiseWarning(fullExp);
  9742. if (!("$$v" in pathVal)) {
  9743. promise = pathVal;
  9744. promise.$$v = undefined;
  9745. promise.then(function(val) { promise.$$v = val; });
  9746. }
  9747. pathVal = pathVal.$$v;
  9748. }
  9749. if (!key2) return pathVal;
  9750. if (pathVal == null) return undefined;
  9751. pathVal = pathVal[key2];
  9752. if (pathVal && pathVal.then) {
  9753. promiseWarning(fullExp);
  9754. if (!("$$v" in pathVal)) {
  9755. promise = pathVal;
  9756. promise.$$v = undefined;
  9757. promise.then(function(val) { promise.$$v = val; });
  9758. }
  9759. pathVal = pathVal.$$v;
  9760. }
  9761. if (!key3) return pathVal;
  9762. if (pathVal == null) return undefined;
  9763. pathVal = pathVal[key3];
  9764. if (pathVal && pathVal.then) {
  9765. promiseWarning(fullExp);
  9766. if (!("$$v" in pathVal)) {
  9767. promise = pathVal;
  9768. promise.$$v = undefined;
  9769. promise.then(function(val) { promise.$$v = val; });
  9770. }
  9771. pathVal = pathVal.$$v;
  9772. }
  9773. if (!key4) return pathVal;
  9774. if (pathVal == null) return undefined;
  9775. pathVal = pathVal[key4];
  9776. if (pathVal && pathVal.then) {
  9777. promiseWarning(fullExp);
  9778. if (!("$$v" in pathVal)) {
  9779. promise = pathVal;
  9780. promise.$$v = undefined;
  9781. promise.then(function(val) { promise.$$v = val; });
  9782. }
  9783. pathVal = pathVal.$$v;
  9784. }
  9785. return pathVal;
  9786. };
  9787. }
  9788. function simpleGetterFn1(key0, fullExp) {
  9789. ensureSafeMemberName(key0, fullExp);
  9790. return function simpleGetterFn1(scope, locals) {
  9791. if (scope == null) return undefined;
  9792. return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9793. };
  9794. }
  9795. function simpleGetterFn2(key0, key1, fullExp) {
  9796. ensureSafeMemberName(key0, fullExp);
  9797. ensureSafeMemberName(key1, fullExp);
  9798. return function simpleGetterFn2(scope, locals) {
  9799. if (scope == null) return undefined;
  9800. scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9801. return scope == null ? undefined : scope[key1];
  9802. };
  9803. }
  9804. function getterFn(path, options, fullExp) {
  9805. // Check whether the cache has this getter already.
  9806. // We can use hasOwnProperty directly on the cache because we ensure,
  9807. // see below, that the cache never stores a path called 'hasOwnProperty'
  9808. if (getterFnCache.hasOwnProperty(path)) {
  9809. return getterFnCache[path];
  9810. }
  9811. var pathKeys = path.split('.'),
  9812. pathKeysLength = pathKeys.length,
  9813. fn;
  9814. // When we have only 1 or 2 tokens, use optimized special case closures.
  9815. // http://jsperf.com/angularjs-parse-getter/6
  9816. if (!options.unwrapPromises && pathKeysLength === 1) {
  9817. fn = simpleGetterFn1(pathKeys[0], fullExp);
  9818. } else if (!options.unwrapPromises && pathKeysLength === 2) {
  9819. fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
  9820. } else if (options.csp) {
  9821. if (pathKeysLength < 6) {
  9822. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  9823. options);
  9824. } else {
  9825. fn = function(scope, locals) {
  9826. var i = 0, val;
  9827. do {
  9828. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  9829. pathKeys[i++], fullExp, options)(scope, locals);
  9830. locals = undefined; // clear after first iteration
  9831. scope = val;
  9832. } while (i < pathKeysLength);
  9833. return val;
  9834. };
  9835. }
  9836. } else {
  9837. var code = 'var p;\n';
  9838. forEach(pathKeys, function(key, index) {
  9839. ensureSafeMemberName(key, fullExp);
  9840. code += 'if(s == null) return undefined;\n' +
  9841. 's='+ (index
  9842. // we simply dereference 's' on any .dot notation
  9843. ? 's'
  9844. // but if we are first then we check locals first, and if so read it first
  9845. : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
  9846. (options.unwrapPromises
  9847. ? 'if (s && s.then) {\n' +
  9848. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  9849. ' if (!("$$v" in s)) {\n' +
  9850. ' p=s;\n' +
  9851. ' p.$$v = undefined;\n' +
  9852. ' p.then(function(v) {p.$$v=v;});\n' +
  9853. '}\n' +
  9854. ' s=s.$$v\n' +
  9855. '}\n'
  9856. : '');
  9857. });
  9858. code += 'return s;';
  9859. /* jshint -W054 */
  9860. var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
  9861. /* jshint +W054 */
  9862. evaledFnGetter.toString = valueFn(code);
  9863. fn = options.unwrapPromises ? function(scope, locals) {
  9864. return evaledFnGetter(scope, locals, promiseWarning);
  9865. } : evaledFnGetter;
  9866. }
  9867. // Only cache the value if it's not going to mess up the cache object
  9868. // This is more performant that using Object.prototype.hasOwnProperty.call
  9869. if (path !== 'hasOwnProperty') {
  9870. getterFnCache[path] = fn;
  9871. }
  9872. return fn;
  9873. }
  9874. ///////////////////////////////////
  9875. /**
  9876. * @ngdoc service
  9877. * @name $parse
  9878. * @kind function
  9879. *
  9880. * @description
  9881. *
  9882. * Converts Angular {@link guide/expression expression} into a function.
  9883. *
  9884. * ```js
  9885. * var getter = $parse('user.name');
  9886. * var setter = getter.assign;
  9887. * var context = {user:{name:'angular'}};
  9888. * var locals = {user:{name:'local'}};
  9889. *
  9890. * expect(getter(context)).toEqual('angular');
  9891. * setter(context, 'newValue');
  9892. * expect(context.user.name).toEqual('newValue');
  9893. * expect(getter(context, locals)).toEqual('local');
  9894. * ```
  9895. *
  9896. *
  9897. * @param {string} expression String expression to compile.
  9898. * @returns {function(context, locals)} a function which represents the compiled expression:
  9899. *
  9900. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  9901. * are evaluated against (typically a scope object).
  9902. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  9903. * `context`.
  9904. *
  9905. * The returned function also has the following properties:
  9906. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  9907. * literal.
  9908. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  9909. * constant literals.
  9910. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  9911. * set to a function to change its value on the given context.
  9912. *
  9913. */
  9914. /**
  9915. * @ngdoc provider
  9916. * @name $parseProvider
  9917. * @kind function
  9918. *
  9919. * @description
  9920. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  9921. * service.
  9922. */
  9923. function $ParseProvider() {
  9924. var cache = {};
  9925. var $parseOptions = {
  9926. csp: false,
  9927. unwrapPromises: false,
  9928. logPromiseWarnings: true
  9929. };
  9930. /**
  9931. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9932. *
  9933. * @ngdoc method
  9934. * @name $parseProvider#unwrapPromises
  9935. * @description
  9936. *
  9937. * **This feature is deprecated, see deprecation notes below for more info**
  9938. *
  9939. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  9940. * found at any part of the expression. In other words, if set to true, the expression will always
  9941. * result in a non-promise value.
  9942. *
  9943. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  9944. * the fulfillment value is used in place of the promise while evaluating the expression.
  9945. *
  9946. * **Deprecation notice**
  9947. *
  9948. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  9949. * dichotomy between data access in templates (accessed as raw values) and controller code
  9950. * (accessed as promises).
  9951. *
  9952. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  9953. * the model access there.
  9954. *
  9955. * Other downsides of automatic promise unwrapping:
  9956. *
  9957. * - when building components it's often desirable to receive the raw promises
  9958. * - adds complexity and slows down expression evaluation
  9959. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  9960. * generated
  9961. * - makes IDE auto-completion and tool support hard
  9962. *
  9963. * **Warning Logs**
  9964. *
  9965. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  9966. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  9967. * `$parseProvider.logPromiseWarnings(false)` api.
  9968. *
  9969. *
  9970. * @param {boolean=} value New value.
  9971. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9972. * setter.
  9973. */
  9974. this.unwrapPromises = function(value) {
  9975. if (isDefined(value)) {
  9976. $parseOptions.unwrapPromises = !!value;
  9977. return this;
  9978. } else {
  9979. return $parseOptions.unwrapPromises;
  9980. }
  9981. };
  9982. /**
  9983. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9984. *
  9985. * @ngdoc method
  9986. * @name $parseProvider#logPromiseWarnings
  9987. * @description
  9988. *
  9989. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  9990. *
  9991. * The default is set to `true`.
  9992. *
  9993. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  9994. *
  9995. * @param {boolean=} value New value.
  9996. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9997. * setter.
  9998. */
  9999. this.logPromiseWarnings = function(value) {
  10000. if (isDefined(value)) {
  10001. $parseOptions.logPromiseWarnings = value;
  10002. return this;
  10003. } else {
  10004. return $parseOptions.logPromiseWarnings;
  10005. }
  10006. };
  10007. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  10008. $parseOptions.csp = $sniffer.csp;
  10009. promiseWarning = function promiseWarningFn(fullExp) {
  10010. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  10011. promiseWarningCache[fullExp] = true;
  10012. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  10013. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  10014. };
  10015. return function(exp) {
  10016. var parsedExpression;
  10017. switch (typeof exp) {
  10018. case 'string':
  10019. if (cache.hasOwnProperty(exp)) {
  10020. return cache[exp];
  10021. }
  10022. var lexer = new Lexer($parseOptions);
  10023. var parser = new Parser(lexer, $filter, $parseOptions);
  10024. parsedExpression = parser.parse(exp);
  10025. if (exp !== 'hasOwnProperty') {
  10026. // Only cache the value if it's not going to mess up the cache object
  10027. // This is more performant that using Object.prototype.hasOwnProperty.call
  10028. cache[exp] = parsedExpression;
  10029. }
  10030. return parsedExpression;
  10031. case 'function':
  10032. return exp;
  10033. default:
  10034. return noop;
  10035. }
  10036. };
  10037. }];
  10038. }
  10039. /**
  10040. * @ngdoc service
  10041. * @name $q
  10042. * @requires $rootScope
  10043. *
  10044. * @description
  10045. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  10046. *
  10047. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  10048. * interface for interacting with an object that represents the result of an action that is
  10049. * performed asynchronously, and may or may not be finished at any given point in time.
  10050. *
  10051. * From the perspective of dealing with error handling, deferred and promise APIs are to
  10052. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  10053. *
  10054. * ```js
  10055. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  10056. * // are available in the current lexical scope (they could have been injected or passed in).
  10057. *
  10058. * function asyncGreet(name) {
  10059. * var deferred = $q.defer();
  10060. *
  10061. * setTimeout(function() {
  10062. * // since this fn executes async in a future turn of the event loop, we need to wrap
  10063. * // our code into an $apply call so that the model changes are properly observed.
  10064. * scope.$apply(function() {
  10065. * deferred.notify('About to greet ' + name + '.');
  10066. *
  10067. * if (okToGreet(name)) {
  10068. * deferred.resolve('Hello, ' + name + '!');
  10069. * } else {
  10070. * deferred.reject('Greeting ' + name + ' is not allowed.');
  10071. * }
  10072. * });
  10073. * }, 1000);
  10074. *
  10075. * return deferred.promise;
  10076. * }
  10077. *
  10078. * var promise = asyncGreet('Robin Hood');
  10079. * promise.then(function(greeting) {
  10080. * alert('Success: ' + greeting);
  10081. * }, function(reason) {
  10082. * alert('Failed: ' + reason);
  10083. * }, function(update) {
  10084. * alert('Got notification: ' + update);
  10085. * });
  10086. * ```
  10087. *
  10088. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10089. * comes in the way of guarantees that promise and deferred APIs make, see
  10090. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10091. *
  10092. * Additionally the promise api allows for composition that is very hard to do with the
  10093. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10094. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10095. * section on serial or parallel joining of promises.
  10096. *
  10097. *
  10098. * # The Deferred API
  10099. *
  10100. * A new instance of deferred is constructed by calling `$q.defer()`.
  10101. *
  10102. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10103. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10104. * of the task.
  10105. *
  10106. * **Methods**
  10107. *
  10108. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10109. * constructed via `$q.reject`, the promise will be rejected instead.
  10110. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10111. * resolving it with a rejection constructed via `$q.reject`.
  10112. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10113. * multiple times before the promise is either resolved or rejected.
  10114. *
  10115. * **Properties**
  10116. *
  10117. * - promise – `{Promise}` – promise object associated with this deferred.
  10118. *
  10119. *
  10120. * # The Promise API
  10121. *
  10122. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10123. * calling `deferred.promise`.
  10124. *
  10125. * The purpose of the promise object is to allow for interested parties to get access to the result
  10126. * of the deferred task when it completes.
  10127. *
  10128. * **Methods**
  10129. *
  10130. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10131. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10132. * as soon as the result is available. The callbacks are called with a single argument: the result
  10133. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10134. * provide a progress indication, before the promise is resolved or rejected.
  10135. *
  10136. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10137. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10138. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10139. * method.
  10140. *
  10141. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10142. *
  10143. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10144. * but to do so without modifying the final value. This is useful to release resources or do some
  10145. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10146. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10147. * more information.
  10148. *
  10149. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10150. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10151. * make your code IE8 and Android 2.x compatible.
  10152. *
  10153. * # Chaining promises
  10154. *
  10155. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10156. * possible to create a chain of promises:
  10157. *
  10158. * ```js
  10159. * promiseB = promiseA.then(function(result) {
  10160. * return result + 1;
  10161. * });
  10162. *
  10163. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10164. * // will be the result of promiseA incremented by 1
  10165. * ```
  10166. *
  10167. * It is possible to create chains of any length and since a promise can be resolved with another
  10168. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10169. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10170. * $http's response interceptors.
  10171. *
  10172. *
  10173. * # Differences between Kris Kowal's Q and $q
  10174. *
  10175. * There are two main differences:
  10176. *
  10177. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10178. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10179. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10180. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10181. * all the important functionality needed for common async tasks.
  10182. *
  10183. * # Testing
  10184. *
  10185. * ```js
  10186. * it('should simulate promise', inject(function($q, $rootScope) {
  10187. * var deferred = $q.defer();
  10188. * var promise = deferred.promise;
  10189. * var resolvedValue;
  10190. *
  10191. * promise.then(function(value) { resolvedValue = value; });
  10192. * expect(resolvedValue).toBeUndefined();
  10193. *
  10194. * // Simulate resolving of promise
  10195. * deferred.resolve(123);
  10196. * // Note that the 'then' function does not get called synchronously.
  10197. * // This is because we want the promise API to always be async, whether or not
  10198. * // it got called synchronously or asynchronously.
  10199. * expect(resolvedValue).toBeUndefined();
  10200. *
  10201. * // Propagate promise resolution to 'then' functions using $apply().
  10202. * $rootScope.$apply();
  10203. * expect(resolvedValue).toEqual(123);
  10204. * }));
  10205. * ```
  10206. */
  10207. function $QProvider() {
  10208. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10209. return qFactory(function(callback) {
  10210. $rootScope.$evalAsync(callback);
  10211. }, $exceptionHandler);
  10212. }];
  10213. }
  10214. /**
  10215. * Constructs a promise manager.
  10216. *
  10217. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10218. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10219. * debugging purposes.
  10220. * @returns {object} Promise manager.
  10221. */
  10222. function qFactory(nextTick, exceptionHandler) {
  10223. /**
  10224. * @ngdoc method
  10225. * @name $q#defer
  10226. * @kind function
  10227. *
  10228. * @description
  10229. * Creates a `Deferred` object which represents a task which will finish in the future.
  10230. *
  10231. * @returns {Deferred} Returns a new instance of deferred.
  10232. */
  10233. var defer = function() {
  10234. var pending = [],
  10235. value, deferred;
  10236. deferred = {
  10237. resolve: function(val) {
  10238. if (pending) {
  10239. var callbacks = pending;
  10240. pending = undefined;
  10241. value = ref(val);
  10242. if (callbacks.length) {
  10243. nextTick(function() {
  10244. var callback;
  10245. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10246. callback = callbacks[i];
  10247. value.then(callback[0], callback[1], callback[2]);
  10248. }
  10249. });
  10250. }
  10251. }
  10252. },
  10253. reject: function(reason) {
  10254. deferred.resolve(createInternalRejectedPromise(reason));
  10255. },
  10256. notify: function(progress) {
  10257. if (pending) {
  10258. var callbacks = pending;
  10259. if (pending.length) {
  10260. nextTick(function() {
  10261. var callback;
  10262. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10263. callback = callbacks[i];
  10264. callback[2](progress);
  10265. }
  10266. });
  10267. }
  10268. }
  10269. },
  10270. promise: {
  10271. then: function(callback, errback, progressback) {
  10272. var result = defer();
  10273. var wrappedCallback = function(value) {
  10274. try {
  10275. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10276. } catch(e) {
  10277. result.reject(e);
  10278. exceptionHandler(e);
  10279. }
  10280. };
  10281. var wrappedErrback = function(reason) {
  10282. try {
  10283. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10284. } catch(e) {
  10285. result.reject(e);
  10286. exceptionHandler(e);
  10287. }
  10288. };
  10289. var wrappedProgressback = function(progress) {
  10290. try {
  10291. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10292. } catch(e) {
  10293. exceptionHandler(e);
  10294. }
  10295. };
  10296. if (pending) {
  10297. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10298. } else {
  10299. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10300. }
  10301. return result.promise;
  10302. },
  10303. "catch": function(callback) {
  10304. return this.then(null, callback);
  10305. },
  10306. "finally": function(callback) {
  10307. function makePromise(value, resolved) {
  10308. var result = defer();
  10309. if (resolved) {
  10310. result.resolve(value);
  10311. } else {
  10312. result.reject(value);
  10313. }
  10314. return result.promise;
  10315. }
  10316. function handleCallback(value, isResolved) {
  10317. var callbackOutput = null;
  10318. try {
  10319. callbackOutput = (callback ||defaultCallback)();
  10320. } catch(e) {
  10321. return makePromise(e, false);
  10322. }
  10323. if (callbackOutput && isFunction(callbackOutput.then)) {
  10324. return callbackOutput.then(function() {
  10325. return makePromise(value, isResolved);
  10326. }, function(error) {
  10327. return makePromise(error, false);
  10328. });
  10329. } else {
  10330. return makePromise(value, isResolved);
  10331. }
  10332. }
  10333. return this.then(function(value) {
  10334. return handleCallback(value, true);
  10335. }, function(error) {
  10336. return handleCallback(error, false);
  10337. });
  10338. }
  10339. }
  10340. };
  10341. return deferred;
  10342. };
  10343. var ref = function(value) {
  10344. if (value && isFunction(value.then)) return value;
  10345. return {
  10346. then: function(callback) {
  10347. var result = defer();
  10348. nextTick(function() {
  10349. result.resolve(callback(value));
  10350. });
  10351. return result.promise;
  10352. }
  10353. };
  10354. };
  10355. /**
  10356. * @ngdoc method
  10357. * @name $q#reject
  10358. * @kind function
  10359. *
  10360. * @description
  10361. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10362. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10363. * a promise chain, you don't need to worry about it.
  10364. *
  10365. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10366. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10367. * a promise error callback and you want to forward the error to the promise derived from the
  10368. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10369. * `reject`.
  10370. *
  10371. * ```js
  10372. * promiseB = promiseA.then(function(result) {
  10373. * // success: do something and resolve promiseB
  10374. * // with the old or a new result
  10375. * return result;
  10376. * }, function(reason) {
  10377. * // error: handle the error if possible and
  10378. * // resolve promiseB with newPromiseOrValue,
  10379. * // otherwise forward the rejection to promiseB
  10380. * if (canHandle(reason)) {
  10381. * // handle the error and recover
  10382. * return newPromiseOrValue;
  10383. * }
  10384. * return $q.reject(reason);
  10385. * });
  10386. * ```
  10387. *
  10388. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10389. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10390. */
  10391. var reject = function(reason) {
  10392. var result = defer();
  10393. result.reject(reason);
  10394. return result.promise;
  10395. };
  10396. var createInternalRejectedPromise = function(reason) {
  10397. return {
  10398. then: function(callback, errback) {
  10399. var result = defer();
  10400. nextTick(function() {
  10401. try {
  10402. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10403. } catch(e) {
  10404. result.reject(e);
  10405. exceptionHandler(e);
  10406. }
  10407. });
  10408. return result.promise;
  10409. }
  10410. };
  10411. };
  10412. /**
  10413. * @ngdoc method
  10414. * @name $q#when
  10415. * @kind function
  10416. *
  10417. * @description
  10418. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10419. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10420. * the promise comes from a source that can't be trusted.
  10421. *
  10422. * @param {*} value Value or a promise
  10423. * @returns {Promise} Returns a promise of the passed value or promise
  10424. */
  10425. var when = function(value, callback, errback, progressback) {
  10426. var result = defer(),
  10427. done;
  10428. var wrappedCallback = function(value) {
  10429. try {
  10430. return (isFunction(callback) ? callback : defaultCallback)(value);
  10431. } catch (e) {
  10432. exceptionHandler(e);
  10433. return reject(e);
  10434. }
  10435. };
  10436. var wrappedErrback = function(reason) {
  10437. try {
  10438. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10439. } catch (e) {
  10440. exceptionHandler(e);
  10441. return reject(e);
  10442. }
  10443. };
  10444. var wrappedProgressback = function(progress) {
  10445. try {
  10446. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10447. } catch (e) {
  10448. exceptionHandler(e);
  10449. }
  10450. };
  10451. nextTick(function() {
  10452. ref(value).then(function(value) {
  10453. if (done) return;
  10454. done = true;
  10455. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10456. }, function(reason) {
  10457. if (done) return;
  10458. done = true;
  10459. result.resolve(wrappedErrback(reason));
  10460. }, function(progress) {
  10461. if (done) return;
  10462. result.notify(wrappedProgressback(progress));
  10463. });
  10464. });
  10465. return result.promise;
  10466. };
  10467. function defaultCallback(value) {
  10468. return value;
  10469. }
  10470. function defaultErrback(reason) {
  10471. return reject(reason);
  10472. }
  10473. /**
  10474. * @ngdoc method
  10475. * @name $q#all
  10476. * @kind function
  10477. *
  10478. * @description
  10479. * Combines multiple promises into a single promise that is resolved when all of the input
  10480. * promises are resolved.
  10481. *
  10482. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10483. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10484. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10485. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10486. * with the same rejection value.
  10487. */
  10488. function all(promises) {
  10489. var deferred = defer(),
  10490. counter = 0,
  10491. results = isArray(promises) ? [] : {};
  10492. forEach(promises, function(promise, key) {
  10493. counter++;
  10494. ref(promise).then(function(value) {
  10495. if (results.hasOwnProperty(key)) return;
  10496. results[key] = value;
  10497. if (!(--counter)) deferred.resolve(results);
  10498. }, function(reason) {
  10499. if (results.hasOwnProperty(key)) return;
  10500. deferred.reject(reason);
  10501. });
  10502. });
  10503. if (counter === 0) {
  10504. deferred.resolve(results);
  10505. }
  10506. return deferred.promise;
  10507. }
  10508. return {
  10509. defer: defer,
  10510. reject: reject,
  10511. when: when,
  10512. all: all
  10513. };
  10514. }
  10515. function $$RAFProvider(){ //rAF
  10516. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10517. var requestAnimationFrame = $window.requestAnimationFrame ||
  10518. $window.webkitRequestAnimationFrame ||
  10519. $window.mozRequestAnimationFrame;
  10520. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10521. $window.webkitCancelAnimationFrame ||
  10522. $window.mozCancelAnimationFrame ||
  10523. $window.webkitCancelRequestAnimationFrame;
  10524. var rafSupported = !!requestAnimationFrame;
  10525. var raf = rafSupported
  10526. ? function(fn) {
  10527. var id = requestAnimationFrame(fn);
  10528. return function() {
  10529. cancelAnimationFrame(id);
  10530. };
  10531. }
  10532. : function(fn) {
  10533. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10534. return function() {
  10535. $timeout.cancel(timer);
  10536. };
  10537. };
  10538. raf.supported = rafSupported;
  10539. return raf;
  10540. }];
  10541. }
  10542. /**
  10543. * DESIGN NOTES
  10544. *
  10545. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10546. *
  10547. * The typical use of scope is to watch the expressions, which most of the time return the same
  10548. * value as last time so we optimize the operation.
  10549. *
  10550. * Closures construction is expensive in terms of speed as well as memory:
  10551. * - No closures, instead use prototypical inheritance for API
  10552. * - Internal state needs to be stored on scope directly, which means that private state is
  10553. * exposed as $$____ properties
  10554. *
  10555. * Loop operations are optimized by using while(count--) { ... }
  10556. * - this means that in order to keep the same order of execution as addition we have to add
  10557. * items to the array at the beginning (unshift) instead of at the end (push)
  10558. *
  10559. * Child scopes are created and removed often
  10560. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10561. *
  10562. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10563. * implemented in the same way as watch. Watch requires return of initialization function which
  10564. * are expensive to construct.
  10565. */
  10566. /**
  10567. * @ngdoc provider
  10568. * @name $rootScopeProvider
  10569. * @description
  10570. *
  10571. * Provider for the $rootScope service.
  10572. */
  10573. /**
  10574. * @ngdoc method
  10575. * @name $rootScopeProvider#digestTtl
  10576. * @description
  10577. *
  10578. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10579. * assuming that the model is unstable.
  10580. *
  10581. * The current default is 10 iterations.
  10582. *
  10583. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10584. * several digest iterations. However if an application needs more than the default 10 digest
  10585. * iterations for its model to stabilize then you should investigate what is causing the model to
  10586. * continuously change during the digest.
  10587. *
  10588. * Increasing the TTL could have performance implications, so you should not change it without
  10589. * proper justification.
  10590. *
  10591. * @param {number} limit The number of digest iterations.
  10592. */
  10593. /**
  10594. * @ngdoc service
  10595. * @name $rootScope
  10596. * @description
  10597. *
  10598. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10599. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10600. * between the model and the view, via a mechanism for watching the model for changes.
  10601. * They also provide an event emission/broadcast and subscription facility. See the
  10602. * {@link guide/scope developer guide on scopes}.
  10603. */
  10604. function $RootScopeProvider(){
  10605. var TTL = 10;
  10606. var $rootScopeMinErr = minErr('$rootScope');
  10607. var lastDirtyWatch = null;
  10608. this.digestTtl = function(value) {
  10609. if (arguments.length) {
  10610. TTL = value;
  10611. }
  10612. return TTL;
  10613. };
  10614. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10615. function( $injector, $exceptionHandler, $parse, $browser) {
  10616. /**
  10617. * @ngdoc type
  10618. * @name $rootScope.Scope
  10619. *
  10620. * @description
  10621. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10622. * {@link auto.$injector $injector}. Child scopes are created using the
  10623. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10624. * compiled HTML template is executed.)
  10625. *
  10626. * Here is a simple scope snippet to show how you can interact with the scope.
  10627. * ```html
  10628. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10629. * ```
  10630. *
  10631. * # Inheritance
  10632. * A scope can inherit from a parent scope, as in this example:
  10633. * ```js
  10634. var parent = $rootScope;
  10635. var child = parent.$new();
  10636. parent.salutation = "Hello";
  10637. child.name = "World";
  10638. expect(child.salutation).toEqual('Hello');
  10639. child.salutation = "Welcome";
  10640. expect(child.salutation).toEqual('Welcome');
  10641. expect(parent.salutation).toEqual('Hello');
  10642. * ```
  10643. *
  10644. *
  10645. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10646. * provided for the current scope. Defaults to {@link ng}.
  10647. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10648. * append/override services provided by `providers`. This is handy
  10649. * when unit-testing and having the need to override a default
  10650. * service.
  10651. * @returns {Object} Newly created scope.
  10652. *
  10653. */
  10654. function Scope() {
  10655. this.$id = nextUid();
  10656. this.$$phase = this.$parent = this.$$watchers =
  10657. this.$$nextSibling = this.$$prevSibling =
  10658. this.$$childHead = this.$$childTail = null;
  10659. this['this'] = this.$root = this;
  10660. this.$$destroyed = false;
  10661. this.$$asyncQueue = [];
  10662. this.$$postDigestQueue = [];
  10663. this.$$listeners = {};
  10664. this.$$listenerCount = {};
  10665. this.$$isolateBindings = {};
  10666. }
  10667. /**
  10668. * @ngdoc property
  10669. * @name $rootScope.Scope#$id
  10670. * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
  10671. * debugging.
  10672. */
  10673. Scope.prototype = {
  10674. constructor: Scope,
  10675. /**
  10676. * @ngdoc method
  10677. * @name $rootScope.Scope#$new
  10678. * @kind function
  10679. *
  10680. * @description
  10681. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10682. *
  10683. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
  10684. * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
  10685. * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10686. *
  10687. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10688. * desired for the scope and its child scopes to be permanently detached from the parent and
  10689. * thus stop participating in model change detection and listener notification by invoking.
  10690. *
  10691. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10692. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10693. * When creating widgets, it is useful for the widget to not accidentally read parent
  10694. * state.
  10695. *
  10696. * @returns {Object} The newly created child scope.
  10697. *
  10698. */
  10699. $new: function(isolate) {
  10700. var ChildScope,
  10701. child;
  10702. if (isolate) {
  10703. child = new Scope();
  10704. child.$root = this.$root;
  10705. // ensure that there is just one async queue per $rootScope and its children
  10706. child.$$asyncQueue = this.$$asyncQueue;
  10707. child.$$postDigestQueue = this.$$postDigestQueue;
  10708. } else {
  10709. // Only create a child scope class if somebody asks for one,
  10710. // but cache it to allow the VM to optimize lookups.
  10711. if (!this.$$childScopeClass) {
  10712. this.$$childScopeClass = function() {
  10713. this.$$watchers = this.$$nextSibling =
  10714. this.$$childHead = this.$$childTail = null;
  10715. this.$$listeners = {};
  10716. this.$$listenerCount = {};
  10717. this.$id = nextUid();
  10718. this.$$childScopeClass = null;
  10719. };
  10720. this.$$childScopeClass.prototype = this;
  10721. }
  10722. child = new this.$$childScopeClass();
  10723. }
  10724. child['this'] = child;
  10725. child.$parent = this;
  10726. child.$$prevSibling = this.$$childTail;
  10727. if (this.$$childHead) {
  10728. this.$$childTail.$$nextSibling = child;
  10729. this.$$childTail = child;
  10730. } else {
  10731. this.$$childHead = this.$$childTail = child;
  10732. }
  10733. return child;
  10734. },
  10735. /**
  10736. * @ngdoc method
  10737. * @name $rootScope.Scope#$watch
  10738. * @kind function
  10739. *
  10740. * @description
  10741. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10742. *
  10743. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  10744. * $digest()} and should return the value that will be watched. (Since
  10745. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  10746. * `watchExpression` can execute multiple times per
  10747. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  10748. * - The `listener` is called only when the value from the current `watchExpression` and the
  10749. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10750. * see below). Inequality is determined according to reference inequality,
  10751. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  10752. * via the `!==` Javascript operator, unless `objectEquality == true`
  10753. * (see next point)
  10754. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  10755. * according to the {@link angular.equals} function. To save the value of the object for
  10756. * later comparison, the {@link angular.copy} function is used. This therefore means that
  10757. * watching complex objects will have adverse memory and performance implications.
  10758. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  10759. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  10760. * iteration limit is 10 to prevent an infinite loop deadlock.
  10761. *
  10762. *
  10763. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  10764. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  10765. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  10766. * change is detected, be prepared for multiple calls to your listener.)
  10767. *
  10768. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  10769. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  10770. * watcher. In rare cases, this is undesirable because the listener is called when the result
  10771. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  10772. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  10773. * listener was called due to initialization.
  10774. *
  10775. * The example below contains an illustration of using a function as your $watch listener
  10776. *
  10777. *
  10778. * # Example
  10779. * ```js
  10780. // let's assume that scope was dependency injected as the $rootScope
  10781. var scope = $rootScope;
  10782. scope.name = 'misko';
  10783. scope.counter = 0;
  10784. expect(scope.counter).toEqual(0);
  10785. scope.$watch('name', function(newValue, oldValue) {
  10786. scope.counter = scope.counter + 1;
  10787. });
  10788. expect(scope.counter).toEqual(0);
  10789. scope.$digest();
  10790. // the listener is always called during the first $digest loop after it was registered
  10791. expect(scope.counter).toEqual(1);
  10792. scope.$digest();
  10793. // but now it will not be called unless the value changes
  10794. expect(scope.counter).toEqual(1);
  10795. scope.name = 'adam';
  10796. scope.$digest();
  10797. expect(scope.counter).toEqual(2);
  10798. // Using a listener function
  10799. var food;
  10800. scope.foodCounter = 0;
  10801. expect(scope.foodCounter).toEqual(0);
  10802. scope.$watch(
  10803. // This is the listener function
  10804. function() { return food; },
  10805. // This is the change handler
  10806. function(newValue, oldValue) {
  10807. if ( newValue !== oldValue ) {
  10808. // Only increment the counter if the value changed
  10809. scope.foodCounter = scope.foodCounter + 1;
  10810. }
  10811. }
  10812. );
  10813. // No digest has been run so the counter will be zero
  10814. expect(scope.foodCounter).toEqual(0);
  10815. // Run the digest but since food has not changed count will still be zero
  10816. scope.$digest();
  10817. expect(scope.foodCounter).toEqual(0);
  10818. // Update food and run digest. Now the counter will increment
  10819. food = 'cheeseburger';
  10820. scope.$digest();
  10821. expect(scope.foodCounter).toEqual(1);
  10822. * ```
  10823. *
  10824. *
  10825. *
  10826. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  10827. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  10828. * a call to the `listener`.
  10829. *
  10830. * - `string`: Evaluated as {@link guide/expression expression}
  10831. * - `function(scope)`: called with current `scope` as a parameter.
  10832. * @param {(function()|string)=} listener Callback called whenever the return value of
  10833. * the `watchExpression` changes.
  10834. *
  10835. * - `string`: Evaluated as {@link guide/expression expression}
  10836. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  10837. * parameters.
  10838. *
  10839. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  10840. * comparing for reference equality.
  10841. * @returns {function()} Returns a deregistration function for this listener.
  10842. */
  10843. $watch: function(watchExp, listener, objectEquality) {
  10844. var scope = this,
  10845. get = compileToFn(watchExp, 'watch'),
  10846. array = scope.$$watchers,
  10847. watcher = {
  10848. fn: listener,
  10849. last: initWatchVal,
  10850. get: get,
  10851. exp: watchExp,
  10852. eq: !!objectEquality
  10853. };
  10854. lastDirtyWatch = null;
  10855. // in the case user pass string, we need to compile it, do we really need this ?
  10856. if (!isFunction(listener)) {
  10857. var listenFn = compileToFn(listener || noop, 'listener');
  10858. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  10859. }
  10860. if (typeof watchExp == 'string' && get.constant) {
  10861. var originalFn = watcher.fn;
  10862. watcher.fn = function(newVal, oldVal, scope) {
  10863. originalFn.call(this, newVal, oldVal, scope);
  10864. arrayRemove(array, watcher);
  10865. };
  10866. }
  10867. if (!array) {
  10868. array = scope.$$watchers = [];
  10869. }
  10870. // we use unshift since we use a while loop in $digest for speed.
  10871. // the while loop reads in reverse order.
  10872. array.unshift(watcher);
  10873. return function deregisterWatch() {
  10874. arrayRemove(array, watcher);
  10875. lastDirtyWatch = null;
  10876. };
  10877. },
  10878. /**
  10879. * @ngdoc method
  10880. * @name $rootScope.Scope#$watchCollection
  10881. * @kind function
  10882. *
  10883. * @description
  10884. * Shallow watches the properties of an object and fires whenever any of the properties change
  10885. * (for arrays, this implies watching the array items; for object maps, this implies watching
  10886. * the properties). If a change is detected, the `listener` callback is fired.
  10887. *
  10888. * - The `obj` collection is observed via standard $watch operation and is examined on every
  10889. * call to $digest() to see if any items have been added, removed, or moved.
  10890. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  10891. * adding, removing, and moving items belonging to an object or array.
  10892. *
  10893. *
  10894. * # Example
  10895. * ```js
  10896. $scope.names = ['igor', 'matias', 'misko', 'james'];
  10897. $scope.dataCount = 4;
  10898. $scope.$watchCollection('names', function(newNames, oldNames) {
  10899. $scope.dataCount = newNames.length;
  10900. });
  10901. expect($scope.dataCount).toEqual(4);
  10902. $scope.$digest();
  10903. //still at 4 ... no changes
  10904. expect($scope.dataCount).toEqual(4);
  10905. $scope.names.pop();
  10906. $scope.$digest();
  10907. //now there's been a change
  10908. expect($scope.dataCount).toEqual(3);
  10909. * ```
  10910. *
  10911. *
  10912. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  10913. * expression value should evaluate to an object or an array which is observed on each
  10914. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  10915. * collection will trigger a call to the `listener`.
  10916. *
  10917. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  10918. * when a change is detected.
  10919. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  10920. * - The `oldCollection` object is a copy of the former collection data.
  10921. * Due to performance considerations, the`oldCollection` value is computed only if the
  10922. * `listener` function declares two or more arguments.
  10923. * - The `scope` argument refers to the current scope.
  10924. *
  10925. * @returns {function()} Returns a de-registration function for this listener. When the
  10926. * de-registration function is executed, the internal watch operation is terminated.
  10927. */
  10928. $watchCollection: function(obj, listener) {
  10929. var self = this;
  10930. // the current value, updated on each dirty-check run
  10931. var newValue;
  10932. // a shallow copy of the newValue from the last dirty-check run,
  10933. // updated to match newValue during dirty-check run
  10934. var oldValue;
  10935. // a shallow copy of the newValue from when the last change happened
  10936. var veryOldValue;
  10937. // only track veryOldValue if the listener is asking for it
  10938. var trackVeryOldValue = (listener.length > 1);
  10939. var changeDetected = 0;
  10940. var objGetter = $parse(obj);
  10941. var internalArray = [];
  10942. var internalObject = {};
  10943. var initRun = true;
  10944. var oldLength = 0;
  10945. function $watchCollectionWatch() {
  10946. newValue = objGetter(self);
  10947. var newLength, key;
  10948. if (!isObject(newValue)) { // if primitive
  10949. if (oldValue !== newValue) {
  10950. oldValue = newValue;
  10951. changeDetected++;
  10952. }
  10953. } else if (isArrayLike(newValue)) {
  10954. if (oldValue !== internalArray) {
  10955. // we are transitioning from something which was not an array into array.
  10956. oldValue = internalArray;
  10957. oldLength = oldValue.length = 0;
  10958. changeDetected++;
  10959. }
  10960. newLength = newValue.length;
  10961. if (oldLength !== newLength) {
  10962. // if lengths do not match we need to trigger change notification
  10963. changeDetected++;
  10964. oldValue.length = oldLength = newLength;
  10965. }
  10966. // copy the items to oldValue and look for changes.
  10967. for (var i = 0; i < newLength; i++) {
  10968. var bothNaN = (oldValue[i] !== oldValue[i]) &&
  10969. (newValue[i] !== newValue[i]);
  10970. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  10971. changeDetected++;
  10972. oldValue[i] = newValue[i];
  10973. }
  10974. }
  10975. } else {
  10976. if (oldValue !== internalObject) {
  10977. // we are transitioning from something which was not an object into object.
  10978. oldValue = internalObject = {};
  10979. oldLength = 0;
  10980. changeDetected++;
  10981. }
  10982. // copy the items to oldValue and look for changes.
  10983. newLength = 0;
  10984. for (key in newValue) {
  10985. if (newValue.hasOwnProperty(key)) {
  10986. newLength++;
  10987. if (oldValue.hasOwnProperty(key)) {
  10988. if (oldValue[key] !== newValue[key]) {
  10989. changeDetected++;
  10990. oldValue[key] = newValue[key];
  10991. }
  10992. } else {
  10993. oldLength++;
  10994. oldValue[key] = newValue[key];
  10995. changeDetected++;
  10996. }
  10997. }
  10998. }
  10999. if (oldLength > newLength) {
  11000. // we used to have more keys, need to find them and destroy them.
  11001. changeDetected++;
  11002. for(key in oldValue) {
  11003. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  11004. oldLength--;
  11005. delete oldValue[key];
  11006. }
  11007. }
  11008. }
  11009. }
  11010. return changeDetected;
  11011. }
  11012. function $watchCollectionAction() {
  11013. if (initRun) {
  11014. initRun = false;
  11015. listener(newValue, newValue, self);
  11016. } else {
  11017. listener(newValue, veryOldValue, self);
  11018. }
  11019. // make a copy for the next time a collection is changed
  11020. if (trackVeryOldValue) {
  11021. if (!isObject(newValue)) {
  11022. //primitive
  11023. veryOldValue = newValue;
  11024. } else if (isArrayLike(newValue)) {
  11025. veryOldValue = new Array(newValue.length);
  11026. for (var i = 0; i < newValue.length; i++) {
  11027. veryOldValue[i] = newValue[i];
  11028. }
  11029. } else { // if object
  11030. veryOldValue = {};
  11031. for (var key in newValue) {
  11032. if (hasOwnProperty.call(newValue, key)) {
  11033. veryOldValue[key] = newValue[key];
  11034. }
  11035. }
  11036. }
  11037. }
  11038. }
  11039. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  11040. },
  11041. /**
  11042. * @ngdoc method
  11043. * @name $rootScope.Scope#$digest
  11044. * @kind function
  11045. *
  11046. * @description
  11047. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  11048. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  11049. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  11050. * until no more listeners are firing. This means that it is possible to get into an infinite
  11051. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  11052. * iterations exceeds 10.
  11053. *
  11054. * Usually, you don't call `$digest()` directly in
  11055. * {@link ng.directive:ngController controllers} or in
  11056. * {@link ng.$compileProvider#directive directives}.
  11057. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  11058. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  11059. *
  11060. * If you want to be notified whenever `$digest()` is called,
  11061. * you can register a `watchExpression` function with
  11062. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  11063. *
  11064. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  11065. *
  11066. * # Example
  11067. * ```js
  11068. var scope = ...;
  11069. scope.name = 'misko';
  11070. scope.counter = 0;
  11071. expect(scope.counter).toEqual(0);
  11072. scope.$watch('name', function(newValue, oldValue) {
  11073. scope.counter = scope.counter + 1;
  11074. });
  11075. expect(scope.counter).toEqual(0);
  11076. scope.$digest();
  11077. // the listener is always called during the first $digest loop after it was registered
  11078. expect(scope.counter).toEqual(1);
  11079. scope.$digest();
  11080. // but now it will not be called unless the value changes
  11081. expect(scope.counter).toEqual(1);
  11082. scope.name = 'adam';
  11083. scope.$digest();
  11084. expect(scope.counter).toEqual(2);
  11085. * ```
  11086. *
  11087. */
  11088. $digest: function() {
  11089. var watch, value, last,
  11090. watchers,
  11091. asyncQueue = this.$$asyncQueue,
  11092. postDigestQueue = this.$$postDigestQueue,
  11093. length,
  11094. dirty, ttl = TTL,
  11095. next, current, target = this,
  11096. watchLog = [],
  11097. logIdx, logMsg, asyncTask;
  11098. beginPhase('$digest');
  11099. lastDirtyWatch = null;
  11100. do { // "while dirty" loop
  11101. dirty = false;
  11102. current = target;
  11103. while(asyncQueue.length) {
  11104. try {
  11105. asyncTask = asyncQueue.shift();
  11106. asyncTask.scope.$eval(asyncTask.expression);
  11107. } catch (e) {
  11108. clearPhase();
  11109. $exceptionHandler(e);
  11110. }
  11111. lastDirtyWatch = null;
  11112. }
  11113. traverseScopesLoop:
  11114. do { // "traverse the scopes" loop
  11115. if ((watchers = current.$$watchers)) {
  11116. // process our watches
  11117. length = watchers.length;
  11118. while (length--) {
  11119. try {
  11120. watch = watchers[length];
  11121. // Most common watches are on primitives, in which case we can short
  11122. // circuit it with === operator, only when === fails do we use .equals
  11123. if (watch) {
  11124. if ((value = watch.get(current)) !== (last = watch.last) &&
  11125. !(watch.eq
  11126. ? equals(value, last)
  11127. : (typeof value == 'number' && typeof last == 'number'
  11128. && isNaN(value) && isNaN(last)))) {
  11129. dirty = true;
  11130. lastDirtyWatch = watch;
  11131. watch.last = watch.eq ? copy(value, null) : value;
  11132. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11133. if (ttl < 5) {
  11134. logIdx = 4 - ttl;
  11135. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11136. logMsg = (isFunction(watch.exp))
  11137. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11138. : watch.exp;
  11139. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11140. watchLog[logIdx].push(logMsg);
  11141. }
  11142. } else if (watch === lastDirtyWatch) {
  11143. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11144. // have already been tested.
  11145. dirty = false;
  11146. break traverseScopesLoop;
  11147. }
  11148. }
  11149. } catch (e) {
  11150. clearPhase();
  11151. $exceptionHandler(e);
  11152. }
  11153. }
  11154. }
  11155. // Insanity Warning: scope depth-first traversal
  11156. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11157. // this piece should be kept in sync with the traversal in $broadcast
  11158. if (!(next = (current.$$childHead ||
  11159. (current !== target && current.$$nextSibling)))) {
  11160. while(current !== target && !(next = current.$$nextSibling)) {
  11161. current = current.$parent;
  11162. }
  11163. }
  11164. } while ((current = next));
  11165. // `break traverseScopesLoop;` takes us to here
  11166. if((dirty || asyncQueue.length) && !(ttl--)) {
  11167. clearPhase();
  11168. throw $rootScopeMinErr('infdig',
  11169. '{0} $digest() iterations reached. Aborting!\n' +
  11170. 'Watchers fired in the last 5 iterations: {1}',
  11171. TTL, toJson(watchLog));
  11172. }
  11173. } while (dirty || asyncQueue.length);
  11174. clearPhase();
  11175. while(postDigestQueue.length) {
  11176. try {
  11177. postDigestQueue.shift()();
  11178. } catch (e) {
  11179. $exceptionHandler(e);
  11180. }
  11181. }
  11182. },
  11183. /**
  11184. * @ngdoc event
  11185. * @name $rootScope.Scope#$destroy
  11186. * @eventType broadcast on scope being destroyed
  11187. *
  11188. * @description
  11189. * Broadcasted when a scope and its children are being destroyed.
  11190. *
  11191. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11192. * clean up DOM bindings before an element is removed from the DOM.
  11193. */
  11194. /**
  11195. * @ngdoc method
  11196. * @name $rootScope.Scope#$destroy
  11197. * @kind function
  11198. *
  11199. * @description
  11200. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11201. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11202. * propagate to the current scope and its children. Removal also implies that the current
  11203. * scope is eligible for garbage collection.
  11204. *
  11205. * The `$destroy()` is usually used by directives such as
  11206. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11207. * unrolling of the loop.
  11208. *
  11209. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11210. * Application code can register a `$destroy` event handler that will give it a chance to
  11211. * perform any necessary cleanup.
  11212. *
  11213. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11214. * clean up DOM bindings before an element is removed from the DOM.
  11215. */
  11216. $destroy: function() {
  11217. // we can't destroy the root scope or a scope that has been already destroyed
  11218. if (this.$$destroyed) return;
  11219. var parent = this.$parent;
  11220. this.$broadcast('$destroy');
  11221. this.$$destroyed = true;
  11222. if (this === $rootScope) return;
  11223. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11224. // sever all the references to parent scopes (after this cleanup, the current scope should
  11225. // not be retained by any of our references and should be eligible for garbage collection)
  11226. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11227. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11228. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11229. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11230. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11231. // and inline caches.
  11232. //
  11233. // see:
  11234. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11235. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11236. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11237. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11238. this.$$childTail = this.$root = null;
  11239. // don't reset these to null in case some async task tries to register a listener/watch/task
  11240. this.$$listeners = {};
  11241. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11242. // prevent NPEs since these methods have references to properties we nulled out
  11243. this.$destroy = this.$digest = this.$apply = noop;
  11244. this.$on = this.$watch = function() { return noop; };
  11245. },
  11246. /**
  11247. * @ngdoc method
  11248. * @name $rootScope.Scope#$eval
  11249. * @kind function
  11250. *
  11251. * @description
  11252. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11253. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11254. * expressions.
  11255. *
  11256. * # Example
  11257. * ```js
  11258. var scope = ng.$rootScope.Scope();
  11259. scope.a = 1;
  11260. scope.b = 2;
  11261. expect(scope.$eval('a+b')).toEqual(3);
  11262. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11263. * ```
  11264. *
  11265. * @param {(string|function())=} expression An angular expression to be executed.
  11266. *
  11267. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11268. * - `function(scope)`: execute the function with the current `scope` parameter.
  11269. *
  11270. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11271. * @returns {*} The result of evaluating the expression.
  11272. */
  11273. $eval: function(expr, locals) {
  11274. return $parse(expr)(this, locals);
  11275. },
  11276. /**
  11277. * @ngdoc method
  11278. * @name $rootScope.Scope#$evalAsync
  11279. * @kind function
  11280. *
  11281. * @description
  11282. * Executes the expression on the current scope at a later point in time.
  11283. *
  11284. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11285. * that:
  11286. *
  11287. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11288. * rendering).
  11289. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11290. * `expression` execution.
  11291. *
  11292. * Any exceptions from the execution of the expression are forwarded to the
  11293. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11294. *
  11295. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11296. * will be scheduled. However, it is encouraged to always call code that changes the model
  11297. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11298. *
  11299. * @param {(string|function())=} expression An angular expression to be executed.
  11300. *
  11301. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11302. * - `function(scope)`: execute the function with the current `scope` parameter.
  11303. *
  11304. */
  11305. $evalAsync: function(expr) {
  11306. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11307. // task also schedule async auto-flush
  11308. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11309. $browser.defer(function() {
  11310. if ($rootScope.$$asyncQueue.length) {
  11311. $rootScope.$digest();
  11312. }
  11313. });
  11314. }
  11315. this.$$asyncQueue.push({scope: this, expression: expr});
  11316. },
  11317. $$postDigest : function(fn) {
  11318. this.$$postDigestQueue.push(fn);
  11319. },
  11320. /**
  11321. * @ngdoc method
  11322. * @name $rootScope.Scope#$apply
  11323. * @kind function
  11324. *
  11325. * @description
  11326. * `$apply()` is used to execute an expression in angular from outside of the angular
  11327. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11328. * Because we are calling into the angular framework we need to perform proper scope life
  11329. * cycle of {@link ng.$exceptionHandler exception handling},
  11330. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11331. *
  11332. * ## Life cycle
  11333. *
  11334. * # Pseudo-Code of `$apply()`
  11335. * ```js
  11336. function $apply(expr) {
  11337. try {
  11338. return $eval(expr);
  11339. } catch (e) {
  11340. $exceptionHandler(e);
  11341. } finally {
  11342. $root.$digest();
  11343. }
  11344. }
  11345. * ```
  11346. *
  11347. *
  11348. * Scope's `$apply()` method transitions through the following stages:
  11349. *
  11350. * 1. The {@link guide/expression expression} is executed using the
  11351. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11352. * 2. Any exceptions from the execution of the expression are forwarded to the
  11353. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11354. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11355. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11356. *
  11357. *
  11358. * @param {(string|function())=} exp An angular expression to be executed.
  11359. *
  11360. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11361. * - `function(scope)`: execute the function with current `scope` parameter.
  11362. *
  11363. * @returns {*} The result of evaluating the expression.
  11364. */
  11365. $apply: function(expr) {
  11366. try {
  11367. beginPhase('$apply');
  11368. return this.$eval(expr);
  11369. } catch (e) {
  11370. $exceptionHandler(e);
  11371. } finally {
  11372. clearPhase();
  11373. try {
  11374. $rootScope.$digest();
  11375. } catch (e) {
  11376. $exceptionHandler(e);
  11377. throw e;
  11378. }
  11379. }
  11380. },
  11381. /**
  11382. * @ngdoc method
  11383. * @name $rootScope.Scope#$on
  11384. * @kind function
  11385. *
  11386. * @description
  11387. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11388. * discussion of event life cycle.
  11389. *
  11390. * The event listener function format is: `function(event, args...)`. The `event` object
  11391. * passed into the listener has the following attributes:
  11392. *
  11393. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11394. * `$broadcast`-ed.
  11395. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11396. * - `name` - `{string}`: name of the event.
  11397. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11398. * further event propagation (available only for events that were `$emit`-ed).
  11399. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11400. * to true.
  11401. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11402. *
  11403. * @param {string} name Event name to listen on.
  11404. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11405. * @returns {function()} Returns a deregistration function for this listener.
  11406. */
  11407. $on: function(name, listener) {
  11408. var namedListeners = this.$$listeners[name];
  11409. if (!namedListeners) {
  11410. this.$$listeners[name] = namedListeners = [];
  11411. }
  11412. namedListeners.push(listener);
  11413. var current = this;
  11414. do {
  11415. if (!current.$$listenerCount[name]) {
  11416. current.$$listenerCount[name] = 0;
  11417. }
  11418. current.$$listenerCount[name]++;
  11419. } while ((current = current.$parent));
  11420. var self = this;
  11421. return function() {
  11422. namedListeners[indexOf(namedListeners, listener)] = null;
  11423. decrementListenerCount(self, 1, name);
  11424. };
  11425. },
  11426. /**
  11427. * @ngdoc method
  11428. * @name $rootScope.Scope#$emit
  11429. * @kind function
  11430. *
  11431. * @description
  11432. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11433. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11434. *
  11435. * The event life cycle starts at the scope on which `$emit` was called. All
  11436. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11437. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11438. * registered listeners along the way. The event will stop propagating if one of the listeners
  11439. * cancels it.
  11440. *
  11441. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11442. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11443. *
  11444. * @param {string} name Event name to emit.
  11445. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11446. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11447. */
  11448. $emit: function(name, args) {
  11449. var empty = [],
  11450. namedListeners,
  11451. scope = this,
  11452. stopPropagation = false,
  11453. event = {
  11454. name: name,
  11455. targetScope: scope,
  11456. stopPropagation: function() {stopPropagation = true;},
  11457. preventDefault: function() {
  11458. event.defaultPrevented = true;
  11459. },
  11460. defaultPrevented: false
  11461. },
  11462. listenerArgs = concat([event], arguments, 1),
  11463. i, length;
  11464. do {
  11465. namedListeners = scope.$$listeners[name] || empty;
  11466. event.currentScope = scope;
  11467. for (i=0, length=namedListeners.length; i<length; i++) {
  11468. // if listeners were deregistered, defragment the array
  11469. if (!namedListeners[i]) {
  11470. namedListeners.splice(i, 1);
  11471. i--;
  11472. length--;
  11473. continue;
  11474. }
  11475. try {
  11476. //allow all listeners attached to the current scope to run
  11477. namedListeners[i].apply(null, listenerArgs);
  11478. } catch (e) {
  11479. $exceptionHandler(e);
  11480. }
  11481. }
  11482. //if any listener on the current scope stops propagation, prevent bubbling
  11483. if (stopPropagation) return event;
  11484. //traverse upwards
  11485. scope = scope.$parent;
  11486. } while (scope);
  11487. return event;
  11488. },
  11489. /**
  11490. * @ngdoc method
  11491. * @name $rootScope.Scope#$broadcast
  11492. * @kind function
  11493. *
  11494. * @description
  11495. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11496. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11497. *
  11498. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11499. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11500. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11501. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11502. *
  11503. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11504. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11505. *
  11506. * @param {string} name Event name to broadcast.
  11507. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11508. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11509. */
  11510. $broadcast: function(name, args) {
  11511. var target = this,
  11512. current = target,
  11513. next = target,
  11514. event = {
  11515. name: name,
  11516. targetScope: target,
  11517. preventDefault: function() {
  11518. event.defaultPrevented = true;
  11519. },
  11520. defaultPrevented: false
  11521. },
  11522. listenerArgs = concat([event], arguments, 1),
  11523. listeners, i, length;
  11524. //down while you can, then up and next sibling or up and next sibling until back at root
  11525. while ((current = next)) {
  11526. event.currentScope = current;
  11527. listeners = current.$$listeners[name] || [];
  11528. for (i=0, length = listeners.length; i<length; i++) {
  11529. // if listeners were deregistered, defragment the array
  11530. if (!listeners[i]) {
  11531. listeners.splice(i, 1);
  11532. i--;
  11533. length--;
  11534. continue;
  11535. }
  11536. try {
  11537. listeners[i].apply(null, listenerArgs);
  11538. } catch(e) {
  11539. $exceptionHandler(e);
  11540. }
  11541. }
  11542. // Insanity Warning: scope depth-first traversal
  11543. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11544. // this piece should be kept in sync with the traversal in $digest
  11545. // (though it differs due to having the extra check for $$listenerCount)
  11546. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11547. (current !== target && current.$$nextSibling)))) {
  11548. while(current !== target && !(next = current.$$nextSibling)) {
  11549. current = current.$parent;
  11550. }
  11551. }
  11552. }
  11553. return event;
  11554. }
  11555. };
  11556. var $rootScope = new Scope();
  11557. return $rootScope;
  11558. function beginPhase(phase) {
  11559. if ($rootScope.$$phase) {
  11560. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11561. }
  11562. $rootScope.$$phase = phase;
  11563. }
  11564. function clearPhase() {
  11565. $rootScope.$$phase = null;
  11566. }
  11567. function compileToFn(exp, name) {
  11568. var fn = $parse(exp);
  11569. assertArgFn(fn, name);
  11570. return fn;
  11571. }
  11572. function decrementListenerCount(current, count, name) {
  11573. do {
  11574. current.$$listenerCount[name] -= count;
  11575. if (current.$$listenerCount[name] === 0) {
  11576. delete current.$$listenerCount[name];
  11577. }
  11578. } while ((current = current.$parent));
  11579. }
  11580. /**
  11581. * function used as an initial value for watchers.
  11582. * because it's unique we can easily tell it apart from other values
  11583. */
  11584. function initWatchVal() {}
  11585. }];
  11586. }
  11587. /**
  11588. * @description
  11589. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11590. */
  11591. function $$SanitizeUriProvider() {
  11592. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11593. imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
  11594. /**
  11595. * @description
  11596. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11597. * urls during a[href] sanitization.
  11598. *
  11599. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11600. *
  11601. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11602. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11603. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11604. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11605. *
  11606. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11607. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11608. * chaining otherwise.
  11609. */
  11610. this.aHrefSanitizationWhitelist = function(regexp) {
  11611. if (isDefined(regexp)) {
  11612. aHrefSanitizationWhitelist = regexp;
  11613. return this;
  11614. }
  11615. return aHrefSanitizationWhitelist;
  11616. };
  11617. /**
  11618. * @description
  11619. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11620. * urls during img[src] sanitization.
  11621. *
  11622. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11623. *
  11624. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11625. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11626. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11627. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11628. *
  11629. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11630. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11631. * chaining otherwise.
  11632. */
  11633. this.imgSrcSanitizationWhitelist = function(regexp) {
  11634. if (isDefined(regexp)) {
  11635. imgSrcSanitizationWhitelist = regexp;
  11636. return this;
  11637. }
  11638. return imgSrcSanitizationWhitelist;
  11639. };
  11640. this.$get = function() {
  11641. return function sanitizeUri(uri, isImage) {
  11642. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11643. var normalizedVal;
  11644. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11645. if (!msie || msie >= 8 ) {
  11646. normalizedVal = urlResolve(uri).href;
  11647. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11648. return 'unsafe:'+normalizedVal;
  11649. }
  11650. }
  11651. return uri;
  11652. };
  11653. };
  11654. }
  11655. var $sceMinErr = minErr('$sce');
  11656. var SCE_CONTEXTS = {
  11657. HTML: 'html',
  11658. CSS: 'css',
  11659. URL: 'url',
  11660. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11661. // url. (e.g. ng-include, script src, templateUrl)
  11662. RESOURCE_URL: 'resourceUrl',
  11663. JS: 'js'
  11664. };
  11665. // Helper functions follow.
  11666. // Copied from:
  11667. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11668. // Prereq: s is a string.
  11669. function escapeForRegexp(s) {
  11670. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11671. replace(/\x08/g, '\\x08');
  11672. }
  11673. function adjustMatcher(matcher) {
  11674. if (matcher === 'self') {
  11675. return matcher;
  11676. } else if (isString(matcher)) {
  11677. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11678. // '*' matches any character except those from the set ':/.?&'.
  11679. // '**' matches any character (like .* in a RegExp).
  11680. // More than 2 *'s raises an error as it's ill defined.
  11681. if (matcher.indexOf('***') > -1) {
  11682. throw $sceMinErr('iwcard',
  11683. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11684. }
  11685. matcher = escapeForRegexp(matcher).
  11686. replace('\\*\\*', '.*').
  11687. replace('\\*', '[^:/.?&;]*');
  11688. return new RegExp('^' + matcher + '$');
  11689. } else if (isRegExp(matcher)) {
  11690. // The only other type of matcher allowed is a Regexp.
  11691. // Match entire URL / disallow partial matches.
  11692. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11693. return new RegExp('^' + matcher.source + '$');
  11694. } else {
  11695. throw $sceMinErr('imatcher',
  11696. 'Matchers may only be "self", string patterns or RegExp objects');
  11697. }
  11698. }
  11699. function adjustMatchers(matchers) {
  11700. var adjustedMatchers = [];
  11701. if (isDefined(matchers)) {
  11702. forEach(matchers, function(matcher) {
  11703. adjustedMatchers.push(adjustMatcher(matcher));
  11704. });
  11705. }
  11706. return adjustedMatchers;
  11707. }
  11708. /**
  11709. * @ngdoc service
  11710. * @name $sceDelegate
  11711. * @kind function
  11712. *
  11713. * @description
  11714. *
  11715. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11716. * Contextual Escaping (SCE)} services to AngularJS.
  11717. *
  11718. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11719. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11720. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11721. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11722. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11723. *
  11724. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11725. *
  11726. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  11727. * can override it completely to change the behavior of `$sce`, the common case would
  11728. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  11729. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  11730. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  11731. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  11732. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11733. */
  11734. /**
  11735. * @ngdoc provider
  11736. * @name $sceDelegateProvider
  11737. * @description
  11738. *
  11739. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11740. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11741. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11742. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11743. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11744. *
  11745. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11746. * Strict Contextual Escaping (SCE)}.
  11747. *
  11748. * **Example**: Consider the following case. <a name="example"></a>
  11749. *
  11750. * - your app is hosted at url `http://myapp.example.com/`
  11751. * - but some of your templates are hosted on other domains you control such as
  11752. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  11753. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  11754. *
  11755. * Here is what a secure configuration for this scenario might look like:
  11756. *
  11757. * <pre class="prettyprint">
  11758. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  11759. * $sceDelegateProvider.resourceUrlWhitelist([
  11760. * // Allow same origin resource loads.
  11761. * 'self',
  11762. * // Allow loading from our assets domain. Notice the difference between * and **.
  11763. * 'http://srv*.assets.example.com/**']);
  11764. *
  11765. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  11766. * $sceDelegateProvider.resourceUrlBlacklist([
  11767. * 'http://myapp.example.com/clickThru**']);
  11768. * });
  11769. * </pre>
  11770. */
  11771. function $SceDelegateProvider() {
  11772. this.SCE_CONTEXTS = SCE_CONTEXTS;
  11773. // Resource URLs can also be trusted by policy.
  11774. var resourceUrlWhitelist = ['self'],
  11775. resourceUrlBlacklist = [];
  11776. /**
  11777. * @ngdoc method
  11778. * @name $sceDelegateProvider#resourceUrlWhitelist
  11779. * @kind function
  11780. *
  11781. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  11782. * provided. This must be an array or null. A snapshot of this array is used so further
  11783. * changes to the array are ignored.
  11784. *
  11785. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11786. * allowed in this array.
  11787. *
  11788. * Note: **an empty whitelist array will block all URLs**!
  11789. *
  11790. * @return {Array} the currently set whitelist array.
  11791. *
  11792. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  11793. * same origin resource requests.
  11794. *
  11795. * @description
  11796. * Sets/Gets the whitelist of trusted resource URLs.
  11797. */
  11798. this.resourceUrlWhitelist = function (value) {
  11799. if (arguments.length) {
  11800. resourceUrlWhitelist = adjustMatchers(value);
  11801. }
  11802. return resourceUrlWhitelist;
  11803. };
  11804. /**
  11805. * @ngdoc method
  11806. * @name $sceDelegateProvider#resourceUrlBlacklist
  11807. * @kind function
  11808. *
  11809. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  11810. * provided. This must be an array or null. A snapshot of this array is used so further
  11811. * changes to the array are ignored.
  11812. *
  11813. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11814. * allowed in this array.
  11815. *
  11816. * The typical usage for the blacklist is to **block
  11817. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  11818. * these would otherwise be trusted but actually return content from the redirected domain.
  11819. *
  11820. * Finally, **the blacklist overrides the whitelist** and has the final say.
  11821. *
  11822. * @return {Array} the currently set blacklist array.
  11823. *
  11824. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  11825. * is no blacklist.)
  11826. *
  11827. * @description
  11828. * Sets/Gets the blacklist of trusted resource URLs.
  11829. */
  11830. this.resourceUrlBlacklist = function (value) {
  11831. if (arguments.length) {
  11832. resourceUrlBlacklist = adjustMatchers(value);
  11833. }
  11834. return resourceUrlBlacklist;
  11835. };
  11836. this.$get = ['$injector', function($injector) {
  11837. var htmlSanitizer = function htmlSanitizer(html) {
  11838. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11839. };
  11840. if ($injector.has('$sanitize')) {
  11841. htmlSanitizer = $injector.get('$sanitize');
  11842. }
  11843. function matchUrl(matcher, parsedUrl) {
  11844. if (matcher === 'self') {
  11845. return urlIsSameOrigin(parsedUrl);
  11846. } else {
  11847. // definitely a regex. See adjustMatchers()
  11848. return !!matcher.exec(parsedUrl.href);
  11849. }
  11850. }
  11851. function isResourceUrlAllowedByPolicy(url) {
  11852. var parsedUrl = urlResolve(url.toString());
  11853. var i, n, allowed = false;
  11854. // Ensure that at least one item from the whitelist allows this url.
  11855. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  11856. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  11857. allowed = true;
  11858. break;
  11859. }
  11860. }
  11861. if (allowed) {
  11862. // Ensure that no item from the blacklist blocked this url.
  11863. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  11864. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  11865. allowed = false;
  11866. break;
  11867. }
  11868. }
  11869. }
  11870. return allowed;
  11871. }
  11872. function generateHolderType(Base) {
  11873. var holderType = function TrustedValueHolderType(trustedValue) {
  11874. this.$$unwrapTrustedValue = function() {
  11875. return trustedValue;
  11876. };
  11877. };
  11878. if (Base) {
  11879. holderType.prototype = new Base();
  11880. }
  11881. holderType.prototype.valueOf = function sceValueOf() {
  11882. return this.$$unwrapTrustedValue();
  11883. };
  11884. holderType.prototype.toString = function sceToString() {
  11885. return this.$$unwrapTrustedValue().toString();
  11886. };
  11887. return holderType;
  11888. }
  11889. var trustedValueHolderBase = generateHolderType(),
  11890. byType = {};
  11891. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  11892. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  11893. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  11894. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  11895. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  11896. /**
  11897. * @ngdoc method
  11898. * @name $sceDelegate#trustAs
  11899. *
  11900. * @description
  11901. * Returns an object that is trusted by angular for use in specified strict
  11902. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  11903. * attribute interpolation, any dom event binding attribute interpolation
  11904. * such as for onclick, etc.) that uses the provided value.
  11905. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  11906. *
  11907. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11908. * resourceUrl, html, js and css.
  11909. * @param {*} value The value that that should be considered trusted/safe.
  11910. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11911. * where Angular expects a $sce.trustAs() return value.
  11912. */
  11913. function trustAs(type, trustedValue) {
  11914. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11915. if (!Constructor) {
  11916. throw $sceMinErr('icontext',
  11917. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  11918. type, trustedValue);
  11919. }
  11920. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  11921. return trustedValue;
  11922. }
  11923. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  11924. // mutable objects, we ensure here that the value passed in is actually a string.
  11925. if (typeof trustedValue !== 'string') {
  11926. throw $sceMinErr('itype',
  11927. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  11928. type);
  11929. }
  11930. return new Constructor(trustedValue);
  11931. }
  11932. /**
  11933. * @ngdoc method
  11934. * @name $sceDelegate#valueOf
  11935. *
  11936. * @description
  11937. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  11938. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  11939. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  11940. *
  11941. * If the passed parameter is not a value that had been returned by {@link
  11942. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  11943. *
  11944. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  11945. * call or anything else.
  11946. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  11947. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  11948. * `value` unchanged.
  11949. */
  11950. function valueOf(maybeTrusted) {
  11951. if (maybeTrusted instanceof trustedValueHolderBase) {
  11952. return maybeTrusted.$$unwrapTrustedValue();
  11953. } else {
  11954. return maybeTrusted;
  11955. }
  11956. }
  11957. /**
  11958. * @ngdoc method
  11959. * @name $sceDelegate#getTrusted
  11960. *
  11961. * @description
  11962. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  11963. * returns the originally supplied value if the queried context type is a supertype of the
  11964. * created type. If this condition isn't satisfied, throws an exception.
  11965. *
  11966. * @param {string} type The kind of context in which this value is to be used.
  11967. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  11968. * `$sceDelegate.trustAs`} call.
  11969. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  11970. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  11971. */
  11972. function getTrusted(type, maybeTrusted) {
  11973. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  11974. return maybeTrusted;
  11975. }
  11976. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11977. if (constructor && maybeTrusted instanceof constructor) {
  11978. return maybeTrusted.$$unwrapTrustedValue();
  11979. }
  11980. // If we get here, then we may only take one of two actions.
  11981. // 1. sanitize the value for the requested type, or
  11982. // 2. throw an exception.
  11983. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  11984. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  11985. return maybeTrusted;
  11986. } else {
  11987. throw $sceMinErr('insecurl',
  11988. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  11989. maybeTrusted.toString());
  11990. }
  11991. } else if (type === SCE_CONTEXTS.HTML) {
  11992. return htmlSanitizer(maybeTrusted);
  11993. }
  11994. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11995. }
  11996. return { trustAs: trustAs,
  11997. getTrusted: getTrusted,
  11998. valueOf: valueOf };
  11999. }];
  12000. }
  12001. /**
  12002. * @ngdoc provider
  12003. * @name $sceProvider
  12004. * @description
  12005. *
  12006. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  12007. * - enable/disable Strict Contextual Escaping (SCE) in a module
  12008. * - override the default implementation with a custom delegate
  12009. *
  12010. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  12011. */
  12012. /* jshint maxlen: false*/
  12013. /**
  12014. * @ngdoc service
  12015. * @name $sce
  12016. * @kind function
  12017. *
  12018. * @description
  12019. *
  12020. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  12021. *
  12022. * # Strict Contextual Escaping
  12023. *
  12024. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  12025. * contexts to result in a value that is marked as safe to use for that context. One example of
  12026. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  12027. * to these contexts as privileged or SCE contexts.
  12028. *
  12029. * As of version 1.2, Angular ships with SCE enabled by default.
  12030. *
  12031. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  12032. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  12033. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  12034. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  12035. * to the top of your HTML document.
  12036. *
  12037. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  12038. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  12039. *
  12040. * Here's an example of a binding in a privileged context:
  12041. *
  12042. * <pre class="prettyprint">
  12043. * <input ng-model="userHtml">
  12044. * <div ng-bind-html="userHtml">
  12045. * </pre>
  12046. *
  12047. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  12048. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  12049. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  12050. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  12051. * security vulnerabilities.)
  12052. *
  12053. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  12054. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  12055. *
  12056. * How would you ensure that every place that used these types of bindings was bound to a value that
  12057. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  12058. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  12059. * properties/fields and forgot to update the binding to the sanitized value?
  12060. *
  12061. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  12062. * determine that something explicitly says it's safe to use a value for binding in that
  12063. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  12064. * for those values that you can easily tell are safe - because they were received from your server,
  12065. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  12066. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  12067. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  12068. *
  12069. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  12070. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  12071. * obtain values that will be accepted by SCE / privileged contexts.
  12072. *
  12073. *
  12074. * ## How does it work?
  12075. *
  12076. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  12077. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  12078. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  12079. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  12080. *
  12081. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  12082. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  12083. * simplified):
  12084. *
  12085. * <pre class="prettyprint">
  12086. * var ngBindHtmlDirective = ['$sce', function($sce) {
  12087. * return function(scope, element, attr) {
  12088. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  12089. * element.html(value || '');
  12090. * });
  12091. * };
  12092. * }];
  12093. * </pre>
  12094. *
  12095. * ## Impact on loading templates
  12096. *
  12097. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12098. * `templateUrl`'s specified by {@link guide/directive directives}.
  12099. *
  12100. * By default, Angular only loads templates from the same domain and protocol as the application
  12101. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12102. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12103. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12104. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12105. *
  12106. * *Please note*:
  12107. * The browser's
  12108. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12109. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12110. * policy apply in addition to this and may further restrict whether the template is successfully
  12111. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12112. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12113. * browsers.
  12114. *
  12115. * ## This feels like too much overhead for the developer?
  12116. *
  12117. * It's important to remember that SCE only applies to interpolation expressions.
  12118. *
  12119. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12120. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12121. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12122. *
  12123. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12124. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12125. *
  12126. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12127. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12128. * It blocks loading templates from other domains or loading templates over http from an https
  12129. * served document. You can change these by setting your own custom {@link
  12130. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12131. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12132. *
  12133. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12134. * application that's secure and can be audited to verify that with much more ease than bolting
  12135. * security onto an application later.
  12136. *
  12137. * <a name="contexts"></a>
  12138. * ## What trusted context types are supported?
  12139. *
  12140. * | Context | Notes |
  12141. * |---------------------|----------------|
  12142. * | `$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. |
  12143. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12144. * | `$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. |
  12145. * | `$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. |
  12146. * | `$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. |
  12147. *
  12148. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12149. *
  12150. * Each element in these arrays must be one of the following:
  12151. *
  12152. * - **'self'**
  12153. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12154. * domain** as the application document using the **same protocol**.
  12155. * - **String** (except the special value `'self'`)
  12156. * - The string is matched against the full *normalized / absolute URL* of the resource
  12157. * being tested (substring matches are not good enough.)
  12158. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12159. * match themselves.
  12160. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12161. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12162. * in a whitelist.
  12163. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12164. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12165. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12166. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  12167. * http://foo.example.com/templates/**).
  12168. * - **RegExp** (*see caveat below*)
  12169. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12170. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12171. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12172. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12173. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12174. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12175. * is highly recommended to use the string patterns and only fall back to regular expressions
  12176. * if they as a last resort.
  12177. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12178. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12179. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12180. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12181. * - If you are generating your JavaScript from some other templating engine (not
  12182. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12183. * remember to escape your regular expression (and be aware that you might need more than
  12184. * one level of escaping depending on your templating engine and the way you interpolated
  12185. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12186. * enough before coding your own. e.g. Ruby has
  12187. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12188. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12189. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12190. * Closure library's [goog.string.regExpEscape(s)](
  12191. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12192. *
  12193. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12194. *
  12195. * ## Show me an example using SCE.
  12196. *
  12197. * @example
  12198. <example module="mySceApp" deps="angular-sanitize.js">
  12199. <file name="index.html">
  12200. <div ng-controller="myAppController as myCtrl">
  12201. <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12202. <b>User comments</b><br>
  12203. By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12204. $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12205. exploit.
  12206. <div class="well">
  12207. <div ng-repeat="userComment in myCtrl.userComments">
  12208. <b>{{userComment.name}}</b>:
  12209. <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12210. <br>
  12211. </div>
  12212. </div>
  12213. </div>
  12214. </file>
  12215. <file name="script.js">
  12216. var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12217. mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12218. var self = this;
  12219. $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12220. self.userComments = userComments;
  12221. });
  12222. self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12223. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12224. 'sanitization.&quot;">Hover over this text.</span>');
  12225. });
  12226. </file>
  12227. <file name="test_data.json">
  12228. [
  12229. { "name": "Alice",
  12230. "htmlComment":
  12231. "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12232. },
  12233. { "name": "Bob",
  12234. "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12235. }
  12236. ]
  12237. </file>
  12238. <file name="protractor.js" type="protractor">
  12239. describe('SCE doc demo', function() {
  12240. it('should sanitize untrusted values', function() {
  12241. expect(element(by.css('.htmlComment')).getInnerHtml())
  12242. .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12243. });
  12244. it('should NOT sanitize explicitly trusted values', function() {
  12245. expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12246. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12247. 'sanitization.&quot;">Hover over this text.</span>');
  12248. });
  12249. });
  12250. </file>
  12251. </example>
  12252. *
  12253. *
  12254. *
  12255. * ## Can I disable SCE completely?
  12256. *
  12257. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12258. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12259. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12260. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12261. * you're migrating them a module at a time.
  12262. *
  12263. * That said, here's how you can completely disable SCE:
  12264. *
  12265. * <pre class="prettyprint">
  12266. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12267. * // Completely disable SCE. For demonstration purposes only!
  12268. * // Do not use in new projects.
  12269. * $sceProvider.enabled(false);
  12270. * });
  12271. * </pre>
  12272. *
  12273. */
  12274. /* jshint maxlen: 100 */
  12275. function $SceProvider() {
  12276. var enabled = true;
  12277. /**
  12278. * @ngdoc method
  12279. * @name $sceProvider#enabled
  12280. * @kind function
  12281. *
  12282. * @param {boolean=} value If provided, then enables/disables SCE.
  12283. * @return {boolean} true if SCE is enabled, false otherwise.
  12284. *
  12285. * @description
  12286. * Enables/disables SCE and returns the current value.
  12287. */
  12288. this.enabled = function (value) {
  12289. if (arguments.length) {
  12290. enabled = !!value;
  12291. }
  12292. return enabled;
  12293. };
  12294. /* Design notes on the default implementation for SCE.
  12295. *
  12296. * The API contract for the SCE delegate
  12297. * -------------------------------------
  12298. * The SCE delegate object must provide the following 3 methods:
  12299. *
  12300. * - trustAs(contextEnum, value)
  12301. * This method is used to tell the SCE service that the provided value is OK to use in the
  12302. * contexts specified by contextEnum. It must return an object that will be accepted by
  12303. * getTrusted() for a compatible contextEnum and return this value.
  12304. *
  12305. * - valueOf(value)
  12306. * For values that were not produced by trustAs(), return them as is. For values that were
  12307. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12308. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12309. * such a value.
  12310. *
  12311. * - getTrusted(contextEnum, value)
  12312. * This function should return the a value that is safe to use in the context specified by
  12313. * contextEnum or throw and exception otherwise.
  12314. *
  12315. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12316. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12317. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12318. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12319. * return the same object passed in if it was found in the registry under a compatible context or
  12320. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12321. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12322. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12323. *
  12324. *
  12325. * A note on the inheritance model for SCE contexts
  12326. * ------------------------------------------------
  12327. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12328. * is purely an implementation details.
  12329. *
  12330. * The contract is simply this:
  12331. *
  12332. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12333. * will also succeed.
  12334. *
  12335. * Inheritance happens to capture this in a natural way. In some future, we
  12336. * may not use inheritance anymore. That is OK because no code outside of
  12337. * sce.js and sceSpecs.js would need to be aware of this detail.
  12338. */
  12339. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12340. $parse, $sniffer, $sceDelegate) {
  12341. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12342. // the "expression(javascript expression)" syntax which is insecure.
  12343. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12344. throw $sceMinErr('iequirks',
  12345. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12346. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12347. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12348. }
  12349. var sce = shallowCopy(SCE_CONTEXTS);
  12350. /**
  12351. * @ngdoc method
  12352. * @name $sce#isEnabled
  12353. * @kind function
  12354. *
  12355. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12356. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12357. *
  12358. * @description
  12359. * Returns a boolean indicating if SCE is enabled.
  12360. */
  12361. sce.isEnabled = function () {
  12362. return enabled;
  12363. };
  12364. sce.trustAs = $sceDelegate.trustAs;
  12365. sce.getTrusted = $sceDelegate.getTrusted;
  12366. sce.valueOf = $sceDelegate.valueOf;
  12367. if (!enabled) {
  12368. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12369. sce.valueOf = identity;
  12370. }
  12371. /**
  12372. * @ngdoc method
  12373. * @name $sce#parse
  12374. *
  12375. * @description
  12376. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12377. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12378. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12379. * *result*)}
  12380. *
  12381. * @param {string} type The kind of SCE context in which this result will be used.
  12382. * @param {string} expression String expression to compile.
  12383. * @returns {function(context, locals)} a function which represents the compiled expression:
  12384. *
  12385. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12386. * are evaluated against (typically a scope object).
  12387. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12388. * `context`.
  12389. */
  12390. sce.parseAs = function sceParseAs(type, expr) {
  12391. var parsed = $parse(expr);
  12392. if (parsed.literal && parsed.constant) {
  12393. return parsed;
  12394. } else {
  12395. return function sceParseAsTrusted(self, locals) {
  12396. return sce.getTrusted(type, parsed(self, locals));
  12397. };
  12398. }
  12399. };
  12400. /**
  12401. * @ngdoc method
  12402. * @name $sce#trustAs
  12403. *
  12404. * @description
  12405. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12406. * returns an object that is trusted by angular for use in specified strict contextual
  12407. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12408. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12409. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12410. * escaping.
  12411. *
  12412. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12413. * resource_url, html, js and css.
  12414. * @param {*} value The value that that should be considered trusted/safe.
  12415. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12416. * where Angular expects a $sce.trustAs() return value.
  12417. */
  12418. /**
  12419. * @ngdoc method
  12420. * @name $sce#trustAsHtml
  12421. *
  12422. * @description
  12423. * Shorthand method. `$sce.trustAsHtml(value)` →
  12424. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12425. *
  12426. * @param {*} value The value to trustAs.
  12427. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12428. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12429. * only accept expressions that are either literal constants or are the
  12430. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12431. */
  12432. /**
  12433. * @ngdoc method
  12434. * @name $sce#trustAsUrl
  12435. *
  12436. * @description
  12437. * Shorthand method. `$sce.trustAsUrl(value)` →
  12438. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12439. *
  12440. * @param {*} value The value to trustAs.
  12441. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12442. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12443. * only accept expressions that are either literal constants or are the
  12444. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12445. */
  12446. /**
  12447. * @ngdoc method
  12448. * @name $sce#trustAsResourceUrl
  12449. *
  12450. * @description
  12451. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12452. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12453. *
  12454. * @param {*} value The value to trustAs.
  12455. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12456. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12457. * only accept expressions that are either literal constants or are the return
  12458. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12459. */
  12460. /**
  12461. * @ngdoc method
  12462. * @name $sce#trustAsJs
  12463. *
  12464. * @description
  12465. * Shorthand method. `$sce.trustAsJs(value)` →
  12466. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12467. *
  12468. * @param {*} value The value to trustAs.
  12469. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12470. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12471. * only accept expressions that are either literal constants or are the
  12472. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12473. */
  12474. /**
  12475. * @ngdoc method
  12476. * @name $sce#getTrusted
  12477. *
  12478. * @description
  12479. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12480. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12481. * originally supplied value if the queried context type is a supertype of the created type.
  12482. * If this condition isn't satisfied, throws an exception.
  12483. *
  12484. * @param {string} type The kind of context in which this value is to be used.
  12485. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12486. * call.
  12487. * @returns {*} The value the was originally provided to
  12488. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12489. * Otherwise, throws an exception.
  12490. */
  12491. /**
  12492. * @ngdoc method
  12493. * @name $sce#getTrustedHtml
  12494. *
  12495. * @description
  12496. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12497. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12498. *
  12499. * @param {*} value The value to pass to `$sce.getTrusted`.
  12500. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12501. */
  12502. /**
  12503. * @ngdoc method
  12504. * @name $sce#getTrustedCss
  12505. *
  12506. * @description
  12507. * Shorthand method. `$sce.getTrustedCss(value)` →
  12508. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12509. *
  12510. * @param {*} value The value to pass to `$sce.getTrusted`.
  12511. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12512. */
  12513. /**
  12514. * @ngdoc method
  12515. * @name $sce#getTrustedUrl
  12516. *
  12517. * @description
  12518. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12519. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12520. *
  12521. * @param {*} value The value to pass to `$sce.getTrusted`.
  12522. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12523. */
  12524. /**
  12525. * @ngdoc method
  12526. * @name $sce#getTrustedResourceUrl
  12527. *
  12528. * @description
  12529. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12530. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12531. *
  12532. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12533. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12534. */
  12535. /**
  12536. * @ngdoc method
  12537. * @name $sce#getTrustedJs
  12538. *
  12539. * @description
  12540. * Shorthand method. `$sce.getTrustedJs(value)` →
  12541. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12542. *
  12543. * @param {*} value The value to pass to `$sce.getTrusted`.
  12544. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12545. */
  12546. /**
  12547. * @ngdoc method
  12548. * @name $sce#parseAsHtml
  12549. *
  12550. * @description
  12551. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12552. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12553. *
  12554. * @param {string} expression String expression to compile.
  12555. * @returns {function(context, locals)} a function which represents the compiled expression:
  12556. *
  12557. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12558. * are evaluated against (typically a scope object).
  12559. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12560. * `context`.
  12561. */
  12562. /**
  12563. * @ngdoc method
  12564. * @name $sce#parseAsCss
  12565. *
  12566. * @description
  12567. * Shorthand method. `$sce.parseAsCss(value)` →
  12568. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12569. *
  12570. * @param {string} expression String expression to compile.
  12571. * @returns {function(context, locals)} a function which represents the compiled expression:
  12572. *
  12573. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12574. * are evaluated against (typically a scope object).
  12575. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12576. * `context`.
  12577. */
  12578. /**
  12579. * @ngdoc method
  12580. * @name $sce#parseAsUrl
  12581. *
  12582. * @description
  12583. * Shorthand method. `$sce.parseAsUrl(value)` →
  12584. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12585. *
  12586. * @param {string} expression String expression to compile.
  12587. * @returns {function(context, locals)} a function which represents the compiled expression:
  12588. *
  12589. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12590. * are evaluated against (typically a scope object).
  12591. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12592. * `context`.
  12593. */
  12594. /**
  12595. * @ngdoc method
  12596. * @name $sce#parseAsResourceUrl
  12597. *
  12598. * @description
  12599. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12600. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12601. *
  12602. * @param {string} expression String expression to compile.
  12603. * @returns {function(context, locals)} a function which represents the compiled expression:
  12604. *
  12605. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12606. * are evaluated against (typically a scope object).
  12607. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12608. * `context`.
  12609. */
  12610. /**
  12611. * @ngdoc method
  12612. * @name $sce#parseAsJs
  12613. *
  12614. * @description
  12615. * Shorthand method. `$sce.parseAsJs(value)` →
  12616. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12617. *
  12618. * @param {string} expression String expression to compile.
  12619. * @returns {function(context, locals)} a function which represents the compiled expression:
  12620. *
  12621. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12622. * are evaluated against (typically a scope object).
  12623. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12624. * `context`.
  12625. */
  12626. // Shorthand delegations.
  12627. var parse = sce.parseAs,
  12628. getTrusted = sce.getTrusted,
  12629. trustAs = sce.trustAs;
  12630. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12631. var lName = lowercase(name);
  12632. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12633. return parse(enumValue, expr);
  12634. };
  12635. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12636. return getTrusted(enumValue, value);
  12637. };
  12638. sce[camelCase("trust_as_" + lName)] = function (value) {
  12639. return trustAs(enumValue, value);
  12640. };
  12641. });
  12642. return sce;
  12643. }];
  12644. }
  12645. /**
  12646. * !!! This is an undocumented "private" service !!!
  12647. *
  12648. * @name $sniffer
  12649. * @requires $window
  12650. * @requires $document
  12651. *
  12652. * @property {boolean} history Does the browser support html5 history api ?
  12653. * @property {boolean} hashchange Does the browser support hashchange event ?
  12654. * @property {boolean} transitions Does the browser support CSS transition events ?
  12655. * @property {boolean} animations Does the browser support CSS animation events ?
  12656. *
  12657. * @description
  12658. * This is very simple implementation of testing browser's features.
  12659. */
  12660. function $SnifferProvider() {
  12661. this.$get = ['$window', '$document', function($window, $document) {
  12662. var eventSupport = {},
  12663. android =
  12664. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12665. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12666. document = $document[0] || {},
  12667. documentMode = document.documentMode,
  12668. vendorPrefix,
  12669. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12670. bodyStyle = document.body && document.body.style,
  12671. transitions = false,
  12672. animations = false,
  12673. match;
  12674. if (bodyStyle) {
  12675. for(var prop in bodyStyle) {
  12676. if(match = vendorRegex.exec(prop)) {
  12677. vendorPrefix = match[0];
  12678. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12679. break;
  12680. }
  12681. }
  12682. if(!vendorPrefix) {
  12683. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12684. }
  12685. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12686. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12687. if (android && (!transitions||!animations)) {
  12688. transitions = isString(document.body.style.webkitTransition);
  12689. animations = isString(document.body.style.webkitAnimation);
  12690. }
  12691. }
  12692. return {
  12693. // Android has history.pushState, but it does not update location correctly
  12694. // so let's not use the history API at all.
  12695. // http://code.google.com/p/android/issues/detail?id=17471
  12696. // https://github.com/angular/angular.js/issues/904
  12697. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12698. // so let's not use the history API also
  12699. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12700. // jshint -W018
  12701. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12702. // jshint +W018
  12703. hashchange: 'onhashchange' in $window &&
  12704. // IE8 compatible mode lies
  12705. (!documentMode || documentMode > 7),
  12706. hasEvent: function(event) {
  12707. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12708. // it. In particular the event is not fired when backspace or delete key are pressed or
  12709. // when cut operation is performed.
  12710. if (event == 'input' && msie == 9) return false;
  12711. if (isUndefined(eventSupport[event])) {
  12712. var divElm = document.createElement('div');
  12713. eventSupport[event] = 'on' + event in divElm;
  12714. }
  12715. return eventSupport[event];
  12716. },
  12717. csp: csp(),
  12718. vendorPrefix: vendorPrefix,
  12719. transitions : transitions,
  12720. animations : animations,
  12721. android: android,
  12722. msie : msie,
  12723. msieDocumentMode: documentMode
  12724. };
  12725. }];
  12726. }
  12727. function $TimeoutProvider() {
  12728. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12729. function($rootScope, $browser, $q, $exceptionHandler) {
  12730. var deferreds = {};
  12731. /**
  12732. * @ngdoc service
  12733. * @name $timeout
  12734. *
  12735. * @description
  12736. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12737. * block and delegates any exceptions to
  12738. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12739. *
  12740. * The return value of registering a timeout function is a promise, which will be resolved when
  12741. * the timeout is reached and the timeout function is executed.
  12742. *
  12743. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  12744. *
  12745. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  12746. * synchronously flush the queue of deferred functions.
  12747. *
  12748. * @param {function()} fn A function, whose execution should be delayed.
  12749. * @param {number=} [delay=0] Delay in milliseconds.
  12750. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12751. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12752. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  12753. * promise will be resolved with is the return value of the `fn` function.
  12754. *
  12755. */
  12756. function timeout(fn, delay, invokeApply) {
  12757. var deferred = $q.defer(),
  12758. promise = deferred.promise,
  12759. skipApply = (isDefined(invokeApply) && !invokeApply),
  12760. timeoutId;
  12761. timeoutId = $browser.defer(function() {
  12762. try {
  12763. deferred.resolve(fn());
  12764. } catch(e) {
  12765. deferred.reject(e);
  12766. $exceptionHandler(e);
  12767. }
  12768. finally {
  12769. delete deferreds[promise.$$timeoutId];
  12770. }
  12771. if (!skipApply) $rootScope.$apply();
  12772. }, delay);
  12773. promise.$$timeoutId = timeoutId;
  12774. deferreds[timeoutId] = deferred;
  12775. return promise;
  12776. }
  12777. /**
  12778. * @ngdoc method
  12779. * @name $timeout#cancel
  12780. *
  12781. * @description
  12782. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  12783. * resolved with a rejection.
  12784. *
  12785. * @param {Promise=} promise Promise returned by the `$timeout` function.
  12786. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  12787. * canceled.
  12788. */
  12789. timeout.cancel = function(promise) {
  12790. if (promise && promise.$$timeoutId in deferreds) {
  12791. deferreds[promise.$$timeoutId].reject('canceled');
  12792. delete deferreds[promise.$$timeoutId];
  12793. return $browser.defer.cancel(promise.$$timeoutId);
  12794. }
  12795. return false;
  12796. };
  12797. return timeout;
  12798. }];
  12799. }
  12800. // NOTE: The usage of window and document instead of $window and $document here is
  12801. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  12802. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  12803. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  12804. // doesn't know about mocked locations and resolves URLs to the real document - which is
  12805. // exactly the behavior needed here. There is little value is mocking these out for this
  12806. // service.
  12807. var urlParsingNode = document.createElement("a");
  12808. var originUrl = urlResolve(window.location.href, true);
  12809. /**
  12810. *
  12811. * Implementation Notes for non-IE browsers
  12812. * ----------------------------------------
  12813. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  12814. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  12815. * URL will be resolved into an absolute URL in the context of the application document.
  12816. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  12817. * properties are all populated to reflect the normalized URL. This approach has wide
  12818. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  12819. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12820. *
  12821. * Implementation Notes for IE
  12822. * ---------------------------
  12823. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  12824. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  12825. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  12826. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  12827. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  12828. * properties such as protocol, hostname, port, etc.
  12829. *
  12830. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  12831. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  12832. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  12833. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  12834. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  12835. * method and IE < 8 is unsupported.
  12836. *
  12837. * References:
  12838. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  12839. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12840. * http://url.spec.whatwg.org/#urlutils
  12841. * https://github.com/angular/angular.js/pull/2902
  12842. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  12843. *
  12844. * @kind function
  12845. * @param {string} url The URL to be parsed.
  12846. * @description Normalizes and parses a URL.
  12847. * @returns {object} Returns the normalized URL as a dictionary.
  12848. *
  12849. * | member name | Description |
  12850. * |---------------|----------------|
  12851. * | href | A normalized version of the provided URL if it was not an absolute URL |
  12852. * | protocol | The protocol including the trailing colon |
  12853. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  12854. * | search | The search params, minus the question mark |
  12855. * | hash | The hash string, minus the hash symbol
  12856. * | hostname | The hostname
  12857. * | port | The port, without ":"
  12858. * | pathname | The pathname, beginning with "/"
  12859. *
  12860. */
  12861. function urlResolve(url, base) {
  12862. var href = url;
  12863. if (msie) {
  12864. // Normalize before parse. Refer Implementation Notes on why this is
  12865. // done in two steps on IE.
  12866. urlParsingNode.setAttribute("href", href);
  12867. href = urlParsingNode.href;
  12868. }
  12869. urlParsingNode.setAttribute('href', href);
  12870. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  12871. return {
  12872. href: urlParsingNode.href,
  12873. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  12874. host: urlParsingNode.host,
  12875. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  12876. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  12877. hostname: urlParsingNode.hostname,
  12878. port: urlParsingNode.port,
  12879. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  12880. ? urlParsingNode.pathname
  12881. : '/' + urlParsingNode.pathname
  12882. };
  12883. }
  12884. /**
  12885. * Parse a request URL and determine whether this is a same-origin request as the application document.
  12886. *
  12887. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  12888. * or a parsed URL object.
  12889. * @returns {boolean} Whether the request is for the same origin as the application document.
  12890. */
  12891. function urlIsSameOrigin(requestUrl) {
  12892. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  12893. return (parsed.protocol === originUrl.protocol &&
  12894. parsed.host === originUrl.host);
  12895. }
  12896. /**
  12897. * @ngdoc service
  12898. * @name $window
  12899. *
  12900. * @description
  12901. * A reference to the browser's `window` object. While `window`
  12902. * is globally available in JavaScript, it causes testability problems, because
  12903. * it is a global variable. In angular we always refer to it through the
  12904. * `$window` service, so it may be overridden, removed or mocked for testing.
  12905. *
  12906. * Expressions, like the one defined for the `ngClick` directive in the example
  12907. * below, are evaluated with respect to the current scope. Therefore, there is
  12908. * no risk of inadvertently coding in a dependency on a global value in such an
  12909. * expression.
  12910. *
  12911. * @example
  12912. <example>
  12913. <file name="index.html">
  12914. <script>
  12915. function Ctrl($scope, $window) {
  12916. $scope.greeting = 'Hello, World!';
  12917. $scope.doGreeting = function(greeting) {
  12918. $window.alert(greeting);
  12919. };
  12920. }
  12921. </script>
  12922. <div ng-controller="Ctrl">
  12923. <input type="text" ng-model="greeting" />
  12924. <button ng-click="doGreeting(greeting)">ALERT</button>
  12925. </div>
  12926. </file>
  12927. <file name="protractor.js" type="protractor">
  12928. it('should display the greeting in the input box', function() {
  12929. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  12930. // If we click the button it will block the test runner
  12931. // element(':button').click();
  12932. });
  12933. </file>
  12934. </example>
  12935. */
  12936. function $WindowProvider(){
  12937. this.$get = valueFn(window);
  12938. }
  12939. /**
  12940. * @ngdoc provider
  12941. * @name $filterProvider
  12942. * @description
  12943. *
  12944. * Filters are just functions which transform input to an output. However filters need to be
  12945. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  12946. * annotated with dependencies and is responsible for creating a filter function.
  12947. *
  12948. * ```js
  12949. * // Filter registration
  12950. * function MyModule($provide, $filterProvider) {
  12951. * // create a service to demonstrate injection (not always needed)
  12952. * $provide.value('greet', function(name){
  12953. * return 'Hello ' + name + '!';
  12954. * });
  12955. *
  12956. * // register a filter factory which uses the
  12957. * // greet service to demonstrate DI.
  12958. * $filterProvider.register('greet', function(greet){
  12959. * // return the filter function which uses the greet service
  12960. * // to generate salutation
  12961. * return function(text) {
  12962. * // filters need to be forgiving so check input validity
  12963. * return text && greet(text) || text;
  12964. * };
  12965. * });
  12966. * }
  12967. * ```
  12968. *
  12969. * The filter function is registered with the `$injector` under the filter name suffix with
  12970. * `Filter`.
  12971. *
  12972. * ```js
  12973. * it('should be the same instance', inject(
  12974. * function($filterProvider) {
  12975. * $filterProvider.register('reverse', function(){
  12976. * return ...;
  12977. * });
  12978. * },
  12979. * function($filter, reverseFilter) {
  12980. * expect($filter('reverse')).toBe(reverseFilter);
  12981. * });
  12982. * ```
  12983. *
  12984. *
  12985. * For more information about how angular filters work, and how to create your own filters, see
  12986. * {@link guide/filter Filters} in the Angular Developer Guide.
  12987. */
  12988. /**
  12989. * @ngdoc method
  12990. * @name $filterProvider#register
  12991. * @description
  12992. * Register filter factory function.
  12993. *
  12994. * @param {String} name Name of the filter.
  12995. * @param {Function} fn The filter factory function which is injectable.
  12996. */
  12997. /**
  12998. * @ngdoc service
  12999. * @name $filter
  13000. * @kind function
  13001. * @description
  13002. * Filters are used for formatting data displayed to the user.
  13003. *
  13004. * The general syntax in templates is as follows:
  13005. *
  13006. * {{ expression [| filter_name[:parameter_value] ... ] }}
  13007. *
  13008. * @param {String} name Name of the filter function to retrieve
  13009. * @return {Function} the filter function
  13010. * @example
  13011. <example name="$filter" module="filterExample">
  13012. <file name="index.html">
  13013. <div ng-controller="MainCtrl">
  13014. <h3>{{ originalText }}</h3>
  13015. <h3>{{ filteredText }}</h3>
  13016. </div>
  13017. </file>
  13018. <file name="script.js">
  13019. angular.module('filterExample', [])
  13020. .controller('MainCtrl', function($scope, $filter) {
  13021. $scope.originalText = 'hello';
  13022. $scope.filteredText = $filter('uppercase')($scope.originalText);
  13023. });
  13024. </file>
  13025. </example>
  13026. */
  13027. $FilterProvider.$inject = ['$provide'];
  13028. function $FilterProvider($provide) {
  13029. var suffix = 'Filter';
  13030. /**
  13031. * @ngdoc method
  13032. * @name $controllerProvider#register
  13033. * @param {string|Object} name Name of the filter function, or an object map of filters where
  13034. * the keys are the filter names and the values are the filter factories.
  13035. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  13036. * of the registered filter instances.
  13037. */
  13038. function register(name, factory) {
  13039. if(isObject(name)) {
  13040. var filters = {};
  13041. forEach(name, function(filter, key) {
  13042. filters[key] = register(key, filter);
  13043. });
  13044. return filters;
  13045. } else {
  13046. return $provide.factory(name + suffix, factory);
  13047. }
  13048. }
  13049. this.register = register;
  13050. this.$get = ['$injector', function($injector) {
  13051. return function(name) {
  13052. return $injector.get(name + suffix);
  13053. };
  13054. }];
  13055. ////////////////////////////////////////
  13056. /* global
  13057. currencyFilter: false,
  13058. dateFilter: false,
  13059. filterFilter: false,
  13060. jsonFilter: false,
  13061. limitToFilter: false,
  13062. lowercaseFilter: false,
  13063. numberFilter: false,
  13064. orderByFilter: false,
  13065. uppercaseFilter: false,
  13066. */
  13067. register('currency', currencyFilter);
  13068. register('date', dateFilter);
  13069. register('filter', filterFilter);
  13070. register('json', jsonFilter);
  13071. register('limitTo', limitToFilter);
  13072. register('lowercase', lowercaseFilter);
  13073. register('number', numberFilter);
  13074. register('orderBy', orderByFilter);
  13075. register('uppercase', uppercaseFilter);
  13076. }
  13077. /**
  13078. * @ngdoc filter
  13079. * @name filter
  13080. * @kind function
  13081. *
  13082. * @description
  13083. * Selects a subset of items from `array` and returns it as a new array.
  13084. *
  13085. * @param {Array} array The source array.
  13086. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  13087. * `array`.
  13088. *
  13089. * Can be one of:
  13090. *
  13091. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  13092. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  13093. * will be returned. The predicate can be negated by prefixing the string with `!`.
  13094. *
  13095. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  13096. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  13097. * which have property `name` containing "M" and property `phone` containing "1". A special
  13098. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  13099. * property of the object. That's equivalent to the simple substring match with a `string`
  13100. * as described above.
  13101. *
  13102. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  13103. * called for each element of `array`. The final result is an array of those elements that
  13104. * the predicate returned true for.
  13105. *
  13106. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  13107. * determining if the expected value (from the filter expression) and actual value (from
  13108. * the object in the array) should be considered a match.
  13109. *
  13110. * Can be one of:
  13111. *
  13112. * - `function(actual, expected)`:
  13113. * The function will be given the object value and the predicate value to compare and
  13114. * should return true if the item should be included in filtered result.
  13115. *
  13116. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13117. * this is essentially strict comparison of expected and actual.
  13118. *
  13119. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13120. * insensitive way.
  13121. *
  13122. * @example
  13123. <example>
  13124. <file name="index.html">
  13125. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13126. {name:'Mary', phone:'800-BIG-MARY'},
  13127. {name:'Mike', phone:'555-4321'},
  13128. {name:'Adam', phone:'555-5678'},
  13129. {name:'Julie', phone:'555-8765'},
  13130. {name:'Juliette', phone:'555-5678'}]"></div>
  13131. Search: <input ng-model="searchText">
  13132. <table id="searchTextResults">
  13133. <tr><th>Name</th><th>Phone</th></tr>
  13134. <tr ng-repeat="friend in friends | filter:searchText">
  13135. <td>{{friend.name}}</td>
  13136. <td>{{friend.phone}}</td>
  13137. </tr>
  13138. </table>
  13139. <hr>
  13140. Any: <input ng-model="search.$"> <br>
  13141. Name only <input ng-model="search.name"><br>
  13142. Phone only <input ng-model="search.phone"><br>
  13143. Equality <input type="checkbox" ng-model="strict"><br>
  13144. <table id="searchObjResults">
  13145. <tr><th>Name</th><th>Phone</th></tr>
  13146. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13147. <td>{{friendObj.name}}</td>
  13148. <td>{{friendObj.phone}}</td>
  13149. </tr>
  13150. </table>
  13151. </file>
  13152. <file name="protractor.js" type="protractor">
  13153. var expectFriendNames = function(expectedNames, key) {
  13154. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13155. arr.forEach(function(wd, i) {
  13156. expect(wd.getText()).toMatch(expectedNames[i]);
  13157. });
  13158. });
  13159. };
  13160. it('should search across all fields when filtering with a string', function() {
  13161. var searchText = element(by.model('searchText'));
  13162. searchText.clear();
  13163. searchText.sendKeys('m');
  13164. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13165. searchText.clear();
  13166. searchText.sendKeys('76');
  13167. expectFriendNames(['John', 'Julie'], 'friend');
  13168. });
  13169. it('should search in specific fields when filtering with a predicate object', function() {
  13170. var searchAny = element(by.model('search.$'));
  13171. searchAny.clear();
  13172. searchAny.sendKeys('i');
  13173. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13174. });
  13175. it('should use a equal comparison when comparator is true', function() {
  13176. var searchName = element(by.model('search.name'));
  13177. var strict = element(by.model('strict'));
  13178. searchName.clear();
  13179. searchName.sendKeys('Julie');
  13180. strict.click();
  13181. expectFriendNames(['Julie'], 'friendObj');
  13182. });
  13183. </file>
  13184. </example>
  13185. */
  13186. function filterFilter() {
  13187. return function(array, expression, comparator) {
  13188. if (!isArray(array)) return array;
  13189. var comparatorType = typeof(comparator),
  13190. predicates = [];
  13191. predicates.check = function(value) {
  13192. for (var j = 0; j < predicates.length; j++) {
  13193. if(!predicates[j](value)) {
  13194. return false;
  13195. }
  13196. }
  13197. return true;
  13198. };
  13199. if (comparatorType !== 'function') {
  13200. if (comparatorType === 'boolean' && comparator) {
  13201. comparator = function(obj, text) {
  13202. return angular.equals(obj, text);
  13203. };
  13204. } else {
  13205. comparator = function(obj, text) {
  13206. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13207. for (var objKey in obj) {
  13208. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13209. comparator(obj[objKey], text[objKey])) {
  13210. return true;
  13211. }
  13212. }
  13213. return false;
  13214. }
  13215. text = (''+text).toLowerCase();
  13216. return (''+obj).toLowerCase().indexOf(text) > -1;
  13217. };
  13218. }
  13219. }
  13220. var search = function(obj, text){
  13221. if (typeof text == 'string' && text.charAt(0) === '!') {
  13222. return !search(obj, text.substr(1));
  13223. }
  13224. switch (typeof obj) {
  13225. case "boolean":
  13226. case "number":
  13227. case "string":
  13228. return comparator(obj, text);
  13229. case "object":
  13230. switch (typeof text) {
  13231. case "object":
  13232. return comparator(obj, text);
  13233. default:
  13234. for ( var objKey in obj) {
  13235. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13236. return true;
  13237. }
  13238. }
  13239. break;
  13240. }
  13241. return false;
  13242. case "array":
  13243. for ( var i = 0; i < obj.length; i++) {
  13244. if (search(obj[i], text)) {
  13245. return true;
  13246. }
  13247. }
  13248. return false;
  13249. default:
  13250. return false;
  13251. }
  13252. };
  13253. switch (typeof expression) {
  13254. case "boolean":
  13255. case "number":
  13256. case "string":
  13257. // Set up expression object and fall through
  13258. expression = {$:expression};
  13259. // jshint -W086
  13260. case "object":
  13261. // jshint +W086
  13262. for (var key in expression) {
  13263. (function(path) {
  13264. if (typeof expression[path] == 'undefined') return;
  13265. predicates.push(function(value) {
  13266. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13267. });
  13268. })(key);
  13269. }
  13270. break;
  13271. case 'function':
  13272. predicates.push(expression);
  13273. break;
  13274. default:
  13275. return array;
  13276. }
  13277. var filtered = [];
  13278. for ( var j = 0; j < array.length; j++) {
  13279. var value = array[j];
  13280. if (predicates.check(value)) {
  13281. filtered.push(value);
  13282. }
  13283. }
  13284. return filtered;
  13285. };
  13286. }
  13287. /**
  13288. * @ngdoc filter
  13289. * @name currency
  13290. * @kind function
  13291. *
  13292. * @description
  13293. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13294. * symbol for current locale is used.
  13295. *
  13296. * @param {number} amount Input to filter.
  13297. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13298. * @returns {string} Formatted number.
  13299. *
  13300. *
  13301. * @example
  13302. <example>
  13303. <file name="index.html">
  13304. <script>
  13305. function Ctrl($scope) {
  13306. $scope.amount = 1234.56;
  13307. }
  13308. </script>
  13309. <div ng-controller="Ctrl">
  13310. <input type="number" ng-model="amount"> <br>
  13311. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13312. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13313. </div>
  13314. </file>
  13315. <file name="protractor.js" type="protractor">
  13316. it('should init with 1234.56', function() {
  13317. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13318. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13319. });
  13320. it('should update', function() {
  13321. if (browser.params.browser == 'safari') {
  13322. // Safari does not understand the minus key. See
  13323. // https://github.com/angular/protractor/issues/481
  13324. return;
  13325. }
  13326. element(by.model('amount')).clear();
  13327. element(by.model('amount')).sendKeys('-1234');
  13328. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13329. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13330. });
  13331. </file>
  13332. </example>
  13333. */
  13334. currencyFilter.$inject = ['$locale'];
  13335. function currencyFilter($locale) {
  13336. var formats = $locale.NUMBER_FORMATS;
  13337. return function(amount, currencySymbol){
  13338. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13339. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13340. replace(/\u00A4/g, currencySymbol);
  13341. };
  13342. }
  13343. /**
  13344. * @ngdoc filter
  13345. * @name number
  13346. * @kind function
  13347. *
  13348. * @description
  13349. * Formats a number as text.
  13350. *
  13351. * If the input is not a number an empty string is returned.
  13352. *
  13353. * @param {number|string} number Number to format.
  13354. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13355. * If this is not provided then the fraction size is computed from the current locale's number
  13356. * formatting pattern. In the case of the default locale, it will be 3.
  13357. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13358. *
  13359. * @example
  13360. <example>
  13361. <file name="index.html">
  13362. <script>
  13363. function Ctrl($scope) {
  13364. $scope.val = 1234.56789;
  13365. }
  13366. </script>
  13367. <div ng-controller="Ctrl">
  13368. Enter number: <input ng-model='val'><br>
  13369. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13370. No fractions: <span>{{val | number:0}}</span><br>
  13371. Negative number: <span>{{-val | number:4}}</span>
  13372. </div>
  13373. </file>
  13374. <file name="protractor.js" type="protractor">
  13375. it('should format numbers', function() {
  13376. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13377. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13378. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13379. });
  13380. it('should update', function() {
  13381. element(by.model('val')).clear();
  13382. element(by.model('val')).sendKeys('3374.333');
  13383. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13384. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13385. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13386. });
  13387. </file>
  13388. </example>
  13389. */
  13390. numberFilter.$inject = ['$locale'];
  13391. function numberFilter($locale) {
  13392. var formats = $locale.NUMBER_FORMATS;
  13393. return function(number, fractionSize) {
  13394. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13395. fractionSize);
  13396. };
  13397. }
  13398. var DECIMAL_SEP = '.';
  13399. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13400. if (number == null || !isFinite(number) || isObject(number)) return '';
  13401. var isNegative = number < 0;
  13402. number = Math.abs(number);
  13403. var numStr = number + '',
  13404. formatedText = '',
  13405. parts = [];
  13406. var hasExponent = false;
  13407. if (numStr.indexOf('e') !== -1) {
  13408. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13409. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13410. numStr = '0';
  13411. } else {
  13412. formatedText = numStr;
  13413. hasExponent = true;
  13414. }
  13415. }
  13416. if (!hasExponent) {
  13417. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13418. // determine fractionSize if it is not specified
  13419. if (isUndefined(fractionSize)) {
  13420. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13421. }
  13422. var pow = Math.pow(10, fractionSize + 1);
  13423. number = Math.floor(number * pow + 5) / pow;
  13424. var fraction = ('' + number).split(DECIMAL_SEP);
  13425. var whole = fraction[0];
  13426. fraction = fraction[1] || '';
  13427. var i, pos = 0,
  13428. lgroup = pattern.lgSize,
  13429. group = pattern.gSize;
  13430. if (whole.length >= (lgroup + group)) {
  13431. pos = whole.length - lgroup;
  13432. for (i = 0; i < pos; i++) {
  13433. if ((pos - i)%group === 0 && i !== 0) {
  13434. formatedText += groupSep;
  13435. }
  13436. formatedText += whole.charAt(i);
  13437. }
  13438. }
  13439. for (i = pos; i < whole.length; i++) {
  13440. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13441. formatedText += groupSep;
  13442. }
  13443. formatedText += whole.charAt(i);
  13444. }
  13445. // format fraction part.
  13446. while(fraction.length < fractionSize) {
  13447. fraction += '0';
  13448. }
  13449. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13450. } else {
  13451. if (fractionSize > 0 && number > -1 && number < 1) {
  13452. formatedText = number.toFixed(fractionSize);
  13453. }
  13454. }
  13455. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13456. parts.push(formatedText);
  13457. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13458. return parts.join('');
  13459. }
  13460. function padNumber(num, digits, trim) {
  13461. var neg = '';
  13462. if (num < 0) {
  13463. neg = '-';
  13464. num = -num;
  13465. }
  13466. num = '' + num;
  13467. while(num.length < digits) num = '0' + num;
  13468. if (trim)
  13469. num = num.substr(num.length - digits);
  13470. return neg + num;
  13471. }
  13472. function dateGetter(name, size, offset, trim) {
  13473. offset = offset || 0;
  13474. return function(date) {
  13475. var value = date['get' + name]();
  13476. if (offset > 0 || value > -offset)
  13477. value += offset;
  13478. if (value === 0 && offset == -12 ) value = 12;
  13479. return padNumber(value, size, trim);
  13480. };
  13481. }
  13482. function dateStrGetter(name, shortForm) {
  13483. return function(date, formats) {
  13484. var value = date['get' + name]();
  13485. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13486. return formats[get][value];
  13487. };
  13488. }
  13489. function timeZoneGetter(date) {
  13490. var zone = -1 * date.getTimezoneOffset();
  13491. var paddedZone = (zone >= 0) ? "+" : "";
  13492. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13493. padNumber(Math.abs(zone % 60), 2);
  13494. return paddedZone;
  13495. }
  13496. function ampmGetter(date, formats) {
  13497. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13498. }
  13499. var DATE_FORMATS = {
  13500. yyyy: dateGetter('FullYear', 4),
  13501. yy: dateGetter('FullYear', 2, 0, true),
  13502. y: dateGetter('FullYear', 1),
  13503. MMMM: dateStrGetter('Month'),
  13504. MMM: dateStrGetter('Month', true),
  13505. MM: dateGetter('Month', 2, 1),
  13506. M: dateGetter('Month', 1, 1),
  13507. dd: dateGetter('Date', 2),
  13508. d: dateGetter('Date', 1),
  13509. HH: dateGetter('Hours', 2),
  13510. H: dateGetter('Hours', 1),
  13511. hh: dateGetter('Hours', 2, -12),
  13512. h: dateGetter('Hours', 1, -12),
  13513. mm: dateGetter('Minutes', 2),
  13514. m: dateGetter('Minutes', 1),
  13515. ss: dateGetter('Seconds', 2),
  13516. s: dateGetter('Seconds', 1),
  13517. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13518. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13519. sss: dateGetter('Milliseconds', 3),
  13520. EEEE: dateStrGetter('Day'),
  13521. EEE: dateStrGetter('Day', true),
  13522. a: ampmGetter,
  13523. Z: timeZoneGetter
  13524. };
  13525. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13526. NUMBER_STRING = /^\-?\d+$/;
  13527. /**
  13528. * @ngdoc filter
  13529. * @name date
  13530. * @kind function
  13531. *
  13532. * @description
  13533. * Formats `date` to a string based on the requested `format`.
  13534. *
  13535. * `format` string can be composed of the following elements:
  13536. *
  13537. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13538. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13539. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13540. * * `'MMMM'`: Month in year (January-December)
  13541. * * `'MMM'`: Month in year (Jan-Dec)
  13542. * * `'MM'`: Month in year, padded (01-12)
  13543. * * `'M'`: Month in year (1-12)
  13544. * * `'dd'`: Day in month, padded (01-31)
  13545. * * `'d'`: Day in month (1-31)
  13546. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13547. * * `'EEE'`: Day in Week, (Sun-Sat)
  13548. * * `'HH'`: Hour in day, padded (00-23)
  13549. * * `'H'`: Hour in day (0-23)
  13550. * * `'hh'`: Hour in am/pm, padded (01-12)
  13551. * * `'h'`: Hour in am/pm, (1-12)
  13552. * * `'mm'`: Minute in hour, padded (00-59)
  13553. * * `'m'`: Minute in hour (0-59)
  13554. * * `'ss'`: Second in minute, padded (00-59)
  13555. * * `'s'`: Second in minute (0-59)
  13556. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13557. * * `'a'`: am/pm marker
  13558. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13559. *
  13560. * `format` string can also be one of the following predefined
  13561. * {@link guide/i18n localizable formats}:
  13562. *
  13563. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13564. * (e.g. Sep 3, 2010 12:05:08 pm)
  13565. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13566. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13567. * (e.g. Friday, September 3, 2010)
  13568. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13569. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13570. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13571. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13572. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13573. *
  13574. * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
  13575. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
  13576. * (e.g. `"h 'o''clock'"`).
  13577. *
  13578. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13579. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
  13580. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13581. * specified in the string input, the time is considered to be in the local timezone.
  13582. * @param {string=} format Formatting rules (see Description). If not specified,
  13583. * `mediumDate` is used.
  13584. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13585. *
  13586. * @example
  13587. <example>
  13588. <file name="index.html">
  13589. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13590. <span>{{1288323623006 | date:'medium'}}</span><br>
  13591. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13592. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13593. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13594. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13595. </file>
  13596. <file name="protractor.js" type="protractor">
  13597. it('should format date', function() {
  13598. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13599. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13600. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13601. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13602. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13603. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13604. });
  13605. </file>
  13606. </example>
  13607. */
  13608. dateFilter.$inject = ['$locale'];
  13609. function dateFilter($locale) {
  13610. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13611. // 1 2 3 4 5 6 7 8 9 10 11
  13612. function jsonStringToDate(string) {
  13613. var match;
  13614. if (match = string.match(R_ISO8601_STR)) {
  13615. var date = new Date(0),
  13616. tzHour = 0,
  13617. tzMin = 0,
  13618. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13619. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13620. if (match[9]) {
  13621. tzHour = int(match[9] + match[10]);
  13622. tzMin = int(match[9] + match[11]);
  13623. }
  13624. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13625. var h = int(match[4]||0) - tzHour;
  13626. var m = int(match[5]||0) - tzMin;
  13627. var s = int(match[6]||0);
  13628. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13629. timeSetter.call(date, h, m, s, ms);
  13630. return date;
  13631. }
  13632. return string;
  13633. }
  13634. return function(date, format) {
  13635. var text = '',
  13636. parts = [],
  13637. fn, match;
  13638. format = format || 'mediumDate';
  13639. format = $locale.DATETIME_FORMATS[format] || format;
  13640. if (isString(date)) {
  13641. if (NUMBER_STRING.test(date)) {
  13642. date = int(date);
  13643. } else {
  13644. date = jsonStringToDate(date);
  13645. }
  13646. }
  13647. if (isNumber(date)) {
  13648. date = new Date(date);
  13649. }
  13650. if (!isDate(date)) {
  13651. return date;
  13652. }
  13653. while(format) {
  13654. match = DATE_FORMATS_SPLIT.exec(format);
  13655. if (match) {
  13656. parts = concat(parts, match, 1);
  13657. format = parts.pop();
  13658. } else {
  13659. parts.push(format);
  13660. format = null;
  13661. }
  13662. }
  13663. forEach(parts, function(value){
  13664. fn = DATE_FORMATS[value];
  13665. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13666. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13667. });
  13668. return text;
  13669. };
  13670. }
  13671. /**
  13672. * @ngdoc filter
  13673. * @name json
  13674. * @kind function
  13675. *
  13676. * @description
  13677. * Allows you to convert a JavaScript object into JSON string.
  13678. *
  13679. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13680. * the binding is automatically converted to JSON.
  13681. *
  13682. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13683. * @returns {string} JSON string.
  13684. *
  13685. *
  13686. * @example
  13687. <example>
  13688. <file name="index.html">
  13689. <pre>{{ {'name':'value'} | json }}</pre>
  13690. </file>
  13691. <file name="protractor.js" type="protractor">
  13692. it('should jsonify filtered objects', function() {
  13693. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  13694. });
  13695. </file>
  13696. </example>
  13697. *
  13698. */
  13699. function jsonFilter() {
  13700. return function(object) {
  13701. return toJson(object, true);
  13702. };
  13703. }
  13704. /**
  13705. * @ngdoc filter
  13706. * @name lowercase
  13707. * @kind function
  13708. * @description
  13709. * Converts string to lowercase.
  13710. * @see angular.lowercase
  13711. */
  13712. var lowercaseFilter = valueFn(lowercase);
  13713. /**
  13714. * @ngdoc filter
  13715. * @name uppercase
  13716. * @kind function
  13717. * @description
  13718. * Converts string to uppercase.
  13719. * @see angular.uppercase
  13720. */
  13721. var uppercaseFilter = valueFn(uppercase);
  13722. /**
  13723. * @ngdoc filter
  13724. * @name limitTo
  13725. * @kind function
  13726. *
  13727. * @description
  13728. * Creates a new array or string containing only a specified number of elements. The elements
  13729. * are taken from either the beginning or the end of the source array or string, as specified by
  13730. * the value and sign (positive or negative) of `limit`.
  13731. *
  13732. * @param {Array|string} input Source array or string to be limited.
  13733. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  13734. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  13735. * If the number is negative, `limit` number of items from the end of the source array/string
  13736. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  13737. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  13738. * had less than `limit` elements.
  13739. *
  13740. * @example
  13741. <example>
  13742. <file name="index.html">
  13743. <script>
  13744. function Ctrl($scope) {
  13745. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  13746. $scope.letters = "abcdefghi";
  13747. $scope.numLimit = 3;
  13748. $scope.letterLimit = 3;
  13749. }
  13750. </script>
  13751. <div ng-controller="Ctrl">
  13752. Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
  13753. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  13754. Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
  13755. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  13756. </div>
  13757. </file>
  13758. <file name="protractor.js" type="protractor">
  13759. var numLimitInput = element(by.model('numLimit'));
  13760. var letterLimitInput = element(by.model('letterLimit'));
  13761. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  13762. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  13763. it('should limit the number array to first three items', function() {
  13764. expect(numLimitInput.getAttribute('value')).toBe('3');
  13765. expect(letterLimitInput.getAttribute('value')).toBe('3');
  13766. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  13767. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  13768. });
  13769. it('should update the output when -3 is entered', function() {
  13770. numLimitInput.clear();
  13771. numLimitInput.sendKeys('-3');
  13772. letterLimitInput.clear();
  13773. letterLimitInput.sendKeys('-3');
  13774. expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  13775. expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  13776. });
  13777. it('should not exceed the maximum size of input array', function() {
  13778. numLimitInput.clear();
  13779. numLimitInput.sendKeys('100');
  13780. letterLimitInput.clear();
  13781. letterLimitInput.sendKeys('100');
  13782. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  13783. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  13784. });
  13785. </file>
  13786. </example>
  13787. */
  13788. function limitToFilter(){
  13789. return function(input, limit) {
  13790. if (!isArray(input) && !isString(input)) return input;
  13791. if (Math.abs(Number(limit)) === Infinity) {
  13792. limit = Number(limit);
  13793. } else {
  13794. limit = int(limit);
  13795. }
  13796. if (isString(input)) {
  13797. //NaN check on limit
  13798. if (limit) {
  13799. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  13800. } else {
  13801. return "";
  13802. }
  13803. }
  13804. var out = [],
  13805. i, n;
  13806. // if abs(limit) exceeds maximum length, trim it
  13807. if (limit > input.length)
  13808. limit = input.length;
  13809. else if (limit < -input.length)
  13810. limit = -input.length;
  13811. if (limit > 0) {
  13812. i = 0;
  13813. n = limit;
  13814. } else {
  13815. i = input.length + limit;
  13816. n = input.length;
  13817. }
  13818. for (; i<n; i++) {
  13819. out.push(input[i]);
  13820. }
  13821. return out;
  13822. };
  13823. }
  13824. /**
  13825. * @ngdoc filter
  13826. * @name orderBy
  13827. * @kind function
  13828. *
  13829. * @description
  13830. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  13831. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  13832. * correctly, make sure they are actually being saved as numbers and not strings.
  13833. *
  13834. * @param {Array} array The array to sort.
  13835. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
  13836. * used by the comparator to determine the order of elements.
  13837. *
  13838. * Can be one of:
  13839. *
  13840. * - `function`: Getter function. The result of this function will be sorted using the
  13841. * `<`, `=`, `>` operator.
  13842. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
  13843. * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
  13844. * ascending or descending sort order (for example, +name or -name).
  13845. * - `Array`: An array of function or string predicates. The first predicate in the array
  13846. * is used for sorting, but when two items are equivalent, the next predicate is used.
  13847. *
  13848. * @param {boolean=} reverse Reverse the order of the array.
  13849. * @returns {Array} Sorted copy of the source array.
  13850. *
  13851. * @example
  13852. <example>
  13853. <file name="index.html">
  13854. <script>
  13855. function Ctrl($scope) {
  13856. $scope.friends =
  13857. [{name:'John', phone:'555-1212', age:10},
  13858. {name:'Mary', phone:'555-9876', age:19},
  13859. {name:'Mike', phone:'555-4321', age:21},
  13860. {name:'Adam', phone:'555-5678', age:35},
  13861. {name:'Julie', phone:'555-8765', age:29}]
  13862. $scope.predicate = '-age';
  13863. }
  13864. </script>
  13865. <div ng-controller="Ctrl">
  13866. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  13867. <hr/>
  13868. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  13869. <table class="friend">
  13870. <tr>
  13871. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  13872. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  13873. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  13874. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  13875. </tr>
  13876. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  13877. <td>{{friend.name}}</td>
  13878. <td>{{friend.phone}}</td>
  13879. <td>{{friend.age}}</td>
  13880. </tr>
  13881. </table>
  13882. </div>
  13883. </file>
  13884. </example>
  13885. *
  13886. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  13887. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  13888. * desired parameters.
  13889. *
  13890. * Example:
  13891. *
  13892. * @example
  13893. <example>
  13894. <file name="index.html">
  13895. <div ng-controller="Ctrl">
  13896. <table class="friend">
  13897. <tr>
  13898. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  13899. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  13900. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  13901. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  13902. </tr>
  13903. <tr ng-repeat="friend in friends">
  13904. <td>{{friend.name}}</td>
  13905. <td>{{friend.phone}}</td>
  13906. <td>{{friend.age}}</td>
  13907. </tr>
  13908. </table>
  13909. </div>
  13910. </file>
  13911. <file name="script.js">
  13912. function Ctrl($scope, $filter) {
  13913. var orderBy = $filter('orderBy');
  13914. $scope.friends = [
  13915. { name: 'John', phone: '555-1212', age: 10 },
  13916. { name: 'Mary', phone: '555-9876', age: 19 },
  13917. { name: 'Mike', phone: '555-4321', age: 21 },
  13918. { name: 'Adam', phone: '555-5678', age: 35 },
  13919. { name: 'Julie', phone: '555-8765', age: 29 }
  13920. ];
  13921. $scope.order = function(predicate, reverse) {
  13922. $scope.friends = orderBy($scope.friends, predicate, reverse);
  13923. };
  13924. $scope.order('-age',false);
  13925. }
  13926. </file>
  13927. </example>
  13928. */
  13929. orderByFilter.$inject = ['$parse'];
  13930. function orderByFilter($parse){
  13931. return function(array, sortPredicate, reverseOrder) {
  13932. if (!isArray(array)) return array;
  13933. if (!sortPredicate) return array;
  13934. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  13935. sortPredicate = map(sortPredicate, function(predicate){
  13936. var descending = false, get = predicate || identity;
  13937. if (isString(predicate)) {
  13938. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  13939. descending = predicate.charAt(0) == '-';
  13940. predicate = predicate.substring(1);
  13941. }
  13942. get = $parse(predicate);
  13943. if (get.constant) {
  13944. var key = get();
  13945. return reverseComparator(function(a,b) {
  13946. return compare(a[key], b[key]);
  13947. }, descending);
  13948. }
  13949. }
  13950. return reverseComparator(function(a,b){
  13951. return compare(get(a),get(b));
  13952. }, descending);
  13953. });
  13954. var arrayCopy = [];
  13955. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  13956. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  13957. function comparator(o1, o2){
  13958. for ( var i = 0; i < sortPredicate.length; i++) {
  13959. var comp = sortPredicate[i](o1, o2);
  13960. if (comp !== 0) return comp;
  13961. }
  13962. return 0;
  13963. }
  13964. function reverseComparator(comp, descending) {
  13965. return toBoolean(descending)
  13966. ? function(a,b){return comp(b,a);}
  13967. : comp;
  13968. }
  13969. function compare(v1, v2){
  13970. var t1 = typeof v1;
  13971. var t2 = typeof v2;
  13972. if (t1 == t2) {
  13973. if (t1 == "string") {
  13974. v1 = v1.toLowerCase();
  13975. v2 = v2.toLowerCase();
  13976. }
  13977. if (v1 === v2) return 0;
  13978. return v1 < v2 ? -1 : 1;
  13979. } else {
  13980. return t1 < t2 ? -1 : 1;
  13981. }
  13982. }
  13983. };
  13984. }
  13985. function ngDirective(directive) {
  13986. if (isFunction(directive)) {
  13987. directive = {
  13988. link: directive
  13989. };
  13990. }
  13991. directive.restrict = directive.restrict || 'AC';
  13992. return valueFn(directive);
  13993. }
  13994. /**
  13995. * @ngdoc directive
  13996. * @name a
  13997. * @restrict E
  13998. *
  13999. * @description
  14000. * Modifies the default behavior of the html A tag so that the default action is prevented when
  14001. * the href attribute is empty.
  14002. *
  14003. * This change permits the easy creation of action links with the `ngClick` directive
  14004. * without changing the location or causing page reloads, e.g.:
  14005. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  14006. */
  14007. var htmlAnchorDirective = valueFn({
  14008. restrict: 'E',
  14009. compile: function(element, attr) {
  14010. if (msie <= 8) {
  14011. // turn <a href ng-click="..">link</a> into a stylable link in IE
  14012. // but only if it doesn't have name attribute, in which case it's an anchor
  14013. if (!attr.href && !attr.name) {
  14014. attr.$set('href', '');
  14015. }
  14016. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  14017. // to new attribute content if attribute is updated with value containing @ and element also
  14018. // contains value with @
  14019. // see issue #1949
  14020. element.append(document.createComment('IE fix'));
  14021. }
  14022. if (!attr.href && !attr.xlinkHref && !attr.name) {
  14023. return function(scope, element) {
  14024. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  14025. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  14026. 'xlink:href' : 'href';
  14027. element.on('click', function(event){
  14028. // if we have no href url, then don't navigate anywhere.
  14029. if (!element.attr(href)) {
  14030. event.preventDefault();
  14031. }
  14032. });
  14033. };
  14034. }
  14035. }
  14036. });
  14037. /**
  14038. * @ngdoc directive
  14039. * @name ngHref
  14040. * @restrict A
  14041. * @priority 99
  14042. *
  14043. * @description
  14044. * Using Angular markup like `{{hash}}` in an href attribute will
  14045. * make the link go to the wrong URL if the user clicks it before
  14046. * Angular has a chance to replace the `{{hash}}` markup with its
  14047. * value. Until Angular replaces the markup the link will be broken
  14048. * and will most likely return a 404 error.
  14049. *
  14050. * The `ngHref` directive solves this problem.
  14051. *
  14052. * The wrong way to write it:
  14053. * ```html
  14054. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  14055. * ```
  14056. *
  14057. * The correct way to write it:
  14058. * ```html
  14059. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  14060. * ```
  14061. *
  14062. * @element A
  14063. * @param {template} ngHref any string which can contain `{{}}` markup.
  14064. *
  14065. * @example
  14066. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  14067. * in links and their different behaviors:
  14068. <example>
  14069. <file name="index.html">
  14070. <input ng-model="value" /><br />
  14071. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  14072. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  14073. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  14074. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  14075. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  14076. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  14077. </file>
  14078. <file name="protractor.js" type="protractor">
  14079. it('should execute ng-click but not reload when href without value', function() {
  14080. element(by.id('link-1')).click();
  14081. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  14082. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  14083. });
  14084. it('should execute ng-click but not reload when href empty string', function() {
  14085. element(by.id('link-2')).click();
  14086. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  14087. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  14088. });
  14089. it('should execute ng-click and change url when ng-href specified', function() {
  14090. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  14091. element(by.id('link-3')).click();
  14092. // At this point, we navigate away from an Angular page, so we need
  14093. // to use browser.driver to get the base webdriver.
  14094. browser.wait(function() {
  14095. return browser.driver.getCurrentUrl().then(function(url) {
  14096. return url.match(/\/123$/);
  14097. });
  14098. }, 1000, 'page should navigate to /123');
  14099. });
  14100. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  14101. element(by.id('link-4')).click();
  14102. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  14103. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  14104. });
  14105. it('should execute ng-click but not reload when no href but name specified', function() {
  14106. element(by.id('link-5')).click();
  14107. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  14108. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  14109. });
  14110. it('should only change url when only ng-href', function() {
  14111. element(by.model('value')).clear();
  14112. element(by.model('value')).sendKeys('6');
  14113. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  14114. element(by.id('link-6')).click();
  14115. // At this point, we navigate away from an Angular page, so we need
  14116. // to use browser.driver to get the base webdriver.
  14117. browser.wait(function() {
  14118. return browser.driver.getCurrentUrl().then(function(url) {
  14119. return url.match(/\/6$/);
  14120. });
  14121. }, 1000, 'page should navigate to /6');
  14122. });
  14123. </file>
  14124. </example>
  14125. */
  14126. /**
  14127. * @ngdoc directive
  14128. * @name ngSrc
  14129. * @restrict A
  14130. * @priority 99
  14131. *
  14132. * @description
  14133. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  14134. * work right: The browser will fetch from the URL with the literal
  14135. * text `{{hash}}` until Angular replaces the expression inside
  14136. * `{{hash}}`. The `ngSrc` directive solves this problem.
  14137. *
  14138. * The buggy way to write it:
  14139. * ```html
  14140. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  14141. * ```
  14142. *
  14143. * The correct way to write it:
  14144. * ```html
  14145. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  14146. * ```
  14147. *
  14148. * @element IMG
  14149. * @param {template} ngSrc any string which can contain `{{}}` markup.
  14150. */
  14151. /**
  14152. * @ngdoc directive
  14153. * @name ngSrcset
  14154. * @restrict A
  14155. * @priority 99
  14156. *
  14157. * @description
  14158. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14159. * work right: The browser will fetch from the URL with the literal
  14160. * text `{{hash}}` until Angular replaces the expression inside
  14161. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14162. *
  14163. * The buggy way to write it:
  14164. * ```html
  14165. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14166. * ```
  14167. *
  14168. * The correct way to write it:
  14169. * ```html
  14170. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14171. * ```
  14172. *
  14173. * @element IMG
  14174. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14175. */
  14176. /**
  14177. * @ngdoc directive
  14178. * @name ngDisabled
  14179. * @restrict A
  14180. * @priority 100
  14181. *
  14182. * @description
  14183. *
  14184. * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14185. * ```html
  14186. * <div ng-init="scope = { isDisabled: false }">
  14187. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14188. * </div>
  14189. * ```
  14190. *
  14191. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14192. * such as disabled. (Their presence means true and their absence means false.)
  14193. * If we put an Angular interpolation expression into such an attribute then the
  14194. * binding information would be lost when the browser removes the attribute.
  14195. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14196. * This complementary directive is not removed by the browser and so provides
  14197. * a permanent reliable place to store the binding information.
  14198. *
  14199. * @example
  14200. <example>
  14201. <file name="index.html">
  14202. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14203. <button ng-model="button" ng-disabled="checked">Button</button>
  14204. </file>
  14205. <file name="protractor.js" type="protractor">
  14206. it('should toggle button', function() {
  14207. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14208. element(by.model('checked')).click();
  14209. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14210. });
  14211. </file>
  14212. </example>
  14213. *
  14214. * @element INPUT
  14215. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14216. * then special attribute "disabled" will be set on the element
  14217. */
  14218. /**
  14219. * @ngdoc directive
  14220. * @name ngChecked
  14221. * @restrict A
  14222. * @priority 100
  14223. *
  14224. * @description
  14225. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14226. * such as checked. (Their presence means true and their absence means false.)
  14227. * If we put an Angular interpolation expression into such an attribute then the
  14228. * binding information would be lost when the browser removes the attribute.
  14229. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14230. * This complementary directive is not removed by the browser and so provides
  14231. * a permanent reliable place to store the binding information.
  14232. * @example
  14233. <example>
  14234. <file name="index.html">
  14235. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14236. <input id="checkSlave" type="checkbox" ng-checked="master">
  14237. </file>
  14238. <file name="protractor.js" type="protractor">
  14239. it('should check both checkBoxes', function() {
  14240. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14241. element(by.model('master')).click();
  14242. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14243. });
  14244. </file>
  14245. </example>
  14246. *
  14247. * @element INPUT
  14248. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14249. * then special attribute "checked" will be set on the element
  14250. */
  14251. /**
  14252. * @ngdoc directive
  14253. * @name ngReadonly
  14254. * @restrict A
  14255. * @priority 100
  14256. *
  14257. * @description
  14258. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14259. * such as readonly. (Their presence means true and their absence means false.)
  14260. * If we put an Angular interpolation expression into such an attribute then the
  14261. * binding information would be lost when the browser removes the attribute.
  14262. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14263. * This complementary directive is not removed by the browser and so provides
  14264. * a permanent reliable place to store the binding information.
  14265. * @example
  14266. <example>
  14267. <file name="index.html">
  14268. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14269. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14270. </file>
  14271. <file name="protractor.js" type="protractor">
  14272. it('should toggle readonly attr', function() {
  14273. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14274. element(by.model('checked')).click();
  14275. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14276. });
  14277. </file>
  14278. </example>
  14279. *
  14280. * @element INPUT
  14281. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14282. * then special attribute "readonly" will be set on the element
  14283. */
  14284. /**
  14285. * @ngdoc directive
  14286. * @name ngSelected
  14287. * @restrict A
  14288. * @priority 100
  14289. *
  14290. * @description
  14291. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14292. * such as selected. (Their presence means true and their absence means false.)
  14293. * If we put an Angular interpolation expression into such an attribute then the
  14294. * binding information would be lost when the browser removes the attribute.
  14295. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14296. * This complementary directive is not removed by the browser and so provides
  14297. * a permanent reliable place to store the binding information.
  14298. *
  14299. * @example
  14300. <example>
  14301. <file name="index.html">
  14302. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14303. <select>
  14304. <option>Hello!</option>
  14305. <option id="greet" ng-selected="selected">Greetings!</option>
  14306. </select>
  14307. </file>
  14308. <file name="protractor.js" type="protractor">
  14309. it('should select Greetings!', function() {
  14310. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14311. element(by.model('selected')).click();
  14312. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14313. });
  14314. </file>
  14315. </example>
  14316. *
  14317. * @element OPTION
  14318. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14319. * then special attribute "selected" will be set on the element
  14320. */
  14321. /**
  14322. * @ngdoc directive
  14323. * @name ngOpen
  14324. * @restrict A
  14325. * @priority 100
  14326. *
  14327. * @description
  14328. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14329. * such as open. (Their presence means true and their absence means false.)
  14330. * If we put an Angular interpolation expression into such an attribute then the
  14331. * binding information would be lost when the browser removes the attribute.
  14332. * The `ngOpen` directive solves this problem for the `open` attribute.
  14333. * This complementary directive is not removed by the browser and so provides
  14334. * a permanent reliable place to store the binding information.
  14335. * @example
  14336. <example>
  14337. <file name="index.html">
  14338. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14339. <details id="details" ng-open="open">
  14340. <summary>Show/Hide me</summary>
  14341. </details>
  14342. </file>
  14343. <file name="protractor.js" type="protractor">
  14344. it('should toggle open', function() {
  14345. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14346. element(by.model('open')).click();
  14347. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14348. });
  14349. </file>
  14350. </example>
  14351. *
  14352. * @element DETAILS
  14353. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14354. * then special attribute "open" will be set on the element
  14355. */
  14356. var ngAttributeAliasDirectives = {};
  14357. // boolean attrs are evaluated
  14358. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14359. // binding to multiple is not supported
  14360. if (propName == "multiple") return;
  14361. var normalized = directiveNormalize('ng-' + attrName);
  14362. ngAttributeAliasDirectives[normalized] = function() {
  14363. return {
  14364. priority: 100,
  14365. link: function(scope, element, attr) {
  14366. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14367. attr.$set(attrName, !!value);
  14368. });
  14369. }
  14370. };
  14371. };
  14372. });
  14373. // ng-src, ng-srcset, ng-href are interpolated
  14374. forEach(['src', 'srcset', 'href'], function(attrName) {
  14375. var normalized = directiveNormalize('ng-' + attrName);
  14376. ngAttributeAliasDirectives[normalized] = function() {
  14377. return {
  14378. priority: 99, // it needs to run after the attributes are interpolated
  14379. link: function(scope, element, attr) {
  14380. var propName = attrName,
  14381. name = attrName;
  14382. if (attrName === 'href' &&
  14383. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14384. name = 'xlinkHref';
  14385. attr.$attr[name] = 'xlink:href';
  14386. propName = null;
  14387. }
  14388. attr.$observe(normalized, function(value) {
  14389. if (!value)
  14390. return;
  14391. attr.$set(name, value);
  14392. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14393. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14394. // to set the property as well to achieve the desired effect.
  14395. // we use attr[attrName] value since $set can sanitize the url.
  14396. if (msie && propName) element.prop(propName, attr[name]);
  14397. });
  14398. }
  14399. };
  14400. };
  14401. });
  14402. /* global -nullFormCtrl */
  14403. var nullFormCtrl = {
  14404. $addControl: noop,
  14405. $removeControl: noop,
  14406. $setValidity: noop,
  14407. $setDirty: noop,
  14408. $setPristine: noop
  14409. };
  14410. /**
  14411. * @ngdoc type
  14412. * @name form.FormController
  14413. *
  14414. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14415. * @property {boolean} $dirty True if user has already interacted with the form.
  14416. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14417. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14418. *
  14419. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14420. * forms, where:
  14421. *
  14422. * - keys are validation tokens (error names),
  14423. * - values are arrays of controls or forms that are invalid for given error name.
  14424. *
  14425. *
  14426. * Built-in validation tokens:
  14427. *
  14428. * - `email`
  14429. * - `max`
  14430. * - `maxlength`
  14431. * - `min`
  14432. * - `minlength`
  14433. * - `number`
  14434. * - `pattern`
  14435. * - `required`
  14436. * - `url`
  14437. *
  14438. * @description
  14439. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  14440. * such as being valid/invalid or dirty/pristine.
  14441. *
  14442. * Each {@link ng.directive:form form} directive creates an instance
  14443. * of `FormController`.
  14444. *
  14445. */
  14446. //asks for $scope to fool the BC controller module
  14447. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14448. function FormController(element, attrs, $scope, $animate) {
  14449. var form = this,
  14450. parentForm = element.parent().controller('form') || nullFormCtrl,
  14451. invalidCount = 0, // used to easily determine if we are valid
  14452. errors = form.$error = {},
  14453. controls = [];
  14454. // init state
  14455. form.$name = attrs.name || attrs.ngForm;
  14456. form.$dirty = false;
  14457. form.$pristine = true;
  14458. form.$valid = true;
  14459. form.$invalid = false;
  14460. parentForm.$addControl(form);
  14461. // Setup initial state of the control
  14462. element.addClass(PRISTINE_CLASS);
  14463. toggleValidCss(true);
  14464. // convenience method for easy toggling of classes
  14465. function toggleValidCss(isValid, validationErrorKey) {
  14466. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14467. $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14468. $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  14469. }
  14470. /**
  14471. * @ngdoc method
  14472. * @name form.FormController#$addControl
  14473. *
  14474. * @description
  14475. * Register a control with the form.
  14476. *
  14477. * Input elements using ngModelController do this automatically when they are linked.
  14478. */
  14479. form.$addControl = function(control) {
  14480. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14481. // and not added to the scope. Now we throw an error.
  14482. assertNotHasOwnProperty(control.$name, 'input');
  14483. controls.push(control);
  14484. if (control.$name) {
  14485. form[control.$name] = control;
  14486. }
  14487. };
  14488. /**
  14489. * @ngdoc method
  14490. * @name form.FormController#$removeControl
  14491. *
  14492. * @description
  14493. * Deregister a control from the form.
  14494. *
  14495. * Input elements using ngModelController do this automatically when they are destroyed.
  14496. */
  14497. form.$removeControl = function(control) {
  14498. if (control.$name && form[control.$name] === control) {
  14499. delete form[control.$name];
  14500. }
  14501. forEach(errors, function(queue, validationToken) {
  14502. form.$setValidity(validationToken, true, control);
  14503. });
  14504. arrayRemove(controls, control);
  14505. };
  14506. /**
  14507. * @ngdoc method
  14508. * @name form.FormController#$setValidity
  14509. *
  14510. * @description
  14511. * Sets the validity of a form control.
  14512. *
  14513. * This method will also propagate to parent forms.
  14514. */
  14515. form.$setValidity = function(validationToken, isValid, control) {
  14516. var queue = errors[validationToken];
  14517. if (isValid) {
  14518. if (queue) {
  14519. arrayRemove(queue, control);
  14520. if (!queue.length) {
  14521. invalidCount--;
  14522. if (!invalidCount) {
  14523. toggleValidCss(isValid);
  14524. form.$valid = true;
  14525. form.$invalid = false;
  14526. }
  14527. errors[validationToken] = false;
  14528. toggleValidCss(true, validationToken);
  14529. parentForm.$setValidity(validationToken, true, form);
  14530. }
  14531. }
  14532. } else {
  14533. if (!invalidCount) {
  14534. toggleValidCss(isValid);
  14535. }
  14536. if (queue) {
  14537. if (includes(queue, control)) return;
  14538. } else {
  14539. errors[validationToken] = queue = [];
  14540. invalidCount++;
  14541. toggleValidCss(false, validationToken);
  14542. parentForm.$setValidity(validationToken, false, form);
  14543. }
  14544. queue.push(control);
  14545. form.$valid = false;
  14546. form.$invalid = true;
  14547. }
  14548. };
  14549. /**
  14550. * @ngdoc method
  14551. * @name form.FormController#$setDirty
  14552. *
  14553. * @description
  14554. * Sets the form to a dirty state.
  14555. *
  14556. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14557. * state (ng-dirty class). This method will also propagate to parent forms.
  14558. */
  14559. form.$setDirty = function() {
  14560. $animate.removeClass(element, PRISTINE_CLASS);
  14561. $animate.addClass(element, DIRTY_CLASS);
  14562. form.$dirty = true;
  14563. form.$pristine = false;
  14564. parentForm.$setDirty();
  14565. };
  14566. /**
  14567. * @ngdoc method
  14568. * @name form.FormController#$setPristine
  14569. *
  14570. * @description
  14571. * Sets the form to its pristine state.
  14572. *
  14573. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14574. * state (ng-pristine class). This method will also propagate to all the controls contained
  14575. * in this form.
  14576. *
  14577. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14578. * saving or resetting it.
  14579. */
  14580. form.$setPristine = function () {
  14581. $animate.removeClass(element, DIRTY_CLASS);
  14582. $animate.addClass(element, PRISTINE_CLASS);
  14583. form.$dirty = false;
  14584. form.$pristine = true;
  14585. forEach(controls, function(control) {
  14586. control.$setPristine();
  14587. });
  14588. };
  14589. }
  14590. /**
  14591. * @ngdoc directive
  14592. * @name ngForm
  14593. * @restrict EAC
  14594. *
  14595. * @description
  14596. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14597. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14598. * sub-group of controls needs to be determined.
  14599. *
  14600. * Note: the purpose of `ngForm` is to group controls,
  14601. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14602. * (e.g. posting to the server, ...).
  14603. *
  14604. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14605. * related scope, under this name.
  14606. *
  14607. */
  14608. /**
  14609. * @ngdoc directive
  14610. * @name form
  14611. * @restrict E
  14612. *
  14613. * @description
  14614. * Directive that instantiates
  14615. * {@link form.FormController FormController}.
  14616. *
  14617. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14618. * this name.
  14619. *
  14620. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14621. *
  14622. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14623. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14624. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14625. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14626. * using Angular validation directives in forms that are dynamically generated using the
  14627. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14628. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14629. * `ngForm` directive and nest these in an outer `form` element.
  14630. *
  14631. *
  14632. * # CSS classes
  14633. * - `ng-valid` is set if the form is valid.
  14634. * - `ng-invalid` is set if the form is invalid.
  14635. * - `ng-pristine` is set if the form is pristine.
  14636. * - `ng-dirty` is set if the form is dirty.
  14637. *
  14638. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14639. *
  14640. *
  14641. * # Submitting a form and preventing the default action
  14642. *
  14643. * Since the role of forms in client-side Angular applications is different than in classical
  14644. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14645. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14646. * to handle the form submission in an application-specific way.
  14647. *
  14648. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14649. * `<form>` element has an `action` attribute specified.
  14650. *
  14651. * You can use one of the following two ways to specify what javascript method should be called when
  14652. * a form is submitted:
  14653. *
  14654. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14655. * - {@link ng.directive:ngClick ngClick} directive on the first
  14656. * button or input field of type submit (input[type=submit])
  14657. *
  14658. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14659. * or {@link ng.directive:ngClick ngClick} directives.
  14660. * This is because of the following form submission rules in the HTML specification:
  14661. *
  14662. * - If a form has only one input field then hitting enter in this field triggers form submit
  14663. * (`ngSubmit`)
  14664. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14665. * doesn't trigger submit
  14666. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14667. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14668. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14669. *
  14670. * @param {string=} name Name of the form. If specified, the form controller will be published into
  14671. * related scope, under this name.
  14672. *
  14673. * ## Animation Hooks
  14674. *
  14675. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  14676. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  14677. * other validations that are performed within the form. Animations in ngForm are similar to how
  14678. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  14679. * as JS animations.
  14680. *
  14681. * The following example shows a simple way to utilize CSS transitions to style a form element
  14682. * that has been rendered as invalid after it has been validated:
  14683. *
  14684. * <pre>
  14685. * //be sure to include ngAnimate as a module to hook into more
  14686. * //advanced animations
  14687. * .my-form {
  14688. * transition:0.5s linear all;
  14689. * background: white;
  14690. * }
  14691. * .my-form.ng-invalid {
  14692. * background: red;
  14693. * color:white;
  14694. * }
  14695. * </pre>
  14696. *
  14697. * @example
  14698. <example deps="angular-animate.js" animations="true" fixBase="true">
  14699. <file name="index.html">
  14700. <script>
  14701. function Ctrl($scope) {
  14702. $scope.userType = 'guest';
  14703. }
  14704. </script>
  14705. <style>
  14706. .my-form {
  14707. -webkit-transition:all linear 0.5s;
  14708. transition:all linear 0.5s;
  14709. background: transparent;
  14710. }
  14711. .my-form.ng-invalid {
  14712. background: red;
  14713. }
  14714. </style>
  14715. <form name="myForm" ng-controller="Ctrl" class="my-form">
  14716. userType: <input name="input" ng-model="userType" required>
  14717. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  14718. <tt>userType = {{userType}}</tt><br>
  14719. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  14720. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  14721. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14722. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14723. </form>
  14724. </file>
  14725. <file name="protractor.js" type="protractor">
  14726. it('should initialize to model', function() {
  14727. var userType = element(by.binding('userType'));
  14728. var valid = element(by.binding('myForm.input.$valid'));
  14729. expect(userType.getText()).toContain('guest');
  14730. expect(valid.getText()).toContain('true');
  14731. });
  14732. it('should be invalid if empty', function() {
  14733. var userType = element(by.binding('userType'));
  14734. var valid = element(by.binding('myForm.input.$valid'));
  14735. var userInput = element(by.model('userType'));
  14736. userInput.clear();
  14737. userInput.sendKeys('');
  14738. expect(userType.getText()).toEqual('userType =');
  14739. expect(valid.getText()).toContain('false');
  14740. });
  14741. </file>
  14742. </example>
  14743. *
  14744. */
  14745. var formDirectiveFactory = function(isNgForm) {
  14746. return ['$timeout', function($timeout) {
  14747. var formDirective = {
  14748. name: 'form',
  14749. restrict: isNgForm ? 'EAC' : 'E',
  14750. controller: FormController,
  14751. compile: function() {
  14752. return {
  14753. pre: function(scope, formElement, attr, controller) {
  14754. if (!attr.action) {
  14755. // we can't use jq events because if a form is destroyed during submission the default
  14756. // action is not prevented. see #1238
  14757. //
  14758. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  14759. // page reload if the form was destroyed by submission of the form via a click handler
  14760. // on a button in the form. Looks like an IE9 specific bug.
  14761. var preventDefaultListener = function(event) {
  14762. event.preventDefault
  14763. ? event.preventDefault()
  14764. : event.returnValue = false; // IE
  14765. };
  14766. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14767. // unregister the preventDefault listener so that we don't not leak memory but in a
  14768. // way that will achieve the prevention of the default action.
  14769. formElement.on('$destroy', function() {
  14770. $timeout(function() {
  14771. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14772. }, 0, false);
  14773. });
  14774. }
  14775. var parentFormCtrl = formElement.parent().controller('form'),
  14776. alias = attr.name || attr.ngForm;
  14777. if (alias) {
  14778. setter(scope, alias, controller, alias);
  14779. }
  14780. if (parentFormCtrl) {
  14781. formElement.on('$destroy', function() {
  14782. parentFormCtrl.$removeControl(controller);
  14783. if (alias) {
  14784. setter(scope, alias, undefined, alias);
  14785. }
  14786. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  14787. });
  14788. }
  14789. }
  14790. };
  14791. }
  14792. };
  14793. return formDirective;
  14794. }];
  14795. };
  14796. var formDirective = formDirectiveFactory();
  14797. var ngFormDirective = formDirectiveFactory(true);
  14798. /* global
  14799. -VALID_CLASS,
  14800. -INVALID_CLASS,
  14801. -PRISTINE_CLASS,
  14802. -DIRTY_CLASS
  14803. */
  14804. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  14805. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;
  14806. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  14807. var inputType = {
  14808. /**
  14809. * @ngdoc input
  14810. * @name input[text]
  14811. *
  14812. * @description
  14813. * Standard HTML text input with angular data binding.
  14814. *
  14815. * @param {string} ngModel Assignable angular expression to data-bind to.
  14816. * @param {string=} name Property name of the form under which the control is published.
  14817. * @param {string=} required Adds `required` validation error key if the value is not entered.
  14818. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14819. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14820. * `required` when you want to data-bind to the `required` attribute.
  14821. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14822. * minlength.
  14823. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14824. * maxlength.
  14825. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14826. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14827. * patterns defined as scope expressions.
  14828. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14829. * interaction with the input element.
  14830. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  14831. *
  14832. * @example
  14833. <example name="text-input-directive">
  14834. <file name="index.html">
  14835. <script>
  14836. function Ctrl($scope) {
  14837. $scope.text = 'guest';
  14838. $scope.word = /^\s*\w*\s*$/;
  14839. }
  14840. </script>
  14841. <form name="myForm" ng-controller="Ctrl">
  14842. Single word: <input type="text" name="input" ng-model="text"
  14843. ng-pattern="word" required ng-trim="false">
  14844. <span class="error" ng-show="myForm.input.$error.required">
  14845. Required!</span>
  14846. <span class="error" ng-show="myForm.input.$error.pattern">
  14847. Single word only!</span>
  14848. <tt>text = {{text}}</tt><br/>
  14849. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14850. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14851. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14852. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14853. </form>
  14854. </file>
  14855. <file name="protractor.js" type="protractor">
  14856. var text = element(by.binding('text'));
  14857. var valid = element(by.binding('myForm.input.$valid'));
  14858. var input = element(by.model('text'));
  14859. it('should initialize to model', function() {
  14860. expect(text.getText()).toContain('guest');
  14861. expect(valid.getText()).toContain('true');
  14862. });
  14863. it('should be invalid if empty', function() {
  14864. input.clear();
  14865. input.sendKeys('');
  14866. expect(text.getText()).toEqual('text =');
  14867. expect(valid.getText()).toContain('false');
  14868. });
  14869. it('should be invalid if multi word', function() {
  14870. input.clear();
  14871. input.sendKeys('hello world');
  14872. expect(valid.getText()).toContain('false');
  14873. });
  14874. </file>
  14875. </example>
  14876. */
  14877. 'text': textInputType,
  14878. /**
  14879. * @ngdoc input
  14880. * @name input[number]
  14881. *
  14882. * @description
  14883. * Text input with number validation and transformation. Sets the `number` validation
  14884. * error if not a valid number.
  14885. *
  14886. * @param {string} ngModel Assignable angular expression to data-bind to.
  14887. * @param {string=} name Property name of the form under which the control is published.
  14888. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  14889. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  14890. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14891. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14892. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14893. * `required` when you want to data-bind to the `required` attribute.
  14894. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14895. * minlength.
  14896. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14897. * maxlength.
  14898. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14899. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14900. * patterns defined as scope expressions.
  14901. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14902. * interaction with the input element.
  14903. *
  14904. * @example
  14905. <example name="number-input-directive">
  14906. <file name="index.html">
  14907. <script>
  14908. function Ctrl($scope) {
  14909. $scope.value = 12;
  14910. }
  14911. </script>
  14912. <form name="myForm" ng-controller="Ctrl">
  14913. Number: <input type="number" name="input" ng-model="value"
  14914. min="0" max="99" required>
  14915. <span class="error" ng-show="myForm.input.$error.required">
  14916. Required!</span>
  14917. <span class="error" ng-show="myForm.input.$error.number">
  14918. Not valid number!</span>
  14919. <tt>value = {{value}}</tt><br/>
  14920. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14921. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14922. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14923. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14924. </form>
  14925. </file>
  14926. <file name="protractor.js" type="protractor">
  14927. var value = element(by.binding('value'));
  14928. var valid = element(by.binding('myForm.input.$valid'));
  14929. var input = element(by.model('value'));
  14930. it('should initialize to model', function() {
  14931. expect(value.getText()).toContain('12');
  14932. expect(valid.getText()).toContain('true');
  14933. });
  14934. it('should be invalid if empty', function() {
  14935. input.clear();
  14936. input.sendKeys('');
  14937. expect(value.getText()).toEqual('value =');
  14938. expect(valid.getText()).toContain('false');
  14939. });
  14940. it('should be invalid if over max', function() {
  14941. input.clear();
  14942. input.sendKeys('123');
  14943. expect(value.getText()).toEqual('value =');
  14944. expect(valid.getText()).toContain('false');
  14945. });
  14946. </file>
  14947. </example>
  14948. */
  14949. 'number': numberInputType,
  14950. /**
  14951. * @ngdoc input
  14952. * @name input[url]
  14953. *
  14954. * @description
  14955. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  14956. * valid URL.
  14957. *
  14958. * @param {string} ngModel Assignable angular expression to data-bind to.
  14959. * @param {string=} name Property name of the form under which the control is published.
  14960. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14961. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14962. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14963. * `required` when you want to data-bind to the `required` attribute.
  14964. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14965. * minlength.
  14966. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14967. * maxlength.
  14968. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14969. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14970. * patterns defined as scope expressions.
  14971. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14972. * interaction with the input element.
  14973. *
  14974. * @example
  14975. <example name="url-input-directive">
  14976. <file name="index.html">
  14977. <script>
  14978. function Ctrl($scope) {
  14979. $scope.text = 'http://google.com';
  14980. }
  14981. </script>
  14982. <form name="myForm" ng-controller="Ctrl">
  14983. URL: <input type="url" name="input" ng-model="text" required>
  14984. <span class="error" ng-show="myForm.input.$error.required">
  14985. Required!</span>
  14986. <span class="error" ng-show="myForm.input.$error.url">
  14987. Not valid url!</span>
  14988. <tt>text = {{text}}</tt><br/>
  14989. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14990. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14991. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14992. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14993. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  14994. </form>
  14995. </file>
  14996. <file name="protractor.js" type="protractor">
  14997. var text = element(by.binding('text'));
  14998. var valid = element(by.binding('myForm.input.$valid'));
  14999. var input = element(by.model('text'));
  15000. it('should initialize to model', function() {
  15001. expect(text.getText()).toContain('http://google.com');
  15002. expect(valid.getText()).toContain('true');
  15003. });
  15004. it('should be invalid if empty', function() {
  15005. input.clear();
  15006. input.sendKeys('');
  15007. expect(text.getText()).toEqual('text =');
  15008. expect(valid.getText()).toContain('false');
  15009. });
  15010. it('should be invalid if not url', function() {
  15011. input.clear();
  15012. input.sendKeys('box');
  15013. expect(valid.getText()).toContain('false');
  15014. });
  15015. </file>
  15016. </example>
  15017. */
  15018. 'url': urlInputType,
  15019. /**
  15020. * @ngdoc input
  15021. * @name input[email]
  15022. *
  15023. * @description
  15024. * Text input with email validation. Sets the `email` validation error key if not a valid email
  15025. * address.
  15026. *
  15027. * @param {string} ngModel Assignable angular expression to data-bind to.
  15028. * @param {string=} name Property name of the form under which the control is published.
  15029. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15030. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15031. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15032. * `required` when you want to data-bind to the `required` attribute.
  15033. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15034. * minlength.
  15035. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15036. * maxlength.
  15037. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15038. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15039. * patterns defined as scope expressions.
  15040. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15041. * interaction with the input element.
  15042. *
  15043. * @example
  15044. <example name="email-input-directive">
  15045. <file name="index.html">
  15046. <script>
  15047. function Ctrl($scope) {
  15048. $scope.text = 'me@example.com';
  15049. }
  15050. </script>
  15051. <form name="myForm" ng-controller="Ctrl">
  15052. Email: <input type="email" name="input" ng-model="text" required>
  15053. <span class="error" ng-show="myForm.input.$error.required">
  15054. Required!</span>
  15055. <span class="error" ng-show="myForm.input.$error.email">
  15056. Not valid email!</span>
  15057. <tt>text = {{text}}</tt><br/>
  15058. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15059. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15060. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15061. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15062. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  15063. </form>
  15064. </file>
  15065. <file name="protractor.js" type="protractor">
  15066. var text = element(by.binding('text'));
  15067. var valid = element(by.binding('myForm.input.$valid'));
  15068. var input = element(by.model('text'));
  15069. it('should initialize to model', function() {
  15070. expect(text.getText()).toContain('me@example.com');
  15071. expect(valid.getText()).toContain('true');
  15072. });
  15073. it('should be invalid if empty', function() {
  15074. input.clear();
  15075. input.sendKeys('');
  15076. expect(text.getText()).toEqual('text =');
  15077. expect(valid.getText()).toContain('false');
  15078. });
  15079. it('should be invalid if not email', function() {
  15080. input.clear();
  15081. input.sendKeys('xxx');
  15082. expect(valid.getText()).toContain('false');
  15083. });
  15084. </file>
  15085. </example>
  15086. */
  15087. 'email': emailInputType,
  15088. /**
  15089. * @ngdoc input
  15090. * @name input[radio]
  15091. *
  15092. * @description
  15093. * HTML radio button.
  15094. *
  15095. * @param {string} ngModel Assignable angular expression to data-bind to.
  15096. * @param {string} value The value to which the expression should be set when selected.
  15097. * @param {string=} name Property name of the form under which the control is published.
  15098. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15099. * interaction with the input element.
  15100. * @param {string} ngValue Angular expression which sets the value to which the expression should
  15101. * be set when selected.
  15102. *
  15103. * @example
  15104. <example name="radio-input-directive">
  15105. <file name="index.html">
  15106. <script>
  15107. function Ctrl($scope) {
  15108. $scope.color = 'blue';
  15109. $scope.specialValue = {
  15110. "id": "12345",
  15111. "value": "green"
  15112. };
  15113. }
  15114. </script>
  15115. <form name="myForm" ng-controller="Ctrl">
  15116. <input type="radio" ng-model="color" value="red"> Red <br/>
  15117. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  15118. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  15119. <tt>color = {{color | json}}</tt><br/>
  15120. </form>
  15121. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  15122. </file>
  15123. <file name="protractor.js" type="protractor">
  15124. it('should change state', function() {
  15125. var color = element(by.binding('color'));
  15126. expect(color.getText()).toContain('blue');
  15127. element.all(by.model('color')).get(0).click();
  15128. expect(color.getText()).toContain('red');
  15129. });
  15130. </file>
  15131. </example>
  15132. */
  15133. 'radio': radioInputType,
  15134. /**
  15135. * @ngdoc input
  15136. * @name input[checkbox]
  15137. *
  15138. * @description
  15139. * HTML checkbox.
  15140. *
  15141. * @param {string} ngModel Assignable angular expression to data-bind to.
  15142. * @param {string=} name Property name of the form under which the control is published.
  15143. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  15144. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  15145. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15146. * interaction with the input element.
  15147. *
  15148. * @example
  15149. <example name="checkbox-input-directive">
  15150. <file name="index.html">
  15151. <script>
  15152. function Ctrl($scope) {
  15153. $scope.value1 = true;
  15154. $scope.value2 = 'YES'
  15155. }
  15156. </script>
  15157. <form name="myForm" ng-controller="Ctrl">
  15158. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15159. Value2: <input type="checkbox" ng-model="value2"
  15160. ng-true-value="YES" ng-false-value="NO"> <br/>
  15161. <tt>value1 = {{value1}}</tt><br/>
  15162. <tt>value2 = {{value2}}</tt><br/>
  15163. </form>
  15164. </file>
  15165. <file name="protractor.js" type="protractor">
  15166. it('should change state', function() {
  15167. var value1 = element(by.binding('value1'));
  15168. var value2 = element(by.binding('value2'));
  15169. expect(value1.getText()).toContain('true');
  15170. expect(value2.getText()).toContain('YES');
  15171. element(by.model('value1')).click();
  15172. element(by.model('value2')).click();
  15173. expect(value1.getText()).toContain('false');
  15174. expect(value2.getText()).toContain('NO');
  15175. });
  15176. </file>
  15177. </example>
  15178. */
  15179. 'checkbox': checkboxInputType,
  15180. 'hidden': noop,
  15181. 'button': noop,
  15182. 'submit': noop,
  15183. 'reset': noop,
  15184. 'file': noop
  15185. };
  15186. // A helper function to call $setValidity and return the value / undefined,
  15187. // a pattern that is repeated a lot in the input validation logic.
  15188. function validate(ctrl, validatorName, validity, value){
  15189. ctrl.$setValidity(validatorName, validity);
  15190. return validity ? value : undefined;
  15191. }
  15192. function addNativeHtml5Validators(ctrl, validatorName, element) {
  15193. var validity = element.prop('validity');
  15194. if (isObject(validity)) {
  15195. var validator = function(value) {
  15196. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15197. // perform the required validation)
  15198. if (!ctrl.$error[validatorName] && (validity.badInput || validity.customError ||
  15199. validity.typeMismatch) && !validity.valueMissing) {
  15200. ctrl.$setValidity(validatorName, false);
  15201. return;
  15202. }
  15203. return value;
  15204. };
  15205. ctrl.$parsers.push(validator);
  15206. }
  15207. }
  15208. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15209. var validity = element.prop('validity');
  15210. var placeholder = element[0].placeholder, noevent = {};
  15211. // In composition mode, users are still inputing intermediate text buffer,
  15212. // hold the listener until composition is done.
  15213. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15214. if (!$sniffer.android) {
  15215. var composing = false;
  15216. element.on('compositionstart', function(data) {
  15217. composing = true;
  15218. });
  15219. element.on('compositionend', function() {
  15220. composing = false;
  15221. listener();
  15222. });
  15223. }
  15224. var listener = function(ev) {
  15225. if (composing) return;
  15226. var value = element.val();
  15227. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  15228. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  15229. // IE also sends input events for other non-input-related things, (such as focusing on a
  15230. // form control), so this change is not entirely enough to solve this.
  15231. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  15232. placeholder = element[0].placeholder;
  15233. return;
  15234. }
  15235. // By default we will trim the value
  15236. // If the attribute ng-trim exists we will avoid trimming
  15237. // e.g. <input ng-model="foo" ng-trim="false">
  15238. if (toBoolean(attr.ngTrim || 'T')) {
  15239. value = trim(value);
  15240. }
  15241. if (ctrl.$viewValue !== value ||
  15242. // If the value is still empty/falsy, and there is no `required` error, run validators
  15243. // again. This enables HTML5 constraint validation errors to affect Angular validation
  15244. // even when the first character entered causes an error.
  15245. (validity && value === '' && !validity.valueMissing)) {
  15246. if (scope.$$phase) {
  15247. ctrl.$setViewValue(value);
  15248. } else {
  15249. scope.$apply(function() {
  15250. ctrl.$setViewValue(value);
  15251. });
  15252. }
  15253. }
  15254. };
  15255. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15256. // input event on backspace, delete or cut
  15257. if ($sniffer.hasEvent('input')) {
  15258. element.on('input', listener);
  15259. } else {
  15260. var timeout;
  15261. var deferListener = function() {
  15262. if (!timeout) {
  15263. timeout = $browser.defer(function() {
  15264. listener();
  15265. timeout = null;
  15266. });
  15267. }
  15268. };
  15269. element.on('keydown', function(event) {
  15270. var key = event.keyCode;
  15271. // ignore
  15272. // command modifiers arrows
  15273. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15274. deferListener();
  15275. });
  15276. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15277. if ($sniffer.hasEvent('paste')) {
  15278. element.on('paste cut', deferListener);
  15279. }
  15280. }
  15281. // if user paste into input using mouse on older browser
  15282. // or form autocomplete on newer browser, we need "change" event to catch it
  15283. element.on('change', listener);
  15284. ctrl.$render = function() {
  15285. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15286. };
  15287. // pattern validator
  15288. var pattern = attr.ngPattern,
  15289. patternValidator,
  15290. match;
  15291. if (pattern) {
  15292. var validateRegex = function(regexp, value) {
  15293. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15294. };
  15295. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15296. if (match) {
  15297. pattern = new RegExp(match[1], match[2]);
  15298. patternValidator = function(value) {
  15299. return validateRegex(pattern, value);
  15300. };
  15301. } else {
  15302. patternValidator = function(value) {
  15303. var patternObj = scope.$eval(pattern);
  15304. if (!patternObj || !patternObj.test) {
  15305. throw minErr('ngPattern')('noregexp',
  15306. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15307. patternObj, startingTag(element));
  15308. }
  15309. return validateRegex(patternObj, value);
  15310. };
  15311. }
  15312. ctrl.$formatters.push(patternValidator);
  15313. ctrl.$parsers.push(patternValidator);
  15314. }
  15315. // min length validator
  15316. if (attr.ngMinlength) {
  15317. var minlength = int(attr.ngMinlength);
  15318. var minLengthValidator = function(value) {
  15319. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15320. };
  15321. ctrl.$parsers.push(minLengthValidator);
  15322. ctrl.$formatters.push(minLengthValidator);
  15323. }
  15324. // max length validator
  15325. if (attr.ngMaxlength) {
  15326. var maxlength = int(attr.ngMaxlength);
  15327. var maxLengthValidator = function(value) {
  15328. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15329. };
  15330. ctrl.$parsers.push(maxLengthValidator);
  15331. ctrl.$formatters.push(maxLengthValidator);
  15332. }
  15333. }
  15334. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15335. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15336. ctrl.$parsers.push(function(value) {
  15337. var empty = ctrl.$isEmpty(value);
  15338. if (empty || NUMBER_REGEXP.test(value)) {
  15339. ctrl.$setValidity('number', true);
  15340. return value === '' ? null : (empty ? value : parseFloat(value));
  15341. } else {
  15342. ctrl.$setValidity('number', false);
  15343. return undefined;
  15344. }
  15345. });
  15346. addNativeHtml5Validators(ctrl, 'number', element);
  15347. ctrl.$formatters.push(function(value) {
  15348. return ctrl.$isEmpty(value) ? '' : '' + value;
  15349. });
  15350. if (attr.min) {
  15351. var minValidator = function(value) {
  15352. var min = parseFloat(attr.min);
  15353. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15354. };
  15355. ctrl.$parsers.push(minValidator);
  15356. ctrl.$formatters.push(minValidator);
  15357. }
  15358. if (attr.max) {
  15359. var maxValidator = function(value) {
  15360. var max = parseFloat(attr.max);
  15361. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15362. };
  15363. ctrl.$parsers.push(maxValidator);
  15364. ctrl.$formatters.push(maxValidator);
  15365. }
  15366. ctrl.$formatters.push(function(value) {
  15367. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15368. });
  15369. }
  15370. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15371. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15372. var urlValidator = function(value) {
  15373. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15374. };
  15375. ctrl.$formatters.push(urlValidator);
  15376. ctrl.$parsers.push(urlValidator);
  15377. }
  15378. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15379. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15380. var emailValidator = function(value) {
  15381. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15382. };
  15383. ctrl.$formatters.push(emailValidator);
  15384. ctrl.$parsers.push(emailValidator);
  15385. }
  15386. function radioInputType(scope, element, attr, ctrl) {
  15387. // make the name unique, if not defined
  15388. if (isUndefined(attr.name)) {
  15389. element.attr('name', nextUid());
  15390. }
  15391. element.on('click', function() {
  15392. if (element[0].checked) {
  15393. scope.$apply(function() {
  15394. ctrl.$setViewValue(attr.value);
  15395. });
  15396. }
  15397. });
  15398. ctrl.$render = function() {
  15399. var value = attr.value;
  15400. element[0].checked = (value == ctrl.$viewValue);
  15401. };
  15402. attr.$observe('value', ctrl.$render);
  15403. }
  15404. function checkboxInputType(scope, element, attr, ctrl) {
  15405. var trueValue = attr.ngTrueValue,
  15406. falseValue = attr.ngFalseValue;
  15407. if (!isString(trueValue)) trueValue = true;
  15408. if (!isString(falseValue)) falseValue = false;
  15409. element.on('click', function() {
  15410. scope.$apply(function() {
  15411. ctrl.$setViewValue(element[0].checked);
  15412. });
  15413. });
  15414. ctrl.$render = function() {
  15415. element[0].checked = ctrl.$viewValue;
  15416. };
  15417. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15418. ctrl.$isEmpty = function(value) {
  15419. return value !== trueValue;
  15420. };
  15421. ctrl.$formatters.push(function(value) {
  15422. return value === trueValue;
  15423. });
  15424. ctrl.$parsers.push(function(value) {
  15425. return value ? trueValue : falseValue;
  15426. });
  15427. }
  15428. /**
  15429. * @ngdoc directive
  15430. * @name textarea
  15431. * @restrict E
  15432. *
  15433. * @description
  15434. * HTML textarea element control with angular data-binding. The data-binding and validation
  15435. * properties of this element are exactly the same as those of the
  15436. * {@link ng.directive:input input element}.
  15437. *
  15438. * @param {string} ngModel Assignable angular expression to data-bind to.
  15439. * @param {string=} name Property name of the form under which the control is published.
  15440. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15441. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15442. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15443. * `required` when you want to data-bind to the `required` attribute.
  15444. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15445. * minlength.
  15446. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15447. * maxlength.
  15448. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15449. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15450. * patterns defined as scope expressions.
  15451. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15452. * interaction with the input element.
  15453. */
  15454. /**
  15455. * @ngdoc directive
  15456. * @name input
  15457. * @restrict E
  15458. *
  15459. * @description
  15460. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15461. * and polyfills the HTML5 validation behavior for older browsers.
  15462. *
  15463. * @param {string} ngModel Assignable angular expression to data-bind to.
  15464. * @param {string=} name Property name of the form under which the control is published.
  15465. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15466. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15467. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15468. * minlength.
  15469. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15470. * maxlength.
  15471. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15472. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15473. * patterns defined as scope expressions.
  15474. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15475. * interaction with the input element.
  15476. *
  15477. * @example
  15478. <example name="input-directive">
  15479. <file name="index.html">
  15480. <script>
  15481. function Ctrl($scope) {
  15482. $scope.user = {name: 'guest', last: 'visitor'};
  15483. }
  15484. </script>
  15485. <div ng-controller="Ctrl">
  15486. <form name="myForm">
  15487. User name: <input type="text" name="userName" ng-model="user.name" required>
  15488. <span class="error" ng-show="myForm.userName.$error.required">
  15489. Required!</span><br>
  15490. Last name: <input type="text" name="lastName" ng-model="user.last"
  15491. ng-minlength="3" ng-maxlength="10">
  15492. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15493. Too short!</span>
  15494. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15495. Too long!</span><br>
  15496. </form>
  15497. <hr>
  15498. <tt>user = {{user}}</tt><br/>
  15499. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15500. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15501. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15502. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15503. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15504. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15505. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15506. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15507. </div>
  15508. </file>
  15509. <file name="protractor.js" type="protractor">
  15510. var user = element(by.binding('{{user}}'));
  15511. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15512. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15513. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15514. var formValid = element(by.binding('myForm.$valid'));
  15515. var userNameInput = element(by.model('user.name'));
  15516. var userLastInput = element(by.model('user.last'));
  15517. it('should initialize to model', function() {
  15518. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15519. expect(userNameValid.getText()).toContain('true');
  15520. expect(formValid.getText()).toContain('true');
  15521. });
  15522. it('should be invalid if empty when required', function() {
  15523. userNameInput.clear();
  15524. userNameInput.sendKeys('');
  15525. expect(user.getText()).toContain('{"last":"visitor"}');
  15526. expect(userNameValid.getText()).toContain('false');
  15527. expect(formValid.getText()).toContain('false');
  15528. });
  15529. it('should be valid if empty when min length is set', function() {
  15530. userLastInput.clear();
  15531. userLastInput.sendKeys('');
  15532. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15533. expect(lastNameValid.getText()).toContain('true');
  15534. expect(formValid.getText()).toContain('true');
  15535. });
  15536. it('should be invalid if less than required min length', function() {
  15537. userLastInput.clear();
  15538. userLastInput.sendKeys('xx');
  15539. expect(user.getText()).toContain('{"name":"guest"}');
  15540. expect(lastNameValid.getText()).toContain('false');
  15541. expect(lastNameError.getText()).toContain('minlength');
  15542. expect(formValid.getText()).toContain('false');
  15543. });
  15544. it('should be invalid if longer than max length', function() {
  15545. userLastInput.clear();
  15546. userLastInput.sendKeys('some ridiculously long name');
  15547. expect(user.getText()).toContain('{"name":"guest"}');
  15548. expect(lastNameValid.getText()).toContain('false');
  15549. expect(lastNameError.getText()).toContain('maxlength');
  15550. expect(formValid.getText()).toContain('false');
  15551. });
  15552. </file>
  15553. </example>
  15554. */
  15555. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15556. return {
  15557. restrict: 'E',
  15558. require: '?ngModel',
  15559. link: function(scope, element, attr, ctrl) {
  15560. if (ctrl) {
  15561. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15562. $browser);
  15563. }
  15564. }
  15565. };
  15566. }];
  15567. var VALID_CLASS = 'ng-valid',
  15568. INVALID_CLASS = 'ng-invalid',
  15569. PRISTINE_CLASS = 'ng-pristine',
  15570. DIRTY_CLASS = 'ng-dirty';
  15571. /**
  15572. * @ngdoc type
  15573. * @name ngModel.NgModelController
  15574. *
  15575. * @property {string} $viewValue Actual string value in the view.
  15576. * @property {*} $modelValue The value in the model, that the control is bound to.
  15577. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15578. the control reads value from the DOM. Each function is called, in turn, passing the value
  15579. through to the next. The last return value is used to populate the model.
  15580. Used to sanitize / convert the value as well as validation. For validation,
  15581. the parsers should update the validity state using
  15582. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15583. and return `undefined` for invalid values.
  15584. *
  15585. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15586. the model value changes. Each function is called, in turn, passing the value through to the
  15587. next. Used to format / convert values for display in the control and validation.
  15588. * ```js
  15589. * function formatter(value) {
  15590. * if (value) {
  15591. * return value.toUpperCase();
  15592. * }
  15593. * }
  15594. * ngModel.$formatters.push(formatter);
  15595. * ```
  15596. *
  15597. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15598. * view value has changed. It is called with no arguments, and its return value is ignored.
  15599. * This can be used in place of additional $watches against the model value.
  15600. *
  15601. * @property {Object} $error An object hash with all errors as keys.
  15602. *
  15603. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15604. * @property {boolean} $dirty True if user has already interacted with the control.
  15605. * @property {boolean} $valid True if there is no error.
  15606. * @property {boolean} $invalid True if at least one error on the control.
  15607. *
  15608. * @description
  15609. *
  15610. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15611. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15612. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15613. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15614. * `NgModelController` for data-binding.
  15615. *
  15616. * ## Custom Control Example
  15617. * This example shows how to use `NgModelController` with a custom control to achieve
  15618. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  15619. * collaborate together to achieve the desired result.
  15620. *
  15621. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  15622. * contents be edited in place by the user. This will not work on older browsers.
  15623. *
  15624. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  15625. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  15626. * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks
  15627. * that content using the `$sce` service.
  15628. *
  15629. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  15630. <file name="style.css">
  15631. [contenteditable] {
  15632. border: 1px solid black;
  15633. background-color: white;
  15634. min-height: 20px;
  15635. }
  15636. .ng-invalid {
  15637. border: 1px solid red;
  15638. }
  15639. </file>
  15640. <file name="script.js">
  15641. angular.module('customControl', ['ngSanitize']).
  15642. directive('contenteditable', ['$sce', function($sce) {
  15643. return {
  15644. restrict: 'A', // only activate on element attribute
  15645. require: '?ngModel', // get a hold of NgModelController
  15646. link: function(scope, element, attrs, ngModel) {
  15647. if(!ngModel) return; // do nothing if no ng-model
  15648. // Specify how UI should be updated
  15649. ngModel.$render = function() {
  15650. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  15651. };
  15652. // Listen for change events to enable binding
  15653. element.on('blur keyup change', function() {
  15654. scope.$apply(read);
  15655. });
  15656. read(); // initialize
  15657. // Write data to the model
  15658. function read() {
  15659. var html = element.html();
  15660. // When we clear the content editable the browser leaves a <br> behind
  15661. // If strip-br attribute is provided then we strip this out
  15662. if( attrs.stripBr && html == '<br>' ) {
  15663. html = '';
  15664. }
  15665. ngModel.$setViewValue(html);
  15666. }
  15667. }
  15668. };
  15669. }]);
  15670. </file>
  15671. <file name="index.html">
  15672. <form name="myForm">
  15673. <div contenteditable
  15674. name="myWidget" ng-model="userContent"
  15675. strip-br="true"
  15676. required>Change me!</div>
  15677. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  15678. <hr>
  15679. <textarea ng-model="userContent"></textarea>
  15680. </form>
  15681. </file>
  15682. <file name="protractor.js" type="protractor">
  15683. it('should data-bind and become invalid', function() {
  15684. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  15685. // SafariDriver can't handle contenteditable
  15686. // and Firefox driver can't clear contenteditables very well
  15687. return;
  15688. }
  15689. var contentEditable = element(by.css('[contenteditable]'));
  15690. var content = 'Change me!';
  15691. expect(contentEditable.getText()).toEqual(content);
  15692. contentEditable.clear();
  15693. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  15694. expect(contentEditable.getText()).toEqual('');
  15695. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  15696. });
  15697. </file>
  15698. * </example>
  15699. *
  15700. *
  15701. */
  15702. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  15703. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  15704. this.$viewValue = Number.NaN;
  15705. this.$modelValue = Number.NaN;
  15706. this.$parsers = [];
  15707. this.$formatters = [];
  15708. this.$viewChangeListeners = [];
  15709. this.$pristine = true;
  15710. this.$dirty = false;
  15711. this.$valid = true;
  15712. this.$invalid = false;
  15713. this.$name = $attr.name;
  15714. var ngModelGet = $parse($attr.ngModel),
  15715. ngModelSet = ngModelGet.assign;
  15716. if (!ngModelSet) {
  15717. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  15718. $attr.ngModel, startingTag($element));
  15719. }
  15720. /**
  15721. * @ngdoc method
  15722. * @name ngModel.NgModelController#$render
  15723. *
  15724. * @description
  15725. * Called when the view needs to be updated. It is expected that the user of the ng-model
  15726. * directive will implement this method.
  15727. */
  15728. this.$render = noop;
  15729. /**
  15730. * @ngdoc method
  15731. * @name ngModel.NgModelController#$isEmpty
  15732. *
  15733. * @description
  15734. * This is called when we need to determine if the value of the input is empty.
  15735. *
  15736. * For instance, the required directive does this to work out if the input has data or not.
  15737. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  15738. *
  15739. * You can override this for input directives whose concept of being empty is different to the
  15740. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  15741. * implies empty.
  15742. *
  15743. * @param {*} value Reference to check.
  15744. * @returns {boolean} True if `value` is empty.
  15745. */
  15746. this.$isEmpty = function(value) {
  15747. return isUndefined(value) || value === '' || value === null || value !== value;
  15748. };
  15749. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  15750. invalidCount = 0, // used to easily determine if we are valid
  15751. $error = this.$error = {}; // keep invalid keys here
  15752. // Setup initial state of the control
  15753. $element.addClass(PRISTINE_CLASS);
  15754. toggleValidCss(true);
  15755. // convenience method for easy toggling of classes
  15756. function toggleValidCss(isValid, validationErrorKey) {
  15757. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  15758. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  15759. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  15760. }
  15761. /**
  15762. * @ngdoc method
  15763. * @name ngModel.NgModelController#$setValidity
  15764. *
  15765. * @description
  15766. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  15767. * does not notify form if given validator is already marked as invalid).
  15768. *
  15769. * This method should be called by validators - i.e. the parser or formatter functions.
  15770. *
  15771. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  15772. * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
  15773. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  15774. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  15775. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  15776. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  15777. */
  15778. this.$setValidity = function(validationErrorKey, isValid) {
  15779. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  15780. // jshint -W018
  15781. if ($error[validationErrorKey] === !isValid) return;
  15782. // jshint +W018
  15783. if (isValid) {
  15784. if ($error[validationErrorKey]) invalidCount--;
  15785. if (!invalidCount) {
  15786. toggleValidCss(true);
  15787. this.$valid = true;
  15788. this.$invalid = false;
  15789. }
  15790. } else {
  15791. toggleValidCss(false);
  15792. this.$invalid = true;
  15793. this.$valid = false;
  15794. invalidCount++;
  15795. }
  15796. $error[validationErrorKey] = !isValid;
  15797. toggleValidCss(isValid, validationErrorKey);
  15798. parentForm.$setValidity(validationErrorKey, isValid, this);
  15799. };
  15800. /**
  15801. * @ngdoc method
  15802. * @name ngModel.NgModelController#$setPristine
  15803. *
  15804. * @description
  15805. * Sets the control to its pristine state.
  15806. *
  15807. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  15808. * state (ng-pristine class).
  15809. */
  15810. this.$setPristine = function () {
  15811. this.$dirty = false;
  15812. this.$pristine = true;
  15813. $animate.removeClass($element, DIRTY_CLASS);
  15814. $animate.addClass($element, PRISTINE_CLASS);
  15815. };
  15816. /**
  15817. * @ngdoc method
  15818. * @name ngModel.NgModelController#$setViewValue
  15819. *
  15820. * @description
  15821. * Update the view value.
  15822. *
  15823. * This method should be called when the view value changes, typically from within a DOM event handler.
  15824. * For example {@link ng.directive:input input} and
  15825. * {@link ng.directive:select select} directives call it.
  15826. *
  15827. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  15828. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  15829. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  15830. *
  15831. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  15832. *
  15833. * Note that calling this function does not trigger a `$digest`.
  15834. *
  15835. * @param {string} value Value from the view.
  15836. */
  15837. this.$setViewValue = function(value) {
  15838. this.$viewValue = value;
  15839. // change to dirty
  15840. if (this.$pristine) {
  15841. this.$dirty = true;
  15842. this.$pristine = false;
  15843. $animate.removeClass($element, PRISTINE_CLASS);
  15844. $animate.addClass($element, DIRTY_CLASS);
  15845. parentForm.$setDirty();
  15846. }
  15847. forEach(this.$parsers, function(fn) {
  15848. value = fn(value);
  15849. });
  15850. if (this.$modelValue !== value) {
  15851. this.$modelValue = value;
  15852. ngModelSet($scope, value);
  15853. forEach(this.$viewChangeListeners, function(listener) {
  15854. try {
  15855. listener();
  15856. } catch(e) {
  15857. $exceptionHandler(e);
  15858. }
  15859. });
  15860. }
  15861. };
  15862. // model -> value
  15863. var ctrl = this;
  15864. $scope.$watch(function ngModelWatch() {
  15865. var value = ngModelGet($scope);
  15866. // if scope model value and ngModel value are out of sync
  15867. if (ctrl.$modelValue !== value) {
  15868. var formatters = ctrl.$formatters,
  15869. idx = formatters.length;
  15870. ctrl.$modelValue = value;
  15871. while(idx--) {
  15872. value = formatters[idx](value);
  15873. }
  15874. if (ctrl.$viewValue !== value) {
  15875. ctrl.$viewValue = value;
  15876. ctrl.$render();
  15877. }
  15878. }
  15879. return value;
  15880. });
  15881. }];
  15882. /**
  15883. * @ngdoc directive
  15884. * @name ngModel
  15885. *
  15886. * @element input
  15887. *
  15888. * @description
  15889. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  15890. * property on the scope using {@link ngModel.NgModelController NgModelController},
  15891. * which is created and exposed by this directive.
  15892. *
  15893. * `ngModel` is responsible for:
  15894. *
  15895. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  15896. * require.
  15897. * - Providing validation behavior (i.e. required, number, email, url).
  15898. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  15899. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  15900. * - Registering the control with its parent {@link ng.directive:form form}.
  15901. *
  15902. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  15903. * current scope. If the property doesn't already exist on this scope, it will be created
  15904. * implicitly and added to the scope.
  15905. *
  15906. * For best practices on using `ngModel`, see:
  15907. *
  15908. * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
  15909. *
  15910. * For basic examples, how to use `ngModel`, see:
  15911. *
  15912. * - {@link ng.directive:input input}
  15913. * - {@link input[text] text}
  15914. * - {@link input[checkbox] checkbox}
  15915. * - {@link input[radio] radio}
  15916. * - {@link input[number] number}
  15917. * - {@link input[email] email}
  15918. * - {@link input[url] url}
  15919. * - {@link ng.directive:select select}
  15920. * - {@link ng.directive:textarea textarea}
  15921. *
  15922. * # CSS classes
  15923. * The following CSS classes are added and removed on the associated input/select/textarea element
  15924. * depending on the validity of the model.
  15925. *
  15926. * - `ng-valid` is set if the model is valid.
  15927. * - `ng-invalid` is set if the model is invalid.
  15928. * - `ng-pristine` is set if the model is pristine.
  15929. * - `ng-dirty` is set if the model is dirty.
  15930. *
  15931. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  15932. *
  15933. * ## Animation Hooks
  15934. *
  15935. * Animations within models are triggered when any of the associated CSS classes are added and removed
  15936. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  15937. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  15938. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  15939. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  15940. *
  15941. * The following example shows a simple way to utilize CSS transitions to style an input element
  15942. * that has been rendered as invalid after it has been validated:
  15943. *
  15944. * <pre>
  15945. * //be sure to include ngAnimate as a module to hook into more
  15946. * //advanced animations
  15947. * .my-input {
  15948. * transition:0.5s linear all;
  15949. * background: white;
  15950. * }
  15951. * .my-input.ng-invalid {
  15952. * background: red;
  15953. * color:white;
  15954. * }
  15955. * </pre>
  15956. *
  15957. * @example
  15958. * <example deps="angular-animate.js" animations="true" fixBase="true">
  15959. <file name="index.html">
  15960. <script>
  15961. function Ctrl($scope) {
  15962. $scope.val = '1';
  15963. }
  15964. </script>
  15965. <style>
  15966. .my-input {
  15967. -webkit-transition:all linear 0.5s;
  15968. transition:all linear 0.5s;
  15969. background: transparent;
  15970. }
  15971. .my-input.ng-invalid {
  15972. color:white;
  15973. background: red;
  15974. }
  15975. </style>
  15976. Update input to see transitions when valid/invalid.
  15977. Integer is a valid value.
  15978. <form name="testForm" ng-controller="Ctrl">
  15979. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  15980. </form>
  15981. </file>
  15982. * </example>
  15983. */
  15984. var ngModelDirective = function() {
  15985. return {
  15986. require: ['ngModel', '^?form'],
  15987. controller: NgModelController,
  15988. link: function(scope, element, attr, ctrls) {
  15989. // notify others, especially parent forms
  15990. var modelCtrl = ctrls[0],
  15991. formCtrl = ctrls[1] || nullFormCtrl;
  15992. formCtrl.$addControl(modelCtrl);
  15993. scope.$on('$destroy', function() {
  15994. formCtrl.$removeControl(modelCtrl);
  15995. });
  15996. }
  15997. };
  15998. };
  15999. /**
  16000. * @ngdoc directive
  16001. * @name ngChange
  16002. *
  16003. * @description
  16004. * Evaluate the given expression when the user changes the input.
  16005. * The expression is evaluated immediately, unlike the JavaScript onchange event
  16006. * which only triggers at the end of a change (usually, when the user leaves the
  16007. * form element or presses the return key).
  16008. * The expression is not evaluated when the value change is coming from the model.
  16009. *
  16010. * Note, this directive requires `ngModel` to be present.
  16011. *
  16012. * @element input
  16013. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  16014. * in input value.
  16015. *
  16016. * @example
  16017. * <example name="ngChange-directive">
  16018. * <file name="index.html">
  16019. * <script>
  16020. * function Controller($scope) {
  16021. * $scope.counter = 0;
  16022. * $scope.change = function() {
  16023. * $scope.counter++;
  16024. * };
  16025. * }
  16026. * </script>
  16027. * <div ng-controller="Controller">
  16028. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  16029. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  16030. * <label for="ng-change-example2">Confirmed</label><br />
  16031. * <tt>debug = {{confirmed}}</tt><br/>
  16032. * <tt>counter = {{counter}}</tt><br/>
  16033. * </div>
  16034. * </file>
  16035. * <file name="protractor.js" type="protractor">
  16036. * var counter = element(by.binding('counter'));
  16037. * var debug = element(by.binding('confirmed'));
  16038. *
  16039. * it('should evaluate the expression if changing from view', function() {
  16040. * expect(counter.getText()).toContain('0');
  16041. *
  16042. * element(by.id('ng-change-example1')).click();
  16043. *
  16044. * expect(counter.getText()).toContain('1');
  16045. * expect(debug.getText()).toContain('true');
  16046. * });
  16047. *
  16048. * it('should not evaluate the expression if changing from model', function() {
  16049. * element(by.id('ng-change-example2')).click();
  16050. * expect(counter.getText()).toContain('0');
  16051. * expect(debug.getText()).toContain('true');
  16052. * });
  16053. * </file>
  16054. * </example>
  16055. */
  16056. var ngChangeDirective = valueFn({
  16057. require: 'ngModel',
  16058. link: function(scope, element, attr, ctrl) {
  16059. ctrl.$viewChangeListeners.push(function() {
  16060. scope.$eval(attr.ngChange);
  16061. });
  16062. }
  16063. });
  16064. var requiredDirective = function() {
  16065. return {
  16066. require: '?ngModel',
  16067. link: function(scope, elm, attr, ctrl) {
  16068. if (!ctrl) return;
  16069. attr.required = true; // force truthy in case we are on non input element
  16070. var validator = function(value) {
  16071. if (attr.required && ctrl.$isEmpty(value)) {
  16072. ctrl.$setValidity('required', false);
  16073. return;
  16074. } else {
  16075. ctrl.$setValidity('required', true);
  16076. return value;
  16077. }
  16078. };
  16079. ctrl.$formatters.push(validator);
  16080. ctrl.$parsers.unshift(validator);
  16081. attr.$observe('required', function() {
  16082. validator(ctrl.$viewValue);
  16083. });
  16084. }
  16085. };
  16086. };
  16087. /**
  16088. * @ngdoc directive
  16089. * @name ngList
  16090. *
  16091. * @description
  16092. * Text input that converts between a delimited string and an array of strings. The delimiter
  16093. * can be a fixed string (by default a comma) or a regular expression.
  16094. *
  16095. * @element input
  16096. * @param {string=} ngList optional delimiter that should be used to split the value. If
  16097. * specified in form `/something/` then the value will be converted into a regular expression.
  16098. *
  16099. * @example
  16100. <example name="ngList-directive">
  16101. <file name="index.html">
  16102. <script>
  16103. function Ctrl($scope) {
  16104. $scope.names = ['igor', 'misko', 'vojta'];
  16105. }
  16106. </script>
  16107. <form name="myForm" ng-controller="Ctrl">
  16108. List: <input name="namesInput" ng-model="names" ng-list required>
  16109. <span class="error" ng-show="myForm.namesInput.$error.required">
  16110. Required!</span>
  16111. <br>
  16112. <tt>names = {{names}}</tt><br/>
  16113. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  16114. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  16115. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16116. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16117. </form>
  16118. </file>
  16119. <file name="protractor.js" type="protractor">
  16120. var listInput = element(by.model('names'));
  16121. var names = element(by.binding('{{names}}'));
  16122. var valid = element(by.binding('myForm.namesInput.$valid'));
  16123. var error = element(by.css('span.error'));
  16124. it('should initialize to model', function() {
  16125. expect(names.getText()).toContain('["igor","misko","vojta"]');
  16126. expect(valid.getText()).toContain('true');
  16127. expect(error.getCssValue('display')).toBe('none');
  16128. });
  16129. it('should be invalid if empty', function() {
  16130. listInput.clear();
  16131. listInput.sendKeys('');
  16132. expect(names.getText()).toContain('');
  16133. expect(valid.getText()).toContain('false');
  16134. expect(error.getCssValue('display')).not.toBe('none'); });
  16135. </file>
  16136. </example>
  16137. */
  16138. var ngListDirective = function() {
  16139. return {
  16140. require: 'ngModel',
  16141. link: function(scope, element, attr, ctrl) {
  16142. var match = /\/(.*)\//.exec(attr.ngList),
  16143. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  16144. var parse = function(viewValue) {
  16145. // If the viewValue is invalid (say required but empty) it will be `undefined`
  16146. if (isUndefined(viewValue)) return;
  16147. var list = [];
  16148. if (viewValue) {
  16149. forEach(viewValue.split(separator), function(value) {
  16150. if (value) list.push(trim(value));
  16151. });
  16152. }
  16153. return list;
  16154. };
  16155. ctrl.$parsers.push(parse);
  16156. ctrl.$formatters.push(function(value) {
  16157. if (isArray(value)) {
  16158. return value.join(', ');
  16159. }
  16160. return undefined;
  16161. });
  16162. // Override the standard $isEmpty because an empty array means the input is empty.
  16163. ctrl.$isEmpty = function(value) {
  16164. return !value || !value.length;
  16165. };
  16166. }
  16167. };
  16168. };
  16169. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  16170. /**
  16171. * @ngdoc directive
  16172. * @name ngValue
  16173. *
  16174. * @description
  16175. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16176. * that when the element is selected, the `ngModel` of that element is set to the
  16177. * bound value.
  16178. *
  16179. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16180. * shown below.
  16181. *
  16182. * @element input
  16183. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16184. * of the `input` element
  16185. *
  16186. * @example
  16187. <example name="ngValue-directive">
  16188. <file name="index.html">
  16189. <script>
  16190. function Ctrl($scope) {
  16191. $scope.names = ['pizza', 'unicorns', 'robots'];
  16192. $scope.my = { favorite: 'unicorns' };
  16193. }
  16194. </script>
  16195. <form ng-controller="Ctrl">
  16196. <h2>Which is your favorite?</h2>
  16197. <label ng-repeat="name in names" for="{{name}}">
  16198. {{name}}
  16199. <input type="radio"
  16200. ng-model="my.favorite"
  16201. ng-value="name"
  16202. id="{{name}}"
  16203. name="favorite">
  16204. </label>
  16205. <div>You chose {{my.favorite}}</div>
  16206. </form>
  16207. </file>
  16208. <file name="protractor.js" type="protractor">
  16209. var favorite = element(by.binding('my.favorite'));
  16210. it('should initialize to model', function() {
  16211. expect(favorite.getText()).toContain('unicorns');
  16212. });
  16213. it('should bind the values to the inputs', function() {
  16214. element.all(by.model('my.favorite')).get(0).click();
  16215. expect(favorite.getText()).toContain('pizza');
  16216. });
  16217. </file>
  16218. </example>
  16219. */
  16220. var ngValueDirective = function() {
  16221. return {
  16222. priority: 100,
  16223. compile: function(tpl, tplAttr) {
  16224. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16225. return function ngValueConstantLink(scope, elm, attr) {
  16226. attr.$set('value', scope.$eval(attr.ngValue));
  16227. };
  16228. } else {
  16229. return function ngValueLink(scope, elm, attr) {
  16230. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16231. attr.$set('value', value);
  16232. });
  16233. };
  16234. }
  16235. }
  16236. };
  16237. };
  16238. /**
  16239. * @ngdoc directive
  16240. * @name ngBind
  16241. * @restrict AC
  16242. *
  16243. * @description
  16244. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16245. * with the value of a given expression, and to update the text content when the value of that
  16246. * expression changes.
  16247. *
  16248. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16249. * `{{ expression }}` which is similar but less verbose.
  16250. *
  16251. * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
  16252. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16253. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16254. *
  16255. * An alternative solution to this problem would be using the
  16256. * {@link ng.directive:ngCloak ngCloak} directive.
  16257. *
  16258. *
  16259. * @element ANY
  16260. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16261. *
  16262. * @example
  16263. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16264. <example>
  16265. <file name="index.html">
  16266. <script>
  16267. function Ctrl($scope) {
  16268. $scope.name = 'Whirled';
  16269. }
  16270. </script>
  16271. <div ng-controller="Ctrl">
  16272. Enter name: <input type="text" ng-model="name"><br>
  16273. Hello <span ng-bind="name"></span>!
  16274. </div>
  16275. </file>
  16276. <file name="protractor.js" type="protractor">
  16277. it('should check ng-bind', function() {
  16278. var nameInput = element(by.model('name'));
  16279. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16280. nameInput.clear();
  16281. nameInput.sendKeys('world');
  16282. expect(element(by.binding('name')).getText()).toBe('world');
  16283. });
  16284. </file>
  16285. </example>
  16286. */
  16287. var ngBindDirective = ngDirective(function(scope, element, attr) {
  16288. element.addClass('ng-binding').data('$binding', attr.ngBind);
  16289. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16290. // We are purposefully using == here rather than === because we want to
  16291. // catch when value is "null or undefined"
  16292. // jshint -W041
  16293. element.text(value == undefined ? '' : value);
  16294. });
  16295. });
  16296. /**
  16297. * @ngdoc directive
  16298. * @name ngBindTemplate
  16299. *
  16300. * @description
  16301. * The `ngBindTemplate` directive specifies that the element
  16302. * text content should be replaced with the interpolation of the template
  16303. * in the `ngBindTemplate` attribute.
  16304. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16305. * expressions. This directive is needed since some HTML elements
  16306. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16307. *
  16308. * @element ANY
  16309. * @param {string} ngBindTemplate template of form
  16310. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16311. *
  16312. * @example
  16313. * Try it here: enter text in text box and watch the greeting change.
  16314. <example>
  16315. <file name="index.html">
  16316. <script>
  16317. function Ctrl($scope) {
  16318. $scope.salutation = 'Hello';
  16319. $scope.name = 'World';
  16320. }
  16321. </script>
  16322. <div ng-controller="Ctrl">
  16323. Salutation: <input type="text" ng-model="salutation"><br>
  16324. Name: <input type="text" ng-model="name"><br>
  16325. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16326. </div>
  16327. </file>
  16328. <file name="protractor.js" type="protractor">
  16329. it('should check ng-bind', function() {
  16330. var salutationElem = element(by.binding('salutation'));
  16331. var salutationInput = element(by.model('salutation'));
  16332. var nameInput = element(by.model('name'));
  16333. expect(salutationElem.getText()).toBe('Hello World!');
  16334. salutationInput.clear();
  16335. salutationInput.sendKeys('Greetings');
  16336. nameInput.clear();
  16337. nameInput.sendKeys('user');
  16338. expect(salutationElem.getText()).toBe('Greetings user!');
  16339. });
  16340. </file>
  16341. </example>
  16342. */
  16343. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16344. return function(scope, element, attr) {
  16345. // TODO: move this to scenario runner
  16346. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16347. element.addClass('ng-binding').data('$binding', interpolateFn);
  16348. attr.$observe('ngBindTemplate', function(value) {
  16349. element.text(value);
  16350. });
  16351. };
  16352. }];
  16353. /**
  16354. * @ngdoc directive
  16355. * @name ngBindHtml
  16356. *
  16357. * @description
  16358. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16359. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16360. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16361. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16362. * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
  16363. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16364. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16365. *
  16366. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16367. * will have an exception (instead of an exploit.)
  16368. *
  16369. * @element ANY
  16370. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16371. *
  16372. * @example
  16373. Try it here: enter text in text box and watch the greeting change.
  16374. <example module="ngBindHtmlExample" deps="angular-sanitize.js">
  16375. <file name="index.html">
  16376. <div ng-controller="ngBindHtmlCtrl">
  16377. <p ng-bind-html="myHTML"></p>
  16378. </div>
  16379. </file>
  16380. <file name="script.js">
  16381. angular.module('ngBindHtmlExample', ['ngSanitize'])
  16382. .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
  16383. $scope.myHTML =
  16384. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
  16385. }]);
  16386. </file>
  16387. <file name="protractor.js" type="protractor">
  16388. it('should check ng-bind-html', function() {
  16389. expect(element(by.binding('myHTML')).getText()).toBe(
  16390. 'I am an HTMLstring with links! and other stuff');
  16391. });
  16392. </file>
  16393. </example>
  16394. */
  16395. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16396. return function(scope, element, attr) {
  16397. element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
  16398. var parsed = $parse(attr.ngBindHtml);
  16399. function getStringValue() { return (parsed(scope) || '').toString(); }
  16400. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16401. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16402. });
  16403. };
  16404. }];
  16405. function classDirective(name, selector) {
  16406. name = 'ngClass' + name;
  16407. return ['$animate', function($animate) {
  16408. return {
  16409. restrict: 'AC',
  16410. link: function(scope, element, attr) {
  16411. var oldVal;
  16412. scope.$watch(attr[name], ngClassWatchAction, true);
  16413. attr.$observe('class', function(value) {
  16414. ngClassWatchAction(scope.$eval(attr[name]));
  16415. });
  16416. if (name !== 'ngClass') {
  16417. scope.$watch('$index', function($index, old$index) {
  16418. // jshint bitwise: false
  16419. var mod = $index & 1;
  16420. if (mod !== (old$index & 1)) {
  16421. var classes = arrayClasses(scope.$eval(attr[name]));
  16422. mod === selector ?
  16423. addClasses(classes) :
  16424. removeClasses(classes);
  16425. }
  16426. });
  16427. }
  16428. function addClasses(classes) {
  16429. var newClasses = digestClassCounts(classes, 1);
  16430. attr.$addClass(newClasses);
  16431. }
  16432. function removeClasses(classes) {
  16433. var newClasses = digestClassCounts(classes, -1);
  16434. attr.$removeClass(newClasses);
  16435. }
  16436. function digestClassCounts (classes, count) {
  16437. var classCounts = element.data('$classCounts') || {};
  16438. var classesToUpdate = [];
  16439. forEach(classes, function (className) {
  16440. if (count > 0 || classCounts[className]) {
  16441. classCounts[className] = (classCounts[className] || 0) + count;
  16442. if (classCounts[className] === +(count > 0)) {
  16443. classesToUpdate.push(className);
  16444. }
  16445. }
  16446. });
  16447. element.data('$classCounts', classCounts);
  16448. return classesToUpdate.join(' ');
  16449. }
  16450. function updateClasses (oldClasses, newClasses) {
  16451. var toAdd = arrayDifference(newClasses, oldClasses);
  16452. var toRemove = arrayDifference(oldClasses, newClasses);
  16453. toRemove = digestClassCounts(toRemove, -1);
  16454. toAdd = digestClassCounts(toAdd, 1);
  16455. if (toAdd.length === 0) {
  16456. $animate.removeClass(element, toRemove);
  16457. } else if (toRemove.length === 0) {
  16458. $animate.addClass(element, toAdd);
  16459. } else {
  16460. $animate.setClass(element, toAdd, toRemove);
  16461. }
  16462. }
  16463. function ngClassWatchAction(newVal) {
  16464. if (selector === true || scope.$index % 2 === selector) {
  16465. var newClasses = arrayClasses(newVal || []);
  16466. if (!oldVal) {
  16467. addClasses(newClasses);
  16468. } else if (!equals(newVal,oldVal)) {
  16469. var oldClasses = arrayClasses(oldVal);
  16470. updateClasses(oldClasses, newClasses);
  16471. }
  16472. }
  16473. oldVal = shallowCopy(newVal);
  16474. }
  16475. }
  16476. };
  16477. function arrayDifference(tokens1, tokens2) {
  16478. var values = [];
  16479. outer:
  16480. for(var i = 0; i < tokens1.length; i++) {
  16481. var token = tokens1[i];
  16482. for(var j = 0; j < tokens2.length; j++) {
  16483. if(token == tokens2[j]) continue outer;
  16484. }
  16485. values.push(token);
  16486. }
  16487. return values;
  16488. }
  16489. function arrayClasses (classVal) {
  16490. if (isArray(classVal)) {
  16491. return classVal;
  16492. } else if (isString(classVal)) {
  16493. return classVal.split(' ');
  16494. } else if (isObject(classVal)) {
  16495. var classes = [], i = 0;
  16496. forEach(classVal, function(v, k) {
  16497. if (v) {
  16498. classes = classes.concat(k.split(' '));
  16499. }
  16500. });
  16501. return classes;
  16502. }
  16503. return classVal;
  16504. }
  16505. }];
  16506. }
  16507. /**
  16508. * @ngdoc directive
  16509. * @name ngClass
  16510. * @restrict AC
  16511. *
  16512. * @description
  16513. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16514. * an expression that represents all classes to be added.
  16515. *
  16516. * The directive operates in three different ways, depending on which of three types the expression
  16517. * evaluates to:
  16518. *
  16519. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16520. * names.
  16521. *
  16522. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16523. * one or more space-delimited class names.
  16524. *
  16525. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16526. * object with a truthy value the corresponding key is used as a class name.
  16527. *
  16528. * The directive won't add duplicate classes if a particular class was already set.
  16529. *
  16530. * When the expression changes, the previously added classes are removed and only then the
  16531. * new classes are added.
  16532. *
  16533. * @animations
  16534. * add - happens just before the class is applied to the element
  16535. * remove - happens just before the class is removed from the element
  16536. *
  16537. * @element ANY
  16538. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16539. * of the evaluation can be a string representing space delimited class
  16540. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16541. * names of the properties whose values are truthy will be added as css classes to the
  16542. * element.
  16543. *
  16544. * @example Example that demonstrates basic bindings via ngClass directive.
  16545. <example>
  16546. <file name="index.html">
  16547. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16548. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16549. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16550. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16551. <hr>
  16552. <p ng-class="style">Using String Syntax</p>
  16553. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16554. <hr>
  16555. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16556. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16557. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16558. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16559. </file>
  16560. <file name="style.css">
  16561. .strike {
  16562. text-decoration: line-through;
  16563. }
  16564. .bold {
  16565. font-weight: bold;
  16566. }
  16567. .red {
  16568. color: red;
  16569. }
  16570. </file>
  16571. <file name="protractor.js" type="protractor">
  16572. var ps = element.all(by.css('p'));
  16573. it('should let you toggle the class', function() {
  16574. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16575. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16576. element(by.model('important')).click();
  16577. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16578. element(by.model('error')).click();
  16579. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16580. });
  16581. it('should let you toggle string example', function() {
  16582. expect(ps.get(1).getAttribute('class')).toBe('');
  16583. element(by.model('style')).clear();
  16584. element(by.model('style')).sendKeys('red');
  16585. expect(ps.get(1).getAttribute('class')).toBe('red');
  16586. });
  16587. it('array example should have 3 classes', function() {
  16588. expect(ps.last().getAttribute('class')).toBe('');
  16589. element(by.model('style1')).sendKeys('bold');
  16590. element(by.model('style2')).sendKeys('strike');
  16591. element(by.model('style3')).sendKeys('red');
  16592. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16593. });
  16594. </file>
  16595. </example>
  16596. ## Animations
  16597. The example below demonstrates how to perform animations using ngClass.
  16598. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  16599. <file name="index.html">
  16600. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  16601. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  16602. <br>
  16603. <span class="base-class" ng-class="myVar">Sample Text</span>
  16604. </file>
  16605. <file name="style.css">
  16606. .base-class {
  16607. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16608. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16609. }
  16610. .base-class.my-class {
  16611. color: red;
  16612. font-size:3em;
  16613. }
  16614. </file>
  16615. <file name="protractor.js" type="protractor">
  16616. it('should check ng-class', function() {
  16617. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16618. toMatch(/my-class/);
  16619. element(by.id('setbtn')).click();
  16620. expect(element(by.css('.base-class')).getAttribute('class')).
  16621. toMatch(/my-class/);
  16622. element(by.id('clearbtn')).click();
  16623. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16624. toMatch(/my-class/);
  16625. });
  16626. </file>
  16627. </example>
  16628. ## ngClass and pre-existing CSS3 Transitions/Animations
  16629. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  16630. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  16631. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  16632. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  16633. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  16634. */
  16635. var ngClassDirective = classDirective('', true);
  16636. /**
  16637. * @ngdoc directive
  16638. * @name ngClassOdd
  16639. * @restrict AC
  16640. *
  16641. * @description
  16642. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16643. * {@link ng.directive:ngClass ngClass}, except they work in
  16644. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16645. *
  16646. * This directive can be applied only within the scope of an
  16647. * {@link ng.directive:ngRepeat ngRepeat}.
  16648. *
  16649. * @element ANY
  16650. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  16651. * of the evaluation can be a string representing space delimited class names or an array.
  16652. *
  16653. * @example
  16654. <example>
  16655. <file name="index.html">
  16656. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16657. <li ng-repeat="name in names">
  16658. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16659. {{name}}
  16660. </span>
  16661. </li>
  16662. </ol>
  16663. </file>
  16664. <file name="style.css">
  16665. .odd {
  16666. color: red;
  16667. }
  16668. .even {
  16669. color: blue;
  16670. }
  16671. </file>
  16672. <file name="protractor.js" type="protractor">
  16673. it('should check ng-class-odd and ng-class-even', function() {
  16674. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16675. toMatch(/odd/);
  16676. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16677. toMatch(/even/);
  16678. });
  16679. </file>
  16680. </example>
  16681. */
  16682. var ngClassOddDirective = classDirective('Odd', 0);
  16683. /**
  16684. * @ngdoc directive
  16685. * @name ngClassEven
  16686. * @restrict AC
  16687. *
  16688. * @description
  16689. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16690. * {@link ng.directive:ngClass ngClass}, except they work in
  16691. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16692. *
  16693. * This directive can be applied only within the scope of an
  16694. * {@link ng.directive:ngRepeat ngRepeat}.
  16695. *
  16696. * @element ANY
  16697. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  16698. * result of the evaluation can be a string representing space delimited class names or an array.
  16699. *
  16700. * @example
  16701. <example>
  16702. <file name="index.html">
  16703. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16704. <li ng-repeat="name in names">
  16705. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16706. {{name}} &nbsp; &nbsp; &nbsp;
  16707. </span>
  16708. </li>
  16709. </ol>
  16710. </file>
  16711. <file name="style.css">
  16712. .odd {
  16713. color: red;
  16714. }
  16715. .even {
  16716. color: blue;
  16717. }
  16718. </file>
  16719. <file name="protractor.js" type="protractor">
  16720. it('should check ng-class-odd and ng-class-even', function() {
  16721. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16722. toMatch(/odd/);
  16723. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16724. toMatch(/even/);
  16725. });
  16726. </file>
  16727. </example>
  16728. */
  16729. var ngClassEvenDirective = classDirective('Even', 1);
  16730. /**
  16731. * @ngdoc directive
  16732. * @name ngCloak
  16733. * @restrict AC
  16734. *
  16735. * @description
  16736. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  16737. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  16738. * directive to avoid the undesirable flicker effect caused by the html template display.
  16739. *
  16740. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  16741. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  16742. * of the browser view.
  16743. *
  16744. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  16745. * `angular.min.js`.
  16746. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  16747. *
  16748. * ```css
  16749. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  16750. * display: none !important;
  16751. * }
  16752. * ```
  16753. *
  16754. * When this css rule is loaded by the browser, all html elements (including their children) that
  16755. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  16756. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  16757. * the compiled element visible.
  16758. *
  16759. * For the best result, the `angular.js` script must be loaded in the head section of the html
  16760. * document; alternatively, the css rule above must be included in the external stylesheet of the
  16761. * application.
  16762. *
  16763. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  16764. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  16765. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  16766. *
  16767. * @element ANY
  16768. *
  16769. * @example
  16770. <example>
  16771. <file name="index.html">
  16772. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  16773. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  16774. </file>
  16775. <file name="protractor.js" type="protractor">
  16776. it('should remove the template directive and css class', function() {
  16777. expect($('#template1').getAttribute('ng-cloak')).
  16778. toBeNull();
  16779. expect($('#template2').getAttribute('ng-cloak')).
  16780. toBeNull();
  16781. });
  16782. </file>
  16783. </example>
  16784. *
  16785. */
  16786. var ngCloakDirective = ngDirective({
  16787. compile: function(element, attr) {
  16788. attr.$set('ngCloak', undefined);
  16789. element.removeClass('ng-cloak');
  16790. }
  16791. });
  16792. /**
  16793. * @ngdoc directive
  16794. * @name ngController
  16795. *
  16796. * @description
  16797. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  16798. * supports the principles behind the Model-View-Controller design pattern.
  16799. *
  16800. * MVC components in angular:
  16801. *
  16802. * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
  16803. * are accessed through bindings.
  16804. * * View — The template (HTML with data bindings) that is rendered into the View.
  16805. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  16806. * logic behind the application to decorate the scope with functions and values
  16807. *
  16808. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  16809. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  16810. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  16811. * and executed twice.
  16812. *
  16813. * @element ANY
  16814. * @scope
  16815. * @param {expression} ngController Name of a globally accessible constructor function or an
  16816. * {@link guide/expression expression} that on the current scope evaluates to a
  16817. * constructor function. The controller instance can be published into a scope property
  16818. * by specifying `as propertyName`.
  16819. *
  16820. * @example
  16821. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  16822. * greeting are methods declared on the controller (see source tab). These methods can
  16823. * easily be called from the angular markup. Any changes to the data are automatically reflected
  16824. * in the View without the need for a manual update.
  16825. *
  16826. * Two different declaration styles are included below:
  16827. *
  16828. * * one binds methods and properties directly onto the controller using `this`:
  16829. * `ng-controller="SettingsController1 as settings"`
  16830. * * one injects `$scope` into the controller:
  16831. * `ng-controller="SettingsController2"`
  16832. *
  16833. * The second option is more common in the Angular community, and is generally used in boilerplates
  16834. * and in this guide. However, there are advantages to binding properties directly to the controller
  16835. * and avoiding scope.
  16836. *
  16837. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  16838. * multiple controllers apply to an element.
  16839. * * If you are writing your controllers as classes you have easier access to the properties and
  16840. * methods, which will appear on the scope, from inside the controller code.
  16841. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  16842. * inheritance masking primitives.
  16843. *
  16844. * This example demonstrates the `controller as` syntax.
  16845. *
  16846. * <example name="ngControllerAs">
  16847. * <file name="index.html">
  16848. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  16849. * Name: <input type="text" ng-model="settings.name"/>
  16850. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  16851. * Contact:
  16852. * <ul>
  16853. * <li ng-repeat="contact in settings.contacts">
  16854. * <select ng-model="contact.type">
  16855. * <option>phone</option>
  16856. * <option>email</option>
  16857. * </select>
  16858. * <input type="text" ng-model="contact.value"/>
  16859. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  16860. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  16861. * </li>
  16862. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  16863. * </ul>
  16864. * </div>
  16865. * </file>
  16866. * <file name="app.js">
  16867. * function SettingsController1() {
  16868. * this.name = "John Smith";
  16869. * this.contacts = [
  16870. * {type: 'phone', value: '408 555 1212'},
  16871. * {type: 'email', value: 'john.smith@example.org'} ];
  16872. * }
  16873. *
  16874. * SettingsController1.prototype.greet = function() {
  16875. * alert(this.name);
  16876. * };
  16877. *
  16878. * SettingsController1.prototype.addContact = function() {
  16879. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  16880. * };
  16881. *
  16882. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  16883. * var index = this.contacts.indexOf(contactToRemove);
  16884. * this.contacts.splice(index, 1);
  16885. * };
  16886. *
  16887. * SettingsController1.prototype.clearContact = function(contact) {
  16888. * contact.type = 'phone';
  16889. * contact.value = '';
  16890. * };
  16891. * </file>
  16892. * <file name="protractor.js" type="protractor">
  16893. * it('should check controller as', function() {
  16894. * var container = element(by.id('ctrl-as-exmpl'));
  16895. * expect(container.findElement(by.model('settings.name'))
  16896. * .getAttribute('value')).toBe('John Smith');
  16897. *
  16898. * var firstRepeat =
  16899. * container.findElement(by.repeater('contact in settings.contacts').row(0));
  16900. * var secondRepeat =
  16901. * container.findElement(by.repeater('contact in settings.contacts').row(1));
  16902. *
  16903. * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16904. * .toBe('408 555 1212');
  16905. *
  16906. * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16907. * .toBe('john.smith@example.org');
  16908. *
  16909. * firstRepeat.findElement(by.linkText('clear')).click();
  16910. *
  16911. * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16912. * .toBe('');
  16913. *
  16914. * container.findElement(by.linkText('add')).click();
  16915. *
  16916. * expect(container.findElement(by.repeater('contact in settings.contacts').row(2))
  16917. * .findElement(by.model('contact.value'))
  16918. * .getAttribute('value'))
  16919. * .toBe('yourname@example.org');
  16920. * });
  16921. * </file>
  16922. * </example>
  16923. *
  16924. * This example demonstrates the "attach to `$scope`" style of controller.
  16925. *
  16926. * <example name="ngController">
  16927. * <file name="index.html">
  16928. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  16929. * Name: <input type="text" ng-model="name"/>
  16930. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  16931. * Contact:
  16932. * <ul>
  16933. * <li ng-repeat="contact in contacts">
  16934. * <select ng-model="contact.type">
  16935. * <option>phone</option>
  16936. * <option>email</option>
  16937. * </select>
  16938. * <input type="text" ng-model="contact.value"/>
  16939. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  16940. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  16941. * </li>
  16942. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  16943. * </ul>
  16944. * </div>
  16945. * </file>
  16946. * <file name="app.js">
  16947. * function SettingsController2($scope) {
  16948. * $scope.name = "John Smith";
  16949. * $scope.contacts = [
  16950. * {type:'phone', value:'408 555 1212'},
  16951. * {type:'email', value:'john.smith@example.org'} ];
  16952. *
  16953. * $scope.greet = function() {
  16954. * alert($scope.name);
  16955. * };
  16956. *
  16957. * $scope.addContact = function() {
  16958. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  16959. * };
  16960. *
  16961. * $scope.removeContact = function(contactToRemove) {
  16962. * var index = $scope.contacts.indexOf(contactToRemove);
  16963. * $scope.contacts.splice(index, 1);
  16964. * };
  16965. *
  16966. * $scope.clearContact = function(contact) {
  16967. * contact.type = 'phone';
  16968. * contact.value = '';
  16969. * };
  16970. * }
  16971. * </file>
  16972. * <file name="protractor.js" type="protractor">
  16973. * it('should check controller', function() {
  16974. * var container = element(by.id('ctrl-exmpl'));
  16975. *
  16976. * expect(container.findElement(by.model('name'))
  16977. * .getAttribute('value')).toBe('John Smith');
  16978. *
  16979. * var firstRepeat =
  16980. * container.findElement(by.repeater('contact in contacts').row(0));
  16981. * var secondRepeat =
  16982. * container.findElement(by.repeater('contact in contacts').row(1));
  16983. *
  16984. * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16985. * .toBe('408 555 1212');
  16986. * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16987. * .toBe('john.smith@example.org');
  16988. *
  16989. * firstRepeat.findElement(by.linkText('clear')).click();
  16990. *
  16991. * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16992. * .toBe('');
  16993. *
  16994. * container.findElement(by.linkText('add')).click();
  16995. *
  16996. * expect(container.findElement(by.repeater('contact in contacts').row(2))
  16997. * .findElement(by.model('contact.value'))
  16998. * .getAttribute('value'))
  16999. * .toBe('yourname@example.org');
  17000. * });
  17001. * </file>
  17002. *</example>
  17003. */
  17004. var ngControllerDirective = [function() {
  17005. return {
  17006. scope: true,
  17007. controller: '@',
  17008. priority: 500
  17009. };
  17010. }];
  17011. /**
  17012. * @ngdoc directive
  17013. * @name ngCsp
  17014. *
  17015. * @element html
  17016. * @description
  17017. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  17018. *
  17019. * This is necessary when developing things like Google Chrome Extensions.
  17020. *
  17021. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  17022. * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
  17023. * any of these restrictions.
  17024. *
  17025. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  17026. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  17027. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  17028. * be raised.
  17029. *
  17030. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  17031. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  17032. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  17033. *
  17034. * In order to use this feature put the `ngCsp` directive on the root element of the application.
  17035. *
  17036. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  17037. *
  17038. * @example
  17039. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  17040. ```html
  17041. <!doctype html>
  17042. <html ng-app ng-csp>
  17043. ...
  17044. ...
  17045. </html>
  17046. ```
  17047. */
  17048. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
  17049. // the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
  17050. // anywhere in the current doc
  17051. /**
  17052. * @ngdoc directive
  17053. * @name ngClick
  17054. *
  17055. * @description
  17056. * The ngClick directive allows you to specify custom behavior when
  17057. * an element is clicked.
  17058. *
  17059. * @element ANY
  17060. * @priority 0
  17061. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  17062. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  17063. *
  17064. * @example
  17065. <example>
  17066. <file name="index.html">
  17067. <button ng-click="count = count + 1" ng-init="count=0">
  17068. Increment
  17069. </button>
  17070. count: {{count}}
  17071. </file>
  17072. <file name="protractor.js" type="protractor">
  17073. it('should check ng-click', function() {
  17074. expect(element(by.binding('count')).getText()).toMatch('0');
  17075. element(by.css('button')).click();
  17076. expect(element(by.binding('count')).getText()).toMatch('1');
  17077. });
  17078. </file>
  17079. </example>
  17080. */
  17081. /*
  17082. * A directive that allows creation of custom onclick handlers that are defined as angular
  17083. * expressions and are compiled and executed within the current scope.
  17084. *
  17085. * Events that are handled via these handler are always configured not to propagate further.
  17086. */
  17087. var ngEventDirectives = {};
  17088. forEach(
  17089. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  17090. function(name) {
  17091. var directiveName = directiveNormalize('ng-' + name);
  17092. ngEventDirectives[directiveName] = ['$parse', function($parse) {
  17093. return {
  17094. compile: function($element, attr) {
  17095. var fn = $parse(attr[directiveName]);
  17096. return function(scope, element, attr) {
  17097. element.on(lowercase(name), function(event) {
  17098. scope.$apply(function() {
  17099. fn(scope, {$event:event});
  17100. });
  17101. });
  17102. };
  17103. }
  17104. };
  17105. }];
  17106. }
  17107. );
  17108. /**
  17109. * @ngdoc directive
  17110. * @name ngDblclick
  17111. *
  17112. * @description
  17113. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  17114. *
  17115. * @element ANY
  17116. * @priority 0
  17117. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  17118. * a dblclick. (The Event object is available as `$event`)
  17119. *
  17120. * @example
  17121. <example>
  17122. <file name="index.html">
  17123. <button ng-dblclick="count = count + 1" ng-init="count=0">
  17124. Increment (on double click)
  17125. </button>
  17126. count: {{count}}
  17127. </file>
  17128. </example>
  17129. */
  17130. /**
  17131. * @ngdoc directive
  17132. * @name ngMousedown
  17133. *
  17134. * @description
  17135. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  17136. *
  17137. * @element ANY
  17138. * @priority 0
  17139. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  17140. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  17141. *
  17142. * @example
  17143. <example>
  17144. <file name="index.html">
  17145. <button ng-mousedown="count = count + 1" ng-init="count=0">
  17146. Increment (on mouse down)
  17147. </button>
  17148. count: {{count}}
  17149. </file>
  17150. </example>
  17151. */
  17152. /**
  17153. * @ngdoc directive
  17154. * @name ngMouseup
  17155. *
  17156. * @description
  17157. * Specify custom behavior on mouseup event.
  17158. *
  17159. * @element ANY
  17160. * @priority 0
  17161. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  17162. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  17163. *
  17164. * @example
  17165. <example>
  17166. <file name="index.html">
  17167. <button ng-mouseup="count = count + 1" ng-init="count=0">
  17168. Increment (on mouse up)
  17169. </button>
  17170. count: {{count}}
  17171. </file>
  17172. </example>
  17173. */
  17174. /**
  17175. * @ngdoc directive
  17176. * @name ngMouseover
  17177. *
  17178. * @description
  17179. * Specify custom behavior on mouseover event.
  17180. *
  17181. * @element ANY
  17182. * @priority 0
  17183. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  17184. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  17185. *
  17186. * @example
  17187. <example>
  17188. <file name="index.html">
  17189. <button ng-mouseover="count = count + 1" ng-init="count=0">
  17190. Increment (when mouse is over)
  17191. </button>
  17192. count: {{count}}
  17193. </file>
  17194. </example>
  17195. */
  17196. /**
  17197. * @ngdoc directive
  17198. * @name ngMouseenter
  17199. *
  17200. * @description
  17201. * Specify custom behavior on mouseenter event.
  17202. *
  17203. * @element ANY
  17204. * @priority 0
  17205. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  17206. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  17207. *
  17208. * @example
  17209. <example>
  17210. <file name="index.html">
  17211. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  17212. Increment (when mouse enters)
  17213. </button>
  17214. count: {{count}}
  17215. </file>
  17216. </example>
  17217. */
  17218. /**
  17219. * @ngdoc directive
  17220. * @name ngMouseleave
  17221. *
  17222. * @description
  17223. * Specify custom behavior on mouseleave event.
  17224. *
  17225. * @element ANY
  17226. * @priority 0
  17227. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17228. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17229. *
  17230. * @example
  17231. <example>
  17232. <file name="index.html">
  17233. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17234. Increment (when mouse leaves)
  17235. </button>
  17236. count: {{count}}
  17237. </file>
  17238. </example>
  17239. */
  17240. /**
  17241. * @ngdoc directive
  17242. * @name ngMousemove
  17243. *
  17244. * @description
  17245. * Specify custom behavior on mousemove event.
  17246. *
  17247. * @element ANY
  17248. * @priority 0
  17249. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17250. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17251. *
  17252. * @example
  17253. <example>
  17254. <file name="index.html">
  17255. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17256. Increment (when mouse moves)
  17257. </button>
  17258. count: {{count}}
  17259. </file>
  17260. </example>
  17261. */
  17262. /**
  17263. * @ngdoc directive
  17264. * @name ngKeydown
  17265. *
  17266. * @description
  17267. * Specify custom behavior on keydown event.
  17268. *
  17269. * @element ANY
  17270. * @priority 0
  17271. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17272. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17273. *
  17274. * @example
  17275. <example>
  17276. <file name="index.html">
  17277. <input ng-keydown="count = count + 1" ng-init="count=0">
  17278. key down count: {{count}}
  17279. </file>
  17280. </example>
  17281. */
  17282. /**
  17283. * @ngdoc directive
  17284. * @name ngKeyup
  17285. *
  17286. * @description
  17287. * Specify custom behavior on keyup event.
  17288. *
  17289. * @element ANY
  17290. * @priority 0
  17291. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17292. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17293. *
  17294. * @example
  17295. <example>
  17296. <file name="index.html">
  17297. <p>Typing in the input box below updates the key count</p>
  17298. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  17299. <p>Typing in the input box below updates the keycode</p>
  17300. <input ng-keyup="event=$event">
  17301. <p>event keyCode: {{ event.keyCode }}</p>
  17302. <p>event altKey: {{ event.altKey }}</p>
  17303. </file>
  17304. </example>
  17305. */
  17306. /**
  17307. * @ngdoc directive
  17308. * @name ngKeypress
  17309. *
  17310. * @description
  17311. * Specify custom behavior on keypress event.
  17312. *
  17313. * @element ANY
  17314. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17315. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17316. * and can be interrogated for keyCode, altKey, etc.)
  17317. *
  17318. * @example
  17319. <example>
  17320. <file name="index.html">
  17321. <input ng-keypress="count = count + 1" ng-init="count=0">
  17322. key press count: {{count}}
  17323. </file>
  17324. </example>
  17325. */
  17326. /**
  17327. * @ngdoc directive
  17328. * @name ngSubmit
  17329. *
  17330. * @description
  17331. * Enables binding angular expressions to onsubmit events.
  17332. *
  17333. * Additionally it prevents the default action (which for form means sending the request to the
  17334. * server and reloading the current page), but only if the form does not contain `action`,
  17335. * `data-action`, or `x-action` attributes.
  17336. *
  17337. * @element form
  17338. * @priority 0
  17339. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17340. * ({@link guide/expression#-event- Event object is available as `$event`})
  17341. *
  17342. * @example
  17343. <example>
  17344. <file name="index.html">
  17345. <script>
  17346. function Ctrl($scope) {
  17347. $scope.list = [];
  17348. $scope.text = 'hello';
  17349. $scope.submit = function() {
  17350. if ($scope.text) {
  17351. $scope.list.push(this.text);
  17352. $scope.text = '';
  17353. }
  17354. };
  17355. }
  17356. </script>
  17357. <form ng-submit="submit()" ng-controller="Ctrl">
  17358. Enter text and hit enter:
  17359. <input type="text" ng-model="text" name="text" />
  17360. <input type="submit" id="submit" value="Submit" />
  17361. <pre>list={{list}}</pre>
  17362. </form>
  17363. </file>
  17364. <file name="protractor.js" type="protractor">
  17365. it('should check ng-submit', function() {
  17366. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17367. element(by.css('#submit')).click();
  17368. expect(element(by.binding('list')).getText()).toContain('hello');
  17369. expect(element(by.input('text')).getAttribute('value')).toBe('');
  17370. });
  17371. it('should ignore empty strings', function() {
  17372. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17373. element(by.css('#submit')).click();
  17374. element(by.css('#submit')).click();
  17375. expect(element(by.binding('list')).getText()).toContain('hello');
  17376. });
  17377. </file>
  17378. </example>
  17379. */
  17380. /**
  17381. * @ngdoc directive
  17382. * @name ngFocus
  17383. *
  17384. * @description
  17385. * Specify custom behavior on focus event.
  17386. *
  17387. * @element window, input, select, textarea, a
  17388. * @priority 0
  17389. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17390. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17391. *
  17392. * @example
  17393. * See {@link ng.directive:ngClick ngClick}
  17394. */
  17395. /**
  17396. * @ngdoc directive
  17397. * @name ngBlur
  17398. *
  17399. * @description
  17400. * Specify custom behavior on blur event.
  17401. *
  17402. * @element window, input, select, textarea, a
  17403. * @priority 0
  17404. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17405. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17406. *
  17407. * @example
  17408. * See {@link ng.directive:ngClick ngClick}
  17409. */
  17410. /**
  17411. * @ngdoc directive
  17412. * @name ngCopy
  17413. *
  17414. * @description
  17415. * Specify custom behavior on copy event.
  17416. *
  17417. * @element window, input, select, textarea, a
  17418. * @priority 0
  17419. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17420. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17421. *
  17422. * @example
  17423. <example>
  17424. <file name="index.html">
  17425. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17426. copied: {{copied}}
  17427. </file>
  17428. </example>
  17429. */
  17430. /**
  17431. * @ngdoc directive
  17432. * @name ngCut
  17433. *
  17434. * @description
  17435. * Specify custom behavior on cut event.
  17436. *
  17437. * @element window, input, select, textarea, a
  17438. * @priority 0
  17439. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17440. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17441. *
  17442. * @example
  17443. <example>
  17444. <file name="index.html">
  17445. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17446. cut: {{cut}}
  17447. </file>
  17448. </example>
  17449. */
  17450. /**
  17451. * @ngdoc directive
  17452. * @name ngPaste
  17453. *
  17454. * @description
  17455. * Specify custom behavior on paste event.
  17456. *
  17457. * @element window, input, select, textarea, a
  17458. * @priority 0
  17459. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17460. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17461. *
  17462. * @example
  17463. <example>
  17464. <file name="index.html">
  17465. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17466. pasted: {{paste}}
  17467. </file>
  17468. </example>
  17469. */
  17470. /**
  17471. * @ngdoc directive
  17472. * @name ngIf
  17473. * @restrict A
  17474. *
  17475. * @description
  17476. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17477. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17478. * value then the element is removed from the DOM, otherwise a clone of the
  17479. * element is reinserted into the DOM.
  17480. *
  17481. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17482. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17483. * case when this difference is significant is when using css selectors that rely on an element's
  17484. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17485. *
  17486. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17487. * is created when the element is restored. The scope created within `ngIf` inherits from
  17488. * its parent scope using
  17489. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance).
  17490. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17491. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17492. * variable within the child scope will override (hide) the value in the parent scope.
  17493. *
  17494. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17495. * is if an element's class attribute is directly modified after it's compiled, using something like
  17496. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17497. * the added class will be lost because the original compiled state is used to regenerate the element.
  17498. *
  17499. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17500. * and `leave` effects.
  17501. *
  17502. * @animations
  17503. * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
  17504. * leave - happens just before the ngIf contents are removed from the DOM
  17505. *
  17506. * @element ANY
  17507. * @scope
  17508. * @priority 600
  17509. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17510. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17511. * element is added to the DOM tree.
  17512. *
  17513. * @example
  17514. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17515. <file name="index.html">
  17516. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17517. Show when checked:
  17518. <span ng-if="checked" class="animate-if">
  17519. I'm removed when the checkbox is unchecked.
  17520. </span>
  17521. </file>
  17522. <file name="animations.css">
  17523. .animate-if {
  17524. background:white;
  17525. border:1px solid black;
  17526. padding:10px;
  17527. }
  17528. .animate-if.ng-enter, .animate-if.ng-leave {
  17529. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17530. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17531. }
  17532. .animate-if.ng-enter,
  17533. .animate-if.ng-leave.ng-leave-active {
  17534. opacity:0;
  17535. }
  17536. .animate-if.ng-leave,
  17537. .animate-if.ng-enter.ng-enter-active {
  17538. opacity:1;
  17539. }
  17540. </file>
  17541. </example>
  17542. */
  17543. var ngIfDirective = ['$animate', function($animate) {
  17544. return {
  17545. transclude: 'element',
  17546. priority: 600,
  17547. terminal: true,
  17548. restrict: 'A',
  17549. $$tlb: true,
  17550. link: function ($scope, $element, $attr, ctrl, $transclude) {
  17551. var block, childScope, previousElements;
  17552. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  17553. if (toBoolean(value)) {
  17554. if (!childScope) {
  17555. childScope = $scope.$new();
  17556. $transclude(childScope, function (clone) {
  17557. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  17558. // Note: We only need the first/last node of the cloned nodes.
  17559. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17560. // by a directive with templateUrl when its template arrives.
  17561. block = {
  17562. clone: clone
  17563. };
  17564. $animate.enter(clone, $element.parent(), $element);
  17565. });
  17566. }
  17567. } else {
  17568. if(previousElements) {
  17569. previousElements.remove();
  17570. previousElements = null;
  17571. }
  17572. if(childScope) {
  17573. childScope.$destroy();
  17574. childScope = null;
  17575. }
  17576. if(block) {
  17577. previousElements = getBlockElements(block.clone);
  17578. $animate.leave(previousElements, function() {
  17579. previousElements = null;
  17580. });
  17581. block = null;
  17582. }
  17583. }
  17584. });
  17585. }
  17586. };
  17587. }];
  17588. /**
  17589. * @ngdoc directive
  17590. * @name ngInclude
  17591. * @restrict ECA
  17592. *
  17593. * @description
  17594. * Fetches, compiles and includes an external HTML fragment.
  17595. *
  17596. * By default, the template URL is restricted to the same domain and protocol as the
  17597. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17598. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  17599. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  17600. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  17601. * ng.$sce Strict Contextual Escaping}.
  17602. *
  17603. * In addition, the browser's
  17604. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17605. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17606. * policy may further restrict whether the template is successfully loaded.
  17607. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  17608. * access on some browsers.
  17609. *
  17610. * @animations
  17611. * enter - animation is used to bring new content into the browser.
  17612. * leave - animation is used to animate existing content away.
  17613. *
  17614. * The enter and leave animation occur concurrently.
  17615. *
  17616. * @scope
  17617. * @priority 400
  17618. *
  17619. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  17620. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  17621. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  17622. *
  17623. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  17624. * $anchorScroll} to scroll the viewport after the content is loaded.
  17625. *
  17626. * - If the attribute is not set, disable scrolling.
  17627. * - If the attribute is set without value, enable scrolling.
  17628. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  17629. *
  17630. * @example
  17631. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17632. <file name="index.html">
  17633. <div ng-controller="Ctrl">
  17634. <select ng-model="template" ng-options="t.name for t in templates">
  17635. <option value="">(blank)</option>
  17636. </select>
  17637. url of the template: <tt>{{template.url}}</tt>
  17638. <hr/>
  17639. <div class="slide-animate-container">
  17640. <div class="slide-animate" ng-include="template.url"></div>
  17641. </div>
  17642. </div>
  17643. </file>
  17644. <file name="script.js">
  17645. function Ctrl($scope) {
  17646. $scope.templates =
  17647. [ { name: 'template1.html', url: 'template1.html'},
  17648. { name: 'template2.html', url: 'template2.html'} ];
  17649. $scope.template = $scope.templates[0];
  17650. }
  17651. </file>
  17652. <file name="template1.html">
  17653. Content of template1.html
  17654. </file>
  17655. <file name="template2.html">
  17656. Content of template2.html
  17657. </file>
  17658. <file name="animations.css">
  17659. .slide-animate-container {
  17660. position:relative;
  17661. background:white;
  17662. border:1px solid black;
  17663. height:40px;
  17664. overflow:hidden;
  17665. }
  17666. .slide-animate {
  17667. padding:10px;
  17668. }
  17669. .slide-animate.ng-enter, .slide-animate.ng-leave {
  17670. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17671. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17672. position:absolute;
  17673. top:0;
  17674. left:0;
  17675. right:0;
  17676. bottom:0;
  17677. display:block;
  17678. padding:10px;
  17679. }
  17680. .slide-animate.ng-enter {
  17681. top:-50px;
  17682. }
  17683. .slide-animate.ng-enter.ng-enter-active {
  17684. top:0;
  17685. }
  17686. .slide-animate.ng-leave {
  17687. top:0;
  17688. }
  17689. .slide-animate.ng-leave.ng-leave-active {
  17690. top:50px;
  17691. }
  17692. </file>
  17693. <file name="protractor.js" type="protractor">
  17694. var templateSelect = element(by.model('template'));
  17695. var includeElem = element(by.css('[ng-include]'));
  17696. it('should load template1.html', function() {
  17697. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  17698. });
  17699. it('should load template2.html', function() {
  17700. if (browser.params.browser == 'firefox') {
  17701. // Firefox can't handle using selects
  17702. // See https://github.com/angular/protractor/issues/480
  17703. return;
  17704. }
  17705. templateSelect.click();
  17706. templateSelect.element.all(by.css('option')).get(2).click();
  17707. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  17708. });
  17709. it('should change to blank', function() {
  17710. if (browser.params.browser == 'firefox') {
  17711. // Firefox can't handle using selects
  17712. return;
  17713. }
  17714. templateSelect.click();
  17715. templateSelect.element.all(by.css('option')).get(0).click();
  17716. expect(includeElem.isPresent()).toBe(false);
  17717. });
  17718. </file>
  17719. </example>
  17720. */
  17721. /**
  17722. * @ngdoc event
  17723. * @name ngInclude#$includeContentRequested
  17724. * @eventType emit on the scope ngInclude was declared in
  17725. * @description
  17726. * Emitted every time the ngInclude content is requested.
  17727. */
  17728. /**
  17729. * @ngdoc event
  17730. * @name ngInclude#$includeContentLoaded
  17731. * @eventType emit on the current ngInclude scope
  17732. * @description
  17733. * Emitted every time the ngInclude content is reloaded.
  17734. */
  17735. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  17736. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  17737. return {
  17738. restrict: 'ECA',
  17739. priority: 400,
  17740. terminal: true,
  17741. transclude: 'element',
  17742. controller: angular.noop,
  17743. compile: function(element, attr) {
  17744. var srcExp = attr.ngInclude || attr.src,
  17745. onloadExp = attr.onload || '',
  17746. autoScrollExp = attr.autoscroll;
  17747. return function(scope, $element, $attr, ctrl, $transclude) {
  17748. var changeCounter = 0,
  17749. currentScope,
  17750. previousElement,
  17751. currentElement;
  17752. var cleanupLastIncludeContent = function() {
  17753. if(previousElement) {
  17754. previousElement.remove();
  17755. previousElement = null;
  17756. }
  17757. if(currentScope) {
  17758. currentScope.$destroy();
  17759. currentScope = null;
  17760. }
  17761. if(currentElement) {
  17762. $animate.leave(currentElement, function() {
  17763. previousElement = null;
  17764. });
  17765. previousElement = currentElement;
  17766. currentElement = null;
  17767. }
  17768. };
  17769. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  17770. var afterAnimation = function() {
  17771. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  17772. $anchorScroll();
  17773. }
  17774. };
  17775. var thisChangeId = ++changeCounter;
  17776. if (src) {
  17777. $http.get(src, {cache: $templateCache}).success(function(response) {
  17778. if (thisChangeId !== changeCounter) return;
  17779. var newScope = scope.$new();
  17780. ctrl.template = response;
  17781. // Note: This will also link all children of ng-include that were contained in the original
  17782. // html. If that content contains controllers, ... they could pollute/change the scope.
  17783. // However, using ng-include on an element with additional content does not make sense...
  17784. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  17785. // function is called before linking the content, which would apply child
  17786. // directives to non existing elements.
  17787. var clone = $transclude(newScope, function(clone) {
  17788. cleanupLastIncludeContent();
  17789. $animate.enter(clone, null, $element, afterAnimation);
  17790. });
  17791. currentScope = newScope;
  17792. currentElement = clone;
  17793. currentScope.$emit('$includeContentLoaded');
  17794. scope.$eval(onloadExp);
  17795. }).error(function() {
  17796. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  17797. });
  17798. scope.$emit('$includeContentRequested');
  17799. } else {
  17800. cleanupLastIncludeContent();
  17801. ctrl.template = null;
  17802. }
  17803. });
  17804. };
  17805. }
  17806. };
  17807. }];
  17808. // This directive is called during the $transclude call of the first `ngInclude` directive.
  17809. // It will replace and compile the content of the element with the loaded template.
  17810. // We need this directive so that the element content is already filled when
  17811. // the link function of another directive on the same element as ngInclude
  17812. // is called.
  17813. var ngIncludeFillContentDirective = ['$compile',
  17814. function($compile) {
  17815. return {
  17816. restrict: 'ECA',
  17817. priority: -400,
  17818. require: 'ngInclude',
  17819. link: function(scope, $element, $attr, ctrl) {
  17820. $element.html(ctrl.template);
  17821. $compile($element.contents())(scope);
  17822. }
  17823. };
  17824. }];
  17825. /**
  17826. * @ngdoc directive
  17827. * @name ngInit
  17828. * @restrict AC
  17829. *
  17830. * @description
  17831. * The `ngInit` directive allows you to evaluate an expression in the
  17832. * current scope.
  17833. *
  17834. * <div class="alert alert-error">
  17835. * The only appropriate use of `ngInit` is for aliasing special properties of
  17836. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  17837. * should use {@link guide/controller controllers} rather than `ngInit`
  17838. * to initialize values on a scope.
  17839. * </div>
  17840. * <div class="alert alert-warning">
  17841. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  17842. * sure you have parenthesis for correct precedence:
  17843. * <pre class="prettyprint">
  17844. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  17845. * </pre>
  17846. * </div>
  17847. *
  17848. * @priority 450
  17849. *
  17850. * @element ANY
  17851. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  17852. *
  17853. * @example
  17854. <example>
  17855. <file name="index.html">
  17856. <script>
  17857. function Ctrl($scope) {
  17858. $scope.list = [['a', 'b'], ['c', 'd']];
  17859. }
  17860. </script>
  17861. <div ng-controller="Ctrl">
  17862. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  17863. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  17864. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  17865. </div>
  17866. </div>
  17867. </div>
  17868. </file>
  17869. <file name="protractor.js" type="protractor">
  17870. it('should alias index positions', function() {
  17871. var elements = element.all(by.css('.example-init'));
  17872. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  17873. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  17874. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  17875. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  17876. });
  17877. </file>
  17878. </example>
  17879. */
  17880. var ngInitDirective = ngDirective({
  17881. priority: 450,
  17882. compile: function() {
  17883. return {
  17884. pre: function(scope, element, attrs) {
  17885. scope.$eval(attrs.ngInit);
  17886. }
  17887. };
  17888. }
  17889. });
  17890. /**
  17891. * @ngdoc directive
  17892. * @name ngNonBindable
  17893. * @restrict AC
  17894. * @priority 1000
  17895. *
  17896. * @description
  17897. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  17898. * DOM element. This is useful if the element contains what appears to be Angular directives and
  17899. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  17900. * displays snippets of code, for instance.
  17901. *
  17902. * @element ANY
  17903. *
  17904. * @example
  17905. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  17906. * but the one wrapped in `ngNonBindable` is left alone.
  17907. *
  17908. * @example
  17909. <example>
  17910. <file name="index.html">
  17911. <div>Normal: {{1 + 2}}</div>
  17912. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  17913. </file>
  17914. <file name="protractor.js" type="protractor">
  17915. it('should check ng-non-bindable', function() {
  17916. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  17917. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  17918. });
  17919. </file>
  17920. </example>
  17921. */
  17922. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  17923. /**
  17924. * @ngdoc directive
  17925. * @name ngPluralize
  17926. * @restrict EA
  17927. *
  17928. * @description
  17929. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  17930. * These rules are bundled with angular.js, but can be overridden
  17931. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  17932. * by specifying the mappings between
  17933. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  17934. * and the strings to be displayed.
  17935. *
  17936. * # Plural categories and explicit number rules
  17937. * There are two
  17938. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  17939. * in Angular's default en-US locale: "one" and "other".
  17940. *
  17941. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  17942. * any number that is not 1), an explicit number rule can only match one number. For example, the
  17943. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  17944. * and explicit number rules throughout the rest of this documentation.
  17945. *
  17946. * # Configuring ngPluralize
  17947. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  17948. * You can also provide an optional attribute, `offset`.
  17949. *
  17950. * The value of the `count` attribute can be either a string or an {@link guide/expression
  17951. * Angular expression}; these are evaluated on the current scope for its bound value.
  17952. *
  17953. * The `when` attribute specifies the mappings between plural categories and the actual
  17954. * string to be displayed. The value of the attribute should be a JSON object.
  17955. *
  17956. * The following example shows how to configure ngPluralize:
  17957. *
  17958. * ```html
  17959. * <ng-pluralize count="personCount"
  17960. when="{'0': 'Nobody is viewing.',
  17961. * 'one': '1 person is viewing.',
  17962. * 'other': '{} people are viewing.'}">
  17963. * </ng-pluralize>
  17964. *```
  17965. *
  17966. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  17967. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  17968. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  17969. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  17970. * show "a dozen people are viewing".
  17971. *
  17972. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  17973. * into pluralized strings. In the previous example, Angular will replace `{}` with
  17974. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  17975. * for <span ng-non-bindable>{{numberExpression}}</span>.
  17976. *
  17977. * # Configuring ngPluralize with offset
  17978. * The `offset` attribute allows further customization of pluralized text, which can result in
  17979. * a better user experience. For example, instead of the message "4 people are viewing this document",
  17980. * you might display "John, Kate and 2 others are viewing this document".
  17981. * The offset attribute allows you to offset a number by any desired value.
  17982. * Let's take a look at an example:
  17983. *
  17984. * ```html
  17985. * <ng-pluralize count="personCount" offset=2
  17986. * when="{'0': 'Nobody is viewing.',
  17987. * '1': '{{person1}} is viewing.',
  17988. * '2': '{{person1}} and {{person2}} are viewing.',
  17989. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  17990. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  17991. * </ng-pluralize>
  17992. * ```
  17993. *
  17994. * Notice that we are still using two plural categories(one, other), but we added
  17995. * three explicit number rules 0, 1 and 2.
  17996. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  17997. * When three people view the document, no explicit number rule is found, so
  17998. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  17999. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
  18000. * is shown.
  18001. *
  18002. * Note that when you specify offsets, you must provide explicit number rules for
  18003. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  18004. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  18005. * plural categories "one" and "other".
  18006. *
  18007. * @param {string|expression} count The variable to be bound to.
  18008. * @param {string} when The mapping between plural category to its corresponding strings.
  18009. * @param {number=} offset Offset to deduct from the total number.
  18010. *
  18011. * @example
  18012. <example>
  18013. <file name="index.html">
  18014. <script>
  18015. function Ctrl($scope) {
  18016. $scope.person1 = 'Igor';
  18017. $scope.person2 = 'Misko';
  18018. $scope.personCount = 1;
  18019. }
  18020. </script>
  18021. <div ng-controller="Ctrl">
  18022. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  18023. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  18024. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  18025. <!--- Example with simple pluralization rules for en locale --->
  18026. Without Offset:
  18027. <ng-pluralize count="personCount"
  18028. when="{'0': 'Nobody is viewing.',
  18029. 'one': '1 person is viewing.',
  18030. 'other': '{} people are viewing.'}">
  18031. </ng-pluralize><br>
  18032. <!--- Example with offset --->
  18033. With Offset(2):
  18034. <ng-pluralize count="personCount" offset=2
  18035. when="{'0': 'Nobody is viewing.',
  18036. '1': '{{person1}} is viewing.',
  18037. '2': '{{person1}} and {{person2}} are viewing.',
  18038. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18039. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18040. </ng-pluralize>
  18041. </div>
  18042. </file>
  18043. <file name="protractor.js" type="protractor">
  18044. it('should show correct pluralized string', function() {
  18045. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  18046. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18047. var countInput = element(by.model('personCount'));
  18048. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  18049. expect(withOffset.getText()).toEqual('Igor is viewing.');
  18050. countInput.clear();
  18051. countInput.sendKeys('0');
  18052. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  18053. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  18054. countInput.clear();
  18055. countInput.sendKeys('2');
  18056. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  18057. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  18058. countInput.clear();
  18059. countInput.sendKeys('3');
  18060. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  18061. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  18062. countInput.clear();
  18063. countInput.sendKeys('4');
  18064. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  18065. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  18066. });
  18067. it('should show data-bound names', function() {
  18068. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18069. var personCount = element(by.model('personCount'));
  18070. var person1 = element(by.model('person1'));
  18071. var person2 = element(by.model('person2'));
  18072. personCount.clear();
  18073. personCount.sendKeys('4');
  18074. person1.clear();
  18075. person1.sendKeys('Di');
  18076. person2.clear();
  18077. person2.sendKeys('Vojta');
  18078. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  18079. });
  18080. </file>
  18081. </example>
  18082. */
  18083. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  18084. var BRACE = /{}/g;
  18085. return {
  18086. restrict: 'EA',
  18087. link: function(scope, element, attr) {
  18088. var numberExp = attr.count,
  18089. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  18090. offset = attr.offset || 0,
  18091. whens = scope.$eval(whenExp) || {},
  18092. whensExpFns = {},
  18093. startSymbol = $interpolate.startSymbol(),
  18094. endSymbol = $interpolate.endSymbol(),
  18095. isWhen = /^when(Minus)?(.+)$/;
  18096. forEach(attr, function(expression, attributeName) {
  18097. if (isWhen.test(attributeName)) {
  18098. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  18099. element.attr(attr.$attr[attributeName]);
  18100. }
  18101. });
  18102. forEach(whens, function(expression, key) {
  18103. whensExpFns[key] =
  18104. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  18105. offset + endSymbol));
  18106. });
  18107. scope.$watch(function ngPluralizeWatch() {
  18108. var value = parseFloat(scope.$eval(numberExp));
  18109. if (!isNaN(value)) {
  18110. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  18111. //check it against pluralization rules in $locale service
  18112. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  18113. return whensExpFns[value](scope, element, true);
  18114. } else {
  18115. return '';
  18116. }
  18117. }, function ngPluralizeWatchAction(newVal) {
  18118. element.text(newVal);
  18119. });
  18120. }
  18121. };
  18122. }];
  18123. /**
  18124. * @ngdoc directive
  18125. * @name ngRepeat
  18126. *
  18127. * @description
  18128. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  18129. * instance gets its own scope, where the given loop variable is set to the current collection item,
  18130. * and `$index` is set to the item index or key.
  18131. *
  18132. * Special properties are exposed on the local scope of each template instance, including:
  18133. *
  18134. * | Variable | Type | Details |
  18135. * |-----------|-----------------|-----------------------------------------------------------------------------|
  18136. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  18137. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  18138. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  18139. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  18140. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  18141. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  18142. *
  18143. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  18144. * This may be useful when, for instance, nesting ngRepeats.
  18145. *
  18146. * # Special repeat start and end points
  18147. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  18148. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  18149. * 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)
  18150. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  18151. *
  18152. * The example below makes use of this feature:
  18153. * ```html
  18154. * <header ng-repeat-start="item in items">
  18155. * Header {{ item }}
  18156. * </header>
  18157. * <div class="body">
  18158. * Body {{ item }}
  18159. * </div>
  18160. * <footer ng-repeat-end>
  18161. * Footer {{ item }}
  18162. * </footer>
  18163. * ```
  18164. *
  18165. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  18166. * ```html
  18167. * <header>
  18168. * Header A
  18169. * </header>
  18170. * <div class="body">
  18171. * Body A
  18172. * </div>
  18173. * <footer>
  18174. * Footer A
  18175. * </footer>
  18176. * <header>
  18177. * Header B
  18178. * </header>
  18179. * <div class="body">
  18180. * Body B
  18181. * </div>
  18182. * <footer>
  18183. * Footer B
  18184. * </footer>
  18185. * ```
  18186. *
  18187. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  18188. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  18189. *
  18190. * @animations
  18191. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  18192. *
  18193. * **.leave** - when an item is removed from the list or when an item is filtered out
  18194. *
  18195. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  18196. *
  18197. * @element ANY
  18198. * @scope
  18199. * @priority 1000
  18200. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  18201. * formats are currently supported:
  18202. *
  18203. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  18204. * is a scope expression giving the collection to enumerate.
  18205. *
  18206. * For example: `album in artist.albums`.
  18207. *
  18208. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  18209. * and `expression` is the scope expression giving the collection to enumerate.
  18210. *
  18211. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  18212. *
  18213. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  18214. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  18215. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  18216. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  18217. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  18218. * before specifying a tracking expression.
  18219. *
  18220. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  18221. * will be associated by item identity in the array.
  18222. *
  18223. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18224. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18225. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18226. * element in the same way in the DOM.
  18227. *
  18228. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18229. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18230. * property is same.
  18231. *
  18232. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18233. * to items in conjunction with a tracking expression.
  18234. *
  18235. * @example
  18236. * This example initializes the scope to a list of names and
  18237. * then uses `ngRepeat` to display every person:
  18238. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18239. <file name="index.html">
  18240. <div ng-init="friends = [
  18241. {name:'John', age:25, gender:'boy'},
  18242. {name:'Jessie', age:30, gender:'girl'},
  18243. {name:'Johanna', age:28, gender:'girl'},
  18244. {name:'Joy', age:15, gender:'girl'},
  18245. {name:'Mary', age:28, gender:'girl'},
  18246. {name:'Peter', age:95, gender:'boy'},
  18247. {name:'Sebastian', age:50, gender:'boy'},
  18248. {name:'Erika', age:27, gender:'girl'},
  18249. {name:'Patrick', age:40, gender:'boy'},
  18250. {name:'Samantha', age:60, gender:'girl'}
  18251. ]">
  18252. I have {{friends.length}} friends. They are:
  18253. <input type="search" ng-model="q" placeholder="filter friends..." />
  18254. <ul class="example-animate-container">
  18255. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18256. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18257. </li>
  18258. </ul>
  18259. </div>
  18260. </file>
  18261. <file name="animations.css">
  18262. .example-animate-container {
  18263. background:white;
  18264. border:1px solid black;
  18265. list-style:none;
  18266. margin:0;
  18267. padding:0 10px;
  18268. }
  18269. .animate-repeat {
  18270. line-height:40px;
  18271. list-style:none;
  18272. box-sizing:border-box;
  18273. }
  18274. .animate-repeat.ng-move,
  18275. .animate-repeat.ng-enter,
  18276. .animate-repeat.ng-leave {
  18277. -webkit-transition:all linear 0.5s;
  18278. transition:all linear 0.5s;
  18279. }
  18280. .animate-repeat.ng-leave.ng-leave-active,
  18281. .animate-repeat.ng-move,
  18282. .animate-repeat.ng-enter {
  18283. opacity:0;
  18284. max-height:0;
  18285. }
  18286. .animate-repeat.ng-leave,
  18287. .animate-repeat.ng-move.ng-move-active,
  18288. .animate-repeat.ng-enter.ng-enter-active {
  18289. opacity:1;
  18290. max-height:40px;
  18291. }
  18292. </file>
  18293. <file name="protractor.js" type="protractor">
  18294. var friends = element.all(by.repeater('friend in friends'));
  18295. it('should render initial data set', function() {
  18296. expect(friends.count()).toBe(10);
  18297. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18298. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18299. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18300. expect(element(by.binding('friends.length')).getText())
  18301. .toMatch("I have 10 friends. They are:");
  18302. });
  18303. it('should update repeater when filter predicate changes', function() {
  18304. expect(friends.count()).toBe(10);
  18305. element(by.model('q')).sendKeys('ma');
  18306. expect(friends.count()).toBe(2);
  18307. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18308. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18309. });
  18310. </file>
  18311. </example>
  18312. */
  18313. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18314. var NG_REMOVED = '$$NG_REMOVED';
  18315. var ngRepeatMinErr = minErr('ngRepeat');
  18316. return {
  18317. transclude: 'element',
  18318. priority: 1000,
  18319. terminal: true,
  18320. $$tlb: true,
  18321. link: function($scope, $element, $attr, ctrl, $transclude){
  18322. var expression = $attr.ngRepeat;
  18323. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18324. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18325. lhs, rhs, valueIdentifier, keyIdentifier,
  18326. hashFnLocals = {$id: hashKey};
  18327. if (!match) {
  18328. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18329. expression);
  18330. }
  18331. lhs = match[1];
  18332. rhs = match[2];
  18333. trackByExp = match[3];
  18334. if (trackByExp) {
  18335. trackByExpGetter = $parse(trackByExp);
  18336. trackByIdExpFn = function(key, value, index) {
  18337. // assign key, value, and $index to the locals so that they can be used in hash functions
  18338. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18339. hashFnLocals[valueIdentifier] = value;
  18340. hashFnLocals.$index = index;
  18341. return trackByExpGetter($scope, hashFnLocals);
  18342. };
  18343. } else {
  18344. trackByIdArrayFn = function(key, value) {
  18345. return hashKey(value);
  18346. };
  18347. trackByIdObjFn = function(key) {
  18348. return key;
  18349. };
  18350. }
  18351. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18352. if (!match) {
  18353. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18354. lhs);
  18355. }
  18356. valueIdentifier = match[3] || match[1];
  18357. keyIdentifier = match[2];
  18358. // Store a list of elements from previous run. This is a hash where key is the item from the
  18359. // iterator, and the value is objects with following properties.
  18360. // - scope: bound scope
  18361. // - element: previous element.
  18362. // - index: position
  18363. var lastBlockMap = {};
  18364. //watch props
  18365. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18366. var index, length,
  18367. previousNode = $element[0], // current position of the node
  18368. nextNode,
  18369. // Same as lastBlockMap but it has the current state. It will become the
  18370. // lastBlockMap on the next iteration.
  18371. nextBlockMap = {},
  18372. arrayLength,
  18373. childScope,
  18374. key, value, // key/value of iteration
  18375. trackById,
  18376. trackByIdFn,
  18377. collectionKeys,
  18378. block, // last object information {scope, element, id}
  18379. nextBlockOrder = [],
  18380. elementsToRemove;
  18381. if (isArrayLike(collection)) {
  18382. collectionKeys = collection;
  18383. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18384. } else {
  18385. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18386. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18387. collectionKeys = [];
  18388. for (key in collection) {
  18389. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18390. collectionKeys.push(key);
  18391. }
  18392. }
  18393. collectionKeys.sort();
  18394. }
  18395. arrayLength = collectionKeys.length;
  18396. // locate existing items
  18397. length = nextBlockOrder.length = collectionKeys.length;
  18398. for(index = 0; index < length; index++) {
  18399. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18400. value = collection[key];
  18401. trackById = trackByIdFn(key, value, index);
  18402. assertNotHasOwnProperty(trackById, '`track by` id');
  18403. if(lastBlockMap.hasOwnProperty(trackById)) {
  18404. block = lastBlockMap[trackById];
  18405. delete lastBlockMap[trackById];
  18406. nextBlockMap[trackById] = block;
  18407. nextBlockOrder[index] = block;
  18408. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18409. // restore lastBlockMap
  18410. forEach(nextBlockOrder, function(block) {
  18411. if (block && block.scope) lastBlockMap[block.id] = block;
  18412. });
  18413. // This is a duplicate and we need to throw an error
  18414. throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
  18415. expression, trackById);
  18416. } else {
  18417. // new never before seen block
  18418. nextBlockOrder[index] = { id: trackById };
  18419. nextBlockMap[trackById] = false;
  18420. }
  18421. }
  18422. // remove existing items
  18423. for (key in lastBlockMap) {
  18424. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18425. if (lastBlockMap.hasOwnProperty(key)) {
  18426. block = lastBlockMap[key];
  18427. elementsToRemove = getBlockElements(block.clone);
  18428. $animate.leave(elementsToRemove);
  18429. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18430. block.scope.$destroy();
  18431. }
  18432. }
  18433. // we are not using forEach for perf reasons (trying to avoid #call)
  18434. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18435. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18436. value = collection[key];
  18437. block = nextBlockOrder[index];
  18438. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18439. if (block.scope) {
  18440. // if we have already seen this object, then we need to reuse the
  18441. // associated scope/element
  18442. childScope = block.scope;
  18443. nextNode = previousNode;
  18444. do {
  18445. nextNode = nextNode.nextSibling;
  18446. } while(nextNode && nextNode[NG_REMOVED]);
  18447. if (getBlockStart(block) != nextNode) {
  18448. // existing item which got moved
  18449. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18450. }
  18451. previousNode = getBlockEnd(block);
  18452. } else {
  18453. // new item which we don't know about
  18454. childScope = $scope.$new();
  18455. }
  18456. childScope[valueIdentifier] = value;
  18457. if (keyIdentifier) childScope[keyIdentifier] = key;
  18458. childScope.$index = index;
  18459. childScope.$first = (index === 0);
  18460. childScope.$last = (index === (arrayLength - 1));
  18461. childScope.$middle = !(childScope.$first || childScope.$last);
  18462. // jshint bitwise: false
  18463. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18464. // jshint bitwise: true
  18465. if (!block.scope) {
  18466. $transclude(childScope, function(clone) {
  18467. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18468. $animate.enter(clone, null, jqLite(previousNode));
  18469. previousNode = clone;
  18470. block.scope = childScope;
  18471. // Note: We only need the first/last node of the cloned nodes.
  18472. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18473. // by a directive with templateUrl when its template arrives.
  18474. block.clone = clone;
  18475. nextBlockMap[block.id] = block;
  18476. });
  18477. }
  18478. }
  18479. lastBlockMap = nextBlockMap;
  18480. });
  18481. }
  18482. };
  18483. function getBlockStart(block) {
  18484. return block.clone[0];
  18485. }
  18486. function getBlockEnd(block) {
  18487. return block.clone[block.clone.length - 1];
  18488. }
  18489. }];
  18490. /**
  18491. * @ngdoc directive
  18492. * @name ngShow
  18493. *
  18494. * @description
  18495. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18496. * provided to the ngShow attribute. The element is shown or hidden by removing or adding
  18497. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18498. * in AngularJS and sets the display style to none (using an !important flag).
  18499. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18500. *
  18501. * ```html
  18502. * <!-- when $scope.myValue is truthy (element is visible) -->
  18503. * <div ng-show="myValue"></div>
  18504. *
  18505. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18506. * <div ng-show="myValue" class="ng-hide"></div>
  18507. * ```
  18508. *
  18509. * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
  18510. * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
  18511. * from the element causing the element not to appear hidden.
  18512. *
  18513. * <div class="alert alert-warning">
  18514. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18515. * "f" / "0" / "false" / "no" / "n" / "[]"
  18516. * </div>
  18517. *
  18518. * ## Why is !important used?
  18519. *
  18520. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18521. * can be easily overridden by heavier selectors. For example, something as simple
  18522. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18523. * This also becomes a bigger issue when dealing with CSS frameworks.
  18524. *
  18525. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18526. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18527. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18528. *
  18529. * ### Overriding .ng-hide
  18530. *
  18531. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18532. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18533. * class in CSS:
  18534. *
  18535. * ```css
  18536. * .ng-hide {
  18537. * //this is just another form of hiding an element
  18538. * display:block!important;
  18539. * position:absolute;
  18540. * top:-9999px;
  18541. * left:-9999px;
  18542. * }
  18543. * ```
  18544. *
  18545. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18546. *
  18547. * ## A note about animations with ngShow
  18548. *
  18549. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18550. * is true and false. This system works like the animation system present with ngClass except that
  18551. * you must also include the !important flag to override the display property
  18552. * so that you can perform an animation when the element is hidden during the time of the animation.
  18553. *
  18554. * ```css
  18555. * //
  18556. * //a working example can be found at the bottom of this page
  18557. * //
  18558. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18559. * transition:0.5s linear all;
  18560. * }
  18561. *
  18562. * .my-element.ng-hide-add { ... }
  18563. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18564. * .my-element.ng-hide-remove { ... }
  18565. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18566. * ```
  18567. *
  18568. * 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
  18569. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  18570. *
  18571. * @animations
  18572. * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
  18573. * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
  18574. *
  18575. * @element ANY
  18576. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  18577. * then the element is shown or hidden respectively.
  18578. *
  18579. * @example
  18580. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18581. <file name="index.html">
  18582. Click me: <input type="checkbox" ng-model="checked"><br/>
  18583. <div>
  18584. Show:
  18585. <div class="check-element animate-show" ng-show="checked">
  18586. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18587. </div>
  18588. </div>
  18589. <div>
  18590. Hide:
  18591. <div class="check-element animate-show" ng-hide="checked">
  18592. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18593. </div>
  18594. </div>
  18595. </file>
  18596. <file name="glyphicons.css">
  18597. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18598. </file>
  18599. <file name="animations.css">
  18600. .animate-show {
  18601. -webkit-transition:all linear 0.5s;
  18602. transition:all linear 0.5s;
  18603. line-height:20px;
  18604. opacity:1;
  18605. padding:10px;
  18606. border:1px solid black;
  18607. background:white;
  18608. }
  18609. .animate-show.ng-hide {
  18610. line-height:0;
  18611. opacity:0;
  18612. padding:0 10px;
  18613. }
  18614. .check-element {
  18615. padding:10px;
  18616. border:1px solid black;
  18617. background:white;
  18618. }
  18619. </file>
  18620. <file name="protractor.js" type="protractor">
  18621. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18622. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18623. it('should check ng-show / ng-hide', function() {
  18624. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18625. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18626. element(by.model('checked')).click();
  18627. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18628. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18629. });
  18630. </file>
  18631. </example>
  18632. */
  18633. var ngShowDirective = ['$animate', function($animate) {
  18634. return function(scope, element, attr) {
  18635. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  18636. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  18637. });
  18638. };
  18639. }];
  18640. /**
  18641. * @ngdoc directive
  18642. * @name ngHide
  18643. *
  18644. * @description
  18645. * The `ngHide` directive shows or hides the given HTML element based on the expression
  18646. * provided to the ngHide attribute. The element is shown or hidden by removing or adding
  18647. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18648. * in AngularJS and sets the display style to none (using an !important flag).
  18649. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18650. *
  18651. * ```html
  18652. * <!-- when $scope.myValue is truthy (element is hidden) -->
  18653. * <div ng-hide="myValue" class="ng-hide"></div>
  18654. *
  18655. * <!-- when $scope.myValue is falsy (element is visible) -->
  18656. * <div ng-hide="myValue"></div>
  18657. * ```
  18658. *
  18659. * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
  18660. * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
  18661. * from the element causing the element not to appear hidden.
  18662. *
  18663. * <div class="alert alert-warning">
  18664. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  18665. * "f" / "0" / "false" / "no" / "n" / "[]"
  18666. * </div>
  18667. *
  18668. * ## Why is !important used?
  18669. *
  18670. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18671. * can be easily overridden by heavier selectors. For example, something as simple
  18672. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18673. * This also becomes a bigger issue when dealing with CSS frameworks.
  18674. *
  18675. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18676. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18677. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18678. *
  18679. * ### Overriding .ng-hide
  18680. *
  18681. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18682. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18683. * class in CSS:
  18684. *
  18685. * ```css
  18686. * .ng-hide {
  18687. * //this is just another form of hiding an element
  18688. * display:block!important;
  18689. * position:absolute;
  18690. * top:-9999px;
  18691. * left:-9999px;
  18692. * }
  18693. * ```
  18694. *
  18695. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18696. *
  18697. * ## A note about animations with ngHide
  18698. *
  18699. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18700. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  18701. * CSS class is added and removed for you instead of your own CSS class.
  18702. *
  18703. * ```css
  18704. * //
  18705. * //a working example can be found at the bottom of this page
  18706. * //
  18707. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18708. * transition:0.5s linear all;
  18709. * }
  18710. *
  18711. * .my-element.ng-hide-add { ... }
  18712. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18713. * .my-element.ng-hide-remove { ... }
  18714. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18715. * ```
  18716. *
  18717. * 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
  18718. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  18719. *
  18720. * @animations
  18721. * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
  18722. * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
  18723. *
  18724. * @element ANY
  18725. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  18726. * the element is shown or hidden respectively.
  18727. *
  18728. * @example
  18729. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18730. <file name="index.html">
  18731. Click me: <input type="checkbox" ng-model="checked"><br/>
  18732. <div>
  18733. Show:
  18734. <div class="check-element animate-hide" ng-show="checked">
  18735. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18736. </div>
  18737. </div>
  18738. <div>
  18739. Hide:
  18740. <div class="check-element animate-hide" ng-hide="checked">
  18741. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18742. </div>
  18743. </div>
  18744. </file>
  18745. <file name="glyphicons.css">
  18746. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18747. </file>
  18748. <file name="animations.css">
  18749. .animate-hide {
  18750. -webkit-transition:all linear 0.5s;
  18751. transition:all linear 0.5s;
  18752. line-height:20px;
  18753. opacity:1;
  18754. padding:10px;
  18755. border:1px solid black;
  18756. background:white;
  18757. }
  18758. .animate-hide.ng-hide {
  18759. line-height:0;
  18760. opacity:0;
  18761. padding:0 10px;
  18762. }
  18763. .check-element {
  18764. padding:10px;
  18765. border:1px solid black;
  18766. background:white;
  18767. }
  18768. </file>
  18769. <file name="protractor.js" type="protractor">
  18770. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18771. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18772. it('should check ng-show / ng-hide', function() {
  18773. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18774. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18775. element(by.model('checked')).click();
  18776. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18777. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18778. });
  18779. </file>
  18780. </example>
  18781. */
  18782. var ngHideDirective = ['$animate', function($animate) {
  18783. return function(scope, element, attr) {
  18784. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  18785. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  18786. });
  18787. };
  18788. }];
  18789. /**
  18790. * @ngdoc directive
  18791. * @name ngStyle
  18792. * @restrict AC
  18793. *
  18794. * @description
  18795. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  18796. *
  18797. * @element ANY
  18798. * @param {expression} ngStyle
  18799. *
  18800. * {@link guide/expression Expression} which evals to an
  18801. * object whose keys are CSS style names and values are corresponding values for those CSS
  18802. * keys.
  18803. *
  18804. * Since some CSS style names are not valid keys for an object, they must be quoted.
  18805. * See the 'background-color' style in the example below.
  18806. *
  18807. * @example
  18808. <example>
  18809. <file name="index.html">
  18810. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  18811. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  18812. <input type="button" value="clear" ng-click="myStyle={}">
  18813. <br/>
  18814. <span ng-style="myStyle">Sample Text</span>
  18815. <pre>myStyle={{myStyle}}</pre>
  18816. </file>
  18817. <file name="style.css">
  18818. span {
  18819. color: black;
  18820. }
  18821. </file>
  18822. <file name="protractor.js" type="protractor">
  18823. var colorSpan = element(by.css('span'));
  18824. iit('should check ng-style', function() {
  18825. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  18826. element(by.css('input[value=\'set color\']')).click();
  18827. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  18828. element(by.css('input[value=clear]')).click();
  18829. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  18830. });
  18831. </file>
  18832. </example>
  18833. */
  18834. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  18835. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  18836. if (oldStyles && (newStyles !== oldStyles)) {
  18837. forEach(oldStyles, function(val, style) { element.css(style, '');});
  18838. }
  18839. if (newStyles) element.css(newStyles);
  18840. }, true);
  18841. });
  18842. /**
  18843. * @ngdoc directive
  18844. * @name ngSwitch
  18845. * @restrict EA
  18846. *
  18847. * @description
  18848. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  18849. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  18850. * as specified in the template.
  18851. *
  18852. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  18853. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  18854. * matches the value obtained from the evaluated expression. In other words, you define a container element
  18855. * (where you place the directive), place an expression on the **`on="..."` attribute**
  18856. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  18857. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  18858. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  18859. * attribute is displayed.
  18860. *
  18861. * <div class="alert alert-info">
  18862. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  18863. * as literal string values to match against.
  18864. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  18865. * value of the expression `$scope.someVal`.
  18866. * </div>
  18867. * @animations
  18868. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  18869. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  18870. *
  18871. * @usage
  18872. *
  18873. * ```
  18874. * <ANY ng-switch="expression">
  18875. * <ANY ng-switch-when="matchValue1">...</ANY>
  18876. * <ANY ng-switch-when="matchValue2">...</ANY>
  18877. * <ANY ng-switch-default>...</ANY>
  18878. * </ANY>
  18879. * ```
  18880. *
  18881. *
  18882. * @scope
  18883. * @priority 800
  18884. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  18885. * On child elements add:
  18886. *
  18887. * * `ngSwitchWhen`: the case statement to match against. If match then this
  18888. * case will be displayed. If the same match appears multiple times, all the
  18889. * elements will be displayed.
  18890. * * `ngSwitchDefault`: the default case when no other case match. If there
  18891. * are multiple default cases, all of them will be displayed when no other
  18892. * case match.
  18893. *
  18894. *
  18895. * @example
  18896. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18897. <file name="index.html">
  18898. <div ng-controller="Ctrl">
  18899. <select ng-model="selection" ng-options="item for item in items">
  18900. </select>
  18901. <tt>selection={{selection}}</tt>
  18902. <hr/>
  18903. <div class="animate-switch-container"
  18904. ng-switch on="selection">
  18905. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  18906. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  18907. <div class="animate-switch" ng-switch-default>default</div>
  18908. </div>
  18909. </div>
  18910. </file>
  18911. <file name="script.js">
  18912. function Ctrl($scope) {
  18913. $scope.items = ['settings', 'home', 'other'];
  18914. $scope.selection = $scope.items[0];
  18915. }
  18916. </file>
  18917. <file name="animations.css">
  18918. .animate-switch-container {
  18919. position:relative;
  18920. background:white;
  18921. border:1px solid black;
  18922. height:40px;
  18923. overflow:hidden;
  18924. }
  18925. .animate-switch {
  18926. padding:10px;
  18927. }
  18928. .animate-switch.ng-animate {
  18929. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18930. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18931. position:absolute;
  18932. top:0;
  18933. left:0;
  18934. right:0;
  18935. bottom:0;
  18936. }
  18937. .animate-switch.ng-leave.ng-leave-active,
  18938. .animate-switch.ng-enter {
  18939. top:-50px;
  18940. }
  18941. .animate-switch.ng-leave,
  18942. .animate-switch.ng-enter.ng-enter-active {
  18943. top:0;
  18944. }
  18945. </file>
  18946. <file name="protractor.js" type="protractor">
  18947. var switchElem = element(by.css('[ng-switch]'));
  18948. var select = element(by.model('selection'));
  18949. it('should start in settings', function() {
  18950. expect(switchElem.getText()).toMatch(/Settings Div/);
  18951. });
  18952. it('should change to home', function() {
  18953. select.element.all(by.css('option')).get(1).click();
  18954. expect(switchElem.getText()).toMatch(/Home Span/);
  18955. });
  18956. it('should select default', function() {
  18957. select.element.all(by.css('option')).get(2).click();
  18958. expect(switchElem.getText()).toMatch(/default/);
  18959. });
  18960. </file>
  18961. </example>
  18962. */
  18963. var ngSwitchDirective = ['$animate', function($animate) {
  18964. return {
  18965. restrict: 'EA',
  18966. require: 'ngSwitch',
  18967. // asks for $scope to fool the BC controller module
  18968. controller: ['$scope', function ngSwitchController() {
  18969. this.cases = {};
  18970. }],
  18971. link: function(scope, element, attr, ngSwitchController) {
  18972. var watchExpr = attr.ngSwitch || attr.on,
  18973. selectedTranscludes = [],
  18974. selectedElements = [],
  18975. previousElements = [],
  18976. selectedScopes = [];
  18977. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  18978. var i, ii;
  18979. for (i = 0, ii = previousElements.length; i < ii; ++i) {
  18980. previousElements[i].remove();
  18981. }
  18982. previousElements.length = 0;
  18983. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  18984. var selected = selectedElements[i];
  18985. selectedScopes[i].$destroy();
  18986. previousElements[i] = selected;
  18987. $animate.leave(selected, function() {
  18988. previousElements.splice(i, 1);
  18989. });
  18990. }
  18991. selectedElements.length = 0;
  18992. selectedScopes.length = 0;
  18993. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  18994. scope.$eval(attr.change);
  18995. forEach(selectedTranscludes, function(selectedTransclude) {
  18996. var selectedScope = scope.$new();
  18997. selectedScopes.push(selectedScope);
  18998. selectedTransclude.transclude(selectedScope, function(caseElement) {
  18999. var anchor = selectedTransclude.element;
  19000. selectedElements.push(caseElement);
  19001. $animate.enter(caseElement, anchor.parent(), anchor);
  19002. });
  19003. });
  19004. }
  19005. });
  19006. }
  19007. };
  19008. }];
  19009. var ngSwitchWhenDirective = ngDirective({
  19010. transclude: 'element',
  19011. priority: 800,
  19012. require: '^ngSwitch',
  19013. link: function(scope, element, attrs, ctrl, $transclude) {
  19014. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  19015. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  19016. }
  19017. });
  19018. var ngSwitchDefaultDirective = ngDirective({
  19019. transclude: 'element',
  19020. priority: 800,
  19021. require: '^ngSwitch',
  19022. link: function(scope, element, attr, ctrl, $transclude) {
  19023. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  19024. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  19025. }
  19026. });
  19027. /**
  19028. * @ngdoc directive
  19029. * @name ngTransclude
  19030. * @restrict AC
  19031. *
  19032. * @description
  19033. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  19034. *
  19035. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  19036. *
  19037. * @element ANY
  19038. *
  19039. * @example
  19040. <example module="transclude">
  19041. <file name="index.html">
  19042. <script>
  19043. function Ctrl($scope) {
  19044. $scope.title = 'Lorem Ipsum';
  19045. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  19046. }
  19047. angular.module('transclude', [])
  19048. .directive('pane', function(){
  19049. return {
  19050. restrict: 'E',
  19051. transclude: true,
  19052. scope: { title:'@' },
  19053. template: '<div style="border: 1px solid black;">' +
  19054. '<div style="background-color: gray">{{title}}</div>' +
  19055. '<div ng-transclude></div>' +
  19056. '</div>'
  19057. };
  19058. });
  19059. </script>
  19060. <div ng-controller="Ctrl">
  19061. <input ng-model="title"><br>
  19062. <textarea ng-model="text"></textarea> <br/>
  19063. <pane title="{{title}}">{{text}}</pane>
  19064. </div>
  19065. </file>
  19066. <file name="protractor.js" type="protractor">
  19067. it('should have transcluded', function() {
  19068. var titleElement = element(by.model('title'));
  19069. titleElement.clear();
  19070. titleElement.sendKeys('TITLE');
  19071. var textElement = element(by.model('text'));
  19072. textElement.clear();
  19073. textElement.sendKeys('TEXT');
  19074. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  19075. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  19076. });
  19077. </file>
  19078. </example>
  19079. *
  19080. */
  19081. var ngTranscludeDirective = ngDirective({
  19082. link: function($scope, $element, $attrs, controller, $transclude) {
  19083. if (!$transclude) {
  19084. throw minErr('ngTransclude')('orphan',
  19085. 'Illegal use of ngTransclude directive in the template! ' +
  19086. 'No parent directive that requires a transclusion found. ' +
  19087. 'Element: {0}',
  19088. startingTag($element));
  19089. }
  19090. $transclude(function(clone) {
  19091. $element.empty();
  19092. $element.append(clone);
  19093. });
  19094. }
  19095. });
  19096. /**
  19097. * @ngdoc directive
  19098. * @name script
  19099. * @restrict E
  19100. *
  19101. * @description
  19102. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  19103. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  19104. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  19105. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  19106. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  19107. *
  19108. * @param {string} type Must be set to `'text/ng-template'`.
  19109. * @param {string} id Cache name of the template.
  19110. *
  19111. * @example
  19112. <example>
  19113. <file name="index.html">
  19114. <script type="text/ng-template" id="/tpl.html">
  19115. Content of the template.
  19116. </script>
  19117. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  19118. <div id="tpl-content" ng-include src="currentTpl"></div>
  19119. </file>
  19120. <file name="protractor.js" type="protractor">
  19121. it('should load template defined inside script tag', function() {
  19122. element(by.css('#tpl-link')).click();
  19123. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  19124. });
  19125. </file>
  19126. </example>
  19127. */
  19128. var scriptDirective = ['$templateCache', function($templateCache) {
  19129. return {
  19130. restrict: 'E',
  19131. terminal: true,
  19132. compile: function(element, attr) {
  19133. if (attr.type == 'text/ng-template') {
  19134. var templateUrl = attr.id,
  19135. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  19136. text = element[0].text;
  19137. $templateCache.put(templateUrl, text);
  19138. }
  19139. }
  19140. };
  19141. }];
  19142. var ngOptionsMinErr = minErr('ngOptions');
  19143. /**
  19144. * @ngdoc directive
  19145. * @name select
  19146. * @restrict E
  19147. *
  19148. * @description
  19149. * HTML `SELECT` element with angular data-binding.
  19150. *
  19151. * # `ngOptions`
  19152. *
  19153. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  19154. * elements for the `<select>` element using the array or object obtained by evaluating the
  19155. * `ngOptions` comprehension_expression.
  19156. *
  19157. * When an item in the `<select>` menu is selected, the array element or object property
  19158. * represented by the selected option will be bound to the model identified by the `ngModel`
  19159. * directive.
  19160. *
  19161. * <div class="alert alert-warning">
  19162. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  19163. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  19164. * </div>
  19165. *
  19166. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  19167. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  19168. * option. See example below for demonstration.
  19169. *
  19170. * <div class="alert alert-warning">
  19171. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  19172. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  19173. * `select` model to be bound to a non-string value. This is because an option element can only
  19174. * be bound to string values at present.
  19175. * </div>
  19176. *
  19177. * @param {string} ngModel Assignable angular expression to data-bind to.
  19178. * @param {string=} name Property name of the form under which the control is published.
  19179. * @param {string=} required The control is considered valid only if value is entered.
  19180. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19181. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19182. * `required` when you want to data-bind to the `required` attribute.
  19183. * @param {comprehension_expression=} ngOptions in one of the following forms:
  19184. *
  19185. * * for array data sources:
  19186. * * `label` **`for`** `value` **`in`** `array`
  19187. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  19188. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  19189. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  19190. * * for object data sources:
  19191. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19192. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19193. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  19194. * * `select` **`as`** `label` **`group by`** `group`
  19195. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  19196. *
  19197. * Where:
  19198. *
  19199. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  19200. * * `value`: local variable which will refer to each item in the `array` or each property value
  19201. * of `object` during iteration.
  19202. * * `key`: local variable which will refer to a property name in `object` during iteration.
  19203. * * `label`: The result of this expression will be the label for `<option>` element. The
  19204. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  19205. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  19206. * element. If not specified, `select` expression will default to `value`.
  19207. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  19208. * DOM element.
  19209. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  19210. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  19211. * `value` variable (e.g. `value.propertyName`).
  19212. *
  19213. * @example
  19214. <example>
  19215. <file name="index.html">
  19216. <script>
  19217. function MyCntrl($scope) {
  19218. $scope.colors = [
  19219. {name:'black', shade:'dark'},
  19220. {name:'white', shade:'light'},
  19221. {name:'red', shade:'dark'},
  19222. {name:'blue', shade:'dark'},
  19223. {name:'yellow', shade:'light'}
  19224. ];
  19225. $scope.myColor = $scope.colors[2]; // red
  19226. }
  19227. </script>
  19228. <div ng-controller="MyCntrl">
  19229. <ul>
  19230. <li ng-repeat="color in colors">
  19231. Name: <input ng-model="color.name">
  19232. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19233. </li>
  19234. <li>
  19235. [<a href ng-click="colors.push({})">add</a>]
  19236. </li>
  19237. </ul>
  19238. <hr/>
  19239. Color (null not allowed):
  19240. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  19241. Color (null allowed):
  19242. <span class="nullable">
  19243. <select ng-model="myColor" ng-options="color.name for color in colors">
  19244. <option value="">-- choose color --</option>
  19245. </select>
  19246. </span><br/>
  19247. Color grouped by shade:
  19248. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  19249. </select><br/>
  19250. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  19251. <hr/>
  19252. Currently selected: {{ {selected_color:myColor} }}
  19253. <div style="border:solid 1px black; height:20px"
  19254. ng-style="{'background-color':myColor.name}">
  19255. </div>
  19256. </div>
  19257. </file>
  19258. <file name="protractor.js" type="protractor">
  19259. it('should check ng-options', function() {
  19260. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  19261. element.all(by.select('myColor')).first().click();
  19262. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  19263. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  19264. element(by.css('.nullable select[ng-model="myColor"]')).click();
  19265. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  19266. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  19267. });
  19268. </file>
  19269. </example>
  19270. */
  19271. var ngOptionsDirective = valueFn({ terminal: true });
  19272. // jshint maxlen: false
  19273. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19274. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19275. 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]+?))?$/,
  19276. nullModelCtrl = {$setViewValue: noop};
  19277. // jshint maxlen: 100
  19278. return {
  19279. restrict: 'E',
  19280. require: ['select', '?ngModel'],
  19281. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19282. var self = this,
  19283. optionsMap = {},
  19284. ngModelCtrl = nullModelCtrl,
  19285. nullOption,
  19286. unknownOption;
  19287. self.databound = $attrs.ngModel;
  19288. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19289. ngModelCtrl = ngModelCtrl_;
  19290. nullOption = nullOption_;
  19291. unknownOption = unknownOption_;
  19292. };
  19293. self.addOption = function(value) {
  19294. assertNotHasOwnProperty(value, '"option value"');
  19295. optionsMap[value] = true;
  19296. if (ngModelCtrl.$viewValue == value) {
  19297. $element.val(value);
  19298. if (unknownOption.parent()) unknownOption.remove();
  19299. }
  19300. };
  19301. self.removeOption = function(value) {
  19302. if (this.hasOption(value)) {
  19303. delete optionsMap[value];
  19304. if (ngModelCtrl.$viewValue == value) {
  19305. this.renderUnknownOption(value);
  19306. }
  19307. }
  19308. };
  19309. self.renderUnknownOption = function(val) {
  19310. var unknownVal = '? ' + hashKey(val) + ' ?';
  19311. unknownOption.val(unknownVal);
  19312. $element.prepend(unknownOption);
  19313. $element.val(unknownVal);
  19314. unknownOption.prop('selected', true); // needed for IE
  19315. };
  19316. self.hasOption = function(value) {
  19317. return optionsMap.hasOwnProperty(value);
  19318. };
  19319. $scope.$on('$destroy', function() {
  19320. // disable unknown option so that we don't do work when the whole select is being destroyed
  19321. self.renderUnknownOption = noop;
  19322. });
  19323. }],
  19324. link: function(scope, element, attr, ctrls) {
  19325. // if ngModel is not defined, we don't need to do anything
  19326. if (!ctrls[1]) return;
  19327. var selectCtrl = ctrls[0],
  19328. ngModelCtrl = ctrls[1],
  19329. multiple = attr.multiple,
  19330. optionsExp = attr.ngOptions,
  19331. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19332. emptyOption,
  19333. // we can't just jqLite('<option>') since jqLite is not smart enough
  19334. // to create it in <select> and IE barfs otherwise.
  19335. optionTemplate = jqLite(document.createElement('option')),
  19336. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19337. unknownOption = optionTemplate.clone();
  19338. // find "null" option
  19339. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19340. if (children[i].value === '') {
  19341. emptyOption = nullOption = children.eq(i);
  19342. break;
  19343. }
  19344. }
  19345. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19346. // required validator
  19347. if (multiple) {
  19348. ngModelCtrl.$isEmpty = function(value) {
  19349. return !value || value.length === 0;
  19350. };
  19351. }
  19352. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19353. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19354. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19355. ////////////////////////////
  19356. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19357. ngModelCtrl.$render = function() {
  19358. var viewValue = ngModelCtrl.$viewValue;
  19359. if (selectCtrl.hasOption(viewValue)) {
  19360. if (unknownOption.parent()) unknownOption.remove();
  19361. selectElement.val(viewValue);
  19362. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19363. } else {
  19364. if (isUndefined(viewValue) && emptyOption) {
  19365. selectElement.val('');
  19366. } else {
  19367. selectCtrl.renderUnknownOption(viewValue);
  19368. }
  19369. }
  19370. };
  19371. selectElement.on('change', function() {
  19372. scope.$apply(function() {
  19373. if (unknownOption.parent()) unknownOption.remove();
  19374. ngModelCtrl.$setViewValue(selectElement.val());
  19375. });
  19376. });
  19377. }
  19378. function setupAsMultiple(scope, selectElement, ctrl) {
  19379. var lastView;
  19380. ctrl.$render = function() {
  19381. var items = new HashMap(ctrl.$viewValue);
  19382. forEach(selectElement.find('option'), function(option) {
  19383. option.selected = isDefined(items.get(option.value));
  19384. });
  19385. };
  19386. // we have to do it on each watch since ngModel watches reference, but
  19387. // we need to work of an array, so we need to see if anything was inserted/removed
  19388. scope.$watch(function selectMultipleWatch() {
  19389. if (!equals(lastView, ctrl.$viewValue)) {
  19390. lastView = shallowCopy(ctrl.$viewValue);
  19391. ctrl.$render();
  19392. }
  19393. });
  19394. selectElement.on('change', function() {
  19395. scope.$apply(function() {
  19396. var array = [];
  19397. forEach(selectElement.find('option'), function(option) {
  19398. if (option.selected) {
  19399. array.push(option.value);
  19400. }
  19401. });
  19402. ctrl.$setViewValue(array);
  19403. });
  19404. });
  19405. }
  19406. function setupAsOptions(scope, selectElement, ctrl) {
  19407. var match;
  19408. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19409. throw ngOptionsMinErr('iexp',
  19410. "Expected expression in form of " +
  19411. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19412. " but got '{0}'. Element: {1}",
  19413. optionsExp, startingTag(selectElement));
  19414. }
  19415. var displayFn = $parse(match[2] || match[1]),
  19416. valueName = match[4] || match[6],
  19417. keyName = match[5],
  19418. groupByFn = $parse(match[3] || ''),
  19419. valueFn = $parse(match[2] ? match[1] : valueName),
  19420. valuesFn = $parse(match[7]),
  19421. track = match[8],
  19422. trackFn = track ? $parse(match[8]) : null,
  19423. // This is an array of array of existing option groups in DOM.
  19424. // We try to reuse these if possible
  19425. // - optionGroupsCache[0] is the options with no option group
  19426. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19427. optionGroupsCache = [[{element: selectElement, label:''}]];
  19428. if (nullOption) {
  19429. // compile the element since there might be bindings in it
  19430. $compile(nullOption)(scope);
  19431. // remove the class, which is added automatically because we recompile the element and it
  19432. // becomes the compilation root
  19433. nullOption.removeClass('ng-scope');
  19434. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19435. // remove the label from the element. wtf?
  19436. nullOption.remove();
  19437. }
  19438. // clear contents, we'll add what's needed based on the model
  19439. selectElement.empty();
  19440. selectElement.on('change', function() {
  19441. scope.$apply(function() {
  19442. var optionGroup,
  19443. collection = valuesFn(scope) || [],
  19444. locals = {},
  19445. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19446. if (multiple) {
  19447. value = [];
  19448. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19449. groupIndex < groupLength;
  19450. groupIndex++) {
  19451. // list of options for that group. (first item has the parent)
  19452. optionGroup = optionGroupsCache[groupIndex];
  19453. for(index = 1, length = optionGroup.length; index < length; index++) {
  19454. if ((optionElement = optionGroup[index].element)[0].selected) {
  19455. key = optionElement.val();
  19456. if (keyName) locals[keyName] = key;
  19457. if (trackFn) {
  19458. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19459. locals[valueName] = collection[trackIndex];
  19460. if (trackFn(scope, locals) == key) break;
  19461. }
  19462. } else {
  19463. locals[valueName] = collection[key];
  19464. }
  19465. value.push(valueFn(scope, locals));
  19466. }
  19467. }
  19468. }
  19469. } else {
  19470. key = selectElement.val();
  19471. if (key == '?') {
  19472. value = undefined;
  19473. } else if (key === ''){
  19474. value = null;
  19475. } else {
  19476. if (trackFn) {
  19477. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19478. locals[valueName] = collection[trackIndex];
  19479. if (trackFn(scope, locals) == key) {
  19480. value = valueFn(scope, locals);
  19481. break;
  19482. }
  19483. }
  19484. } else {
  19485. locals[valueName] = collection[key];
  19486. if (keyName) locals[keyName] = key;
  19487. value = valueFn(scope, locals);
  19488. }
  19489. }
  19490. // Update the null option's selected property here so $render cleans it up correctly
  19491. if (optionGroupsCache[0].length > 1) {
  19492. if (optionGroupsCache[0][1].id !== key) {
  19493. optionGroupsCache[0][1].selected = false;
  19494. }
  19495. }
  19496. }
  19497. ctrl.$setViewValue(value);
  19498. });
  19499. });
  19500. ctrl.$render = render;
  19501. // TODO(vojta): can't we optimize this ?
  19502. scope.$watch(render);
  19503. function render() {
  19504. // Temporary location for the option groups before we render them
  19505. var optionGroups = {'':[]},
  19506. optionGroupNames = [''],
  19507. optionGroupName,
  19508. optionGroup,
  19509. option,
  19510. existingParent, existingOptions, existingOption,
  19511. modelValue = ctrl.$modelValue,
  19512. values = valuesFn(scope) || [],
  19513. keys = keyName ? sortedKeys(values) : values,
  19514. key,
  19515. groupLength, length,
  19516. groupIndex, index,
  19517. locals = {},
  19518. selected,
  19519. selectedSet = false, // nothing is selected yet
  19520. lastElement,
  19521. element,
  19522. label;
  19523. if (multiple) {
  19524. if (trackFn && isArray(modelValue)) {
  19525. selectedSet = new HashMap([]);
  19526. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19527. locals[valueName] = modelValue[trackIndex];
  19528. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19529. }
  19530. } else {
  19531. selectedSet = new HashMap(modelValue);
  19532. }
  19533. }
  19534. // We now build up the list of options we need (we merge later)
  19535. for (index = 0; length = keys.length, index < length; index++) {
  19536. key = index;
  19537. if (keyName) {
  19538. key = keys[index];
  19539. if ( key.charAt(0) === '$' ) continue;
  19540. locals[keyName] = key;
  19541. }
  19542. locals[valueName] = values[key];
  19543. optionGroupName = groupByFn(scope, locals) || '';
  19544. if (!(optionGroup = optionGroups[optionGroupName])) {
  19545. optionGroup = optionGroups[optionGroupName] = [];
  19546. optionGroupNames.push(optionGroupName);
  19547. }
  19548. if (multiple) {
  19549. selected = isDefined(
  19550. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  19551. );
  19552. } else {
  19553. if (trackFn) {
  19554. var modelCast = {};
  19555. modelCast[valueName] = modelValue;
  19556. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  19557. } else {
  19558. selected = modelValue === valueFn(scope, locals);
  19559. }
  19560. selectedSet = selectedSet || selected; // see if at least one item is selected
  19561. }
  19562. label = displayFn(scope, locals); // what will be seen by the user
  19563. // doing displayFn(scope, locals) || '' overwrites zero values
  19564. label = isDefined(label) ? label : '';
  19565. optionGroup.push({
  19566. // either the index into array or key from object
  19567. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  19568. label: label,
  19569. selected: selected // determine if we should be selected
  19570. });
  19571. }
  19572. if (!multiple) {
  19573. if (nullOption || modelValue === null) {
  19574. // insert null option if we have a placeholder, or the model is null
  19575. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  19576. } else if (!selectedSet) {
  19577. // option could not be found, we have to insert the undefined item
  19578. optionGroups[''].unshift({id:'?', label:'', selected:true});
  19579. }
  19580. }
  19581. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  19582. for (groupIndex = 0, groupLength = optionGroupNames.length;
  19583. groupIndex < groupLength;
  19584. groupIndex++) {
  19585. // current option group name or '' if no group
  19586. optionGroupName = optionGroupNames[groupIndex];
  19587. // list of options for that group. (first item has the parent)
  19588. optionGroup = optionGroups[optionGroupName];
  19589. if (optionGroupsCache.length <= groupIndex) {
  19590. // we need to grow the optionGroups
  19591. existingParent = {
  19592. element: optGroupTemplate.clone().attr('label', optionGroupName),
  19593. label: optionGroup.label
  19594. };
  19595. existingOptions = [existingParent];
  19596. optionGroupsCache.push(existingOptions);
  19597. selectElement.append(existingParent.element);
  19598. } else {
  19599. existingOptions = optionGroupsCache[groupIndex];
  19600. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  19601. // update the OPTGROUP label if not the same.
  19602. if (existingParent.label != optionGroupName) {
  19603. existingParent.element.attr('label', existingParent.label = optionGroupName);
  19604. }
  19605. }
  19606. lastElement = null; // start at the beginning
  19607. for(index = 0, length = optionGroup.length; index < length; index++) {
  19608. option = optionGroup[index];
  19609. if ((existingOption = existingOptions[index+1])) {
  19610. // reuse elements
  19611. lastElement = existingOption.element;
  19612. if (existingOption.label !== option.label) {
  19613. lastElement.text(existingOption.label = option.label);
  19614. }
  19615. if (existingOption.id !== option.id) {
  19616. lastElement.val(existingOption.id = option.id);
  19617. }
  19618. // lastElement.prop('selected') provided by jQuery has side-effects
  19619. if (existingOption.selected !== option.selected) {
  19620. lastElement.prop('selected', (existingOption.selected = option.selected));
  19621. }
  19622. } else {
  19623. // grow elements
  19624. // if it's a null option
  19625. if (option.id === '' && nullOption) {
  19626. // put back the pre-compiled element
  19627. element = nullOption;
  19628. } else {
  19629. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  19630. // in this version of jQuery on some browser the .text() returns a string
  19631. // rather then the element.
  19632. (element = optionTemplate.clone())
  19633. .val(option.id)
  19634. .attr('selected', option.selected)
  19635. .text(option.label);
  19636. }
  19637. existingOptions.push(existingOption = {
  19638. element: element,
  19639. label: option.label,
  19640. id: option.id,
  19641. selected: option.selected
  19642. });
  19643. if (lastElement) {
  19644. lastElement.after(element);
  19645. } else {
  19646. existingParent.element.append(element);
  19647. }
  19648. lastElement = element;
  19649. }
  19650. }
  19651. // remove any excessive OPTIONs in a group
  19652. index++; // increment since the existingOptions[0] is parent element not OPTION
  19653. while(existingOptions.length > index) {
  19654. existingOptions.pop().element.remove();
  19655. }
  19656. }
  19657. // remove any excessive OPTGROUPs from select
  19658. while(optionGroupsCache.length > groupIndex) {
  19659. optionGroupsCache.pop()[0].element.remove();
  19660. }
  19661. }
  19662. }
  19663. }
  19664. };
  19665. }];
  19666. var optionDirective = ['$interpolate', function($interpolate) {
  19667. var nullSelectCtrl = {
  19668. addOption: noop,
  19669. removeOption: noop
  19670. };
  19671. return {
  19672. restrict: 'E',
  19673. priority: 100,
  19674. compile: function(element, attr) {
  19675. if (isUndefined(attr.value)) {
  19676. var interpolateFn = $interpolate(element.text(), true);
  19677. if (!interpolateFn) {
  19678. attr.$set('value', element.text());
  19679. }
  19680. }
  19681. return function (scope, element, attr) {
  19682. var selectCtrlName = '$selectController',
  19683. parent = element.parent(),
  19684. selectCtrl = parent.data(selectCtrlName) ||
  19685. parent.parent().data(selectCtrlName); // in case we are in optgroup
  19686. if (selectCtrl && selectCtrl.databound) {
  19687. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  19688. // We don't want the view to drive the initialization of the model anyway.
  19689. element.prop('selected', false);
  19690. } else {
  19691. selectCtrl = nullSelectCtrl;
  19692. }
  19693. if (interpolateFn) {
  19694. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  19695. attr.$set('value', newVal);
  19696. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  19697. selectCtrl.addOption(newVal);
  19698. });
  19699. } else {
  19700. selectCtrl.addOption(attr.value);
  19701. }
  19702. element.on('$destroy', function() {
  19703. selectCtrl.removeOption(attr.value);
  19704. });
  19705. };
  19706. }
  19707. };
  19708. }];
  19709. var styleDirective = valueFn({
  19710. restrict: 'E',
  19711. terminal: true
  19712. });
  19713. if (window.angular.bootstrap) {
  19714. //AngularJS is already loaded, so we can return here...
  19715. console.log('WARNING: Tried to load angular more than once.');
  19716. return;
  19717. }
  19718. //try to bind to jquery now so that one can write angular.element().read()
  19719. //but we will rebind on bootstrap again.
  19720. bindJQuery();
  19721. publishExternalAPI(angular);
  19722. jqLite(document).ready(function() {
  19723. angularInit(document, bootstrap);
  19724. });
  19725. })(window, document);
  19726. !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>');