angular.js 771 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154
  1. /**
  2. * @license AngularJS v1.2.28
  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.28/' +
  67. (module ? module + '/' : '') + code;
  68. for (i = 2; i < arguments.length; i++) {
  69. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  70. encodeURIComponent(stringify(arguments[i]));
  71. }
  72. return new Error(message);
  73. };
  74. }
  75. /* We need to tell jshint what variables are being exported */
  76. /* global angular: true,
  77. msie: true,
  78. jqLite: true,
  79. jQuery: true,
  80. slice: true,
  81. push: true,
  82. toString: true,
  83. ngMinErr: true,
  84. angularModule: true,
  85. nodeName_: true,
  86. uid: true,
  87. VALIDITY_STATE_PROPERTY: true,
  88. lowercase: true,
  89. uppercase: true,
  90. manualLowercase: true,
  91. manualUppercase: true,
  92. nodeName_: true,
  93. isArrayLike: true,
  94. forEach: true,
  95. sortedKeys: true,
  96. forEachSorted: true,
  97. reverseParams: true,
  98. nextUid: true,
  99. setHashKey: true,
  100. extend: true,
  101. int: true,
  102. inherit: true,
  103. noop: true,
  104. identity: true,
  105. valueFn: true,
  106. isUndefined: true,
  107. isDefined: true,
  108. isObject: true,
  109. isString: true,
  110. isNumber: true,
  111. isDate: true,
  112. isArray: true,
  113. isFunction: true,
  114. isRegExp: true,
  115. isWindow: true,
  116. isScope: true,
  117. isFile: true,
  118. isBlob: true,
  119. isBoolean: true,
  120. isPromiseLike: true,
  121. trim: true,
  122. isElement: true,
  123. makeMap: true,
  124. map: true,
  125. size: true,
  126. includes: true,
  127. indexOf: true,
  128. arrayRemove: true,
  129. isLeafNode: true,
  130. copy: true,
  131. shallowCopy: true,
  132. equals: true,
  133. csp: true,
  134. concat: true,
  135. sliceArgs: true,
  136. bind: true,
  137. toJsonReplacer: true,
  138. toJson: true,
  139. fromJson: true,
  140. toBoolean: true,
  141. startingTag: true,
  142. tryDecodeURIComponent: true,
  143. parseKeyValue: true,
  144. toKeyValue: true,
  145. encodeUriSegment: true,
  146. encodeUriQuery: true,
  147. angularInit: true,
  148. bootstrap: true,
  149. snake_case: true,
  150. bindJQuery: true,
  151. assertArg: true,
  152. assertArgFn: true,
  153. assertNotHasOwnProperty: true,
  154. getter: true,
  155. getBlockElements: true,
  156. hasOwnProperty: true,
  157. */
  158. ////////////////////////////////////
  159. /**
  160. * @ngdoc module
  161. * @name ng
  162. * @module ng
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. // The name of a form control's ValidityState property.
  174. // This is used so that it's possible for internal tests to create mock ValidityStates.
  175. var VALIDITY_STATE_PROPERTY = 'validity';
  176. /**
  177. * @ngdoc function
  178. * @name angular.lowercase
  179. * @module ng
  180. * @kind function
  181. *
  182. * @description Converts the specified string to lowercase.
  183. * @param {string} string String to be converted to lowercase.
  184. * @returns {string} Lowercased string.
  185. */
  186. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  187. var hasOwnProperty = Object.prototype.hasOwnProperty;
  188. /**
  189. * @ngdoc function
  190. * @name angular.uppercase
  191. * @module ng
  192. * @kind function
  193. *
  194. * @description Converts the specified string to uppercase.
  195. * @param {string} string String to be converted to uppercase.
  196. * @returns {string} Uppercased string.
  197. */
  198. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  199. var manualLowercase = function(s) {
  200. /* jshint bitwise: false */
  201. return isString(s)
  202. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  203. : s;
  204. };
  205. var manualUppercase = function(s) {
  206. /* jshint bitwise: false */
  207. return isString(s)
  208. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  209. : s;
  210. };
  211. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  212. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  213. // with correct but slower alternatives.
  214. if ('i' !== 'I'.toLowerCase()) {
  215. lowercase = manualLowercase;
  216. uppercase = manualUppercase;
  217. }
  218. var
  219. msie, // holds major version number for IE, or NaN if UA is not IE.
  220. jqLite, // delay binding since jQuery could be loaded after us.
  221. jQuery, // delay binding
  222. slice = [].slice,
  223. push = [].push,
  224. toString = Object.prototype.toString,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. nodeName_,
  230. uid = ['0', '0', '0'];
  231. /**
  232. * IE 11 changed the format of the UserAgent string.
  233. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  234. */
  235. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  236. if (isNaN(msie)) {
  237. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  238. }
  239. /**
  240. * @private
  241. * @param {*} obj
  242. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  243. * String ...)
  244. */
  245. function isArrayLike(obj) {
  246. if (obj == null || isWindow(obj)) {
  247. return false;
  248. }
  249. var length = obj.length;
  250. if (obj.nodeType === 1 && length) {
  251. return true;
  252. }
  253. return isString(obj) || isArray(obj) || length === 0 ||
  254. typeof length === 'number' && length > 0 && (length - 1) in obj;
  255. }
  256. /**
  257. * @ngdoc function
  258. * @name angular.forEach
  259. * @module ng
  260. * @kind function
  261. *
  262. * @description
  263. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  264. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  265. * is the value of an object property or an array element and `key` is the object property key or
  266. * array element index. Specifying a `context` for the function is optional.
  267. *
  268. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  269. * using the `hasOwnProperty` method.
  270. *
  271. ```js
  272. var values = {name: 'misko', gender: 'male'};
  273. var log = [];
  274. angular.forEach(values, function(value, key) {
  275. this.push(key + ': ' + value);
  276. }, log);
  277. expect(log).toEqual(['name: misko', 'gender: male']);
  278. ```
  279. *
  280. * @param {Object|Array} obj Object to iterate over.
  281. * @param {Function} iterator Iterator function.
  282. * @param {Object=} context Object to become context (`this`) for the iterator function.
  283. * @returns {Object|Array} Reference to `obj`.
  284. */
  285. function forEach(obj, iterator, context) {
  286. var key;
  287. if (obj) {
  288. if (isFunction(obj)) {
  289. for (key in obj) {
  290. // Need to check if hasOwnProperty exists,
  291. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  292. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  293. iterator.call(context, obj[key], key);
  294. }
  295. }
  296. } else if (isArray(obj) || isArrayLike(obj)) {
  297. for (key = 0; key < obj.length; key++) {
  298. iterator.call(context, obj[key], key);
  299. }
  300. } else if (obj.forEach && obj.forEach !== forEach) {
  301. obj.forEach(iterator, context);
  302. } else {
  303. for (key in obj) {
  304. if (obj.hasOwnProperty(key)) {
  305. iterator.call(context, obj[key], key);
  306. }
  307. }
  308. }
  309. }
  310. return obj;
  311. }
  312. function sortedKeys(obj) {
  313. var keys = [];
  314. for (var key in obj) {
  315. if (obj.hasOwnProperty(key)) {
  316. keys.push(key);
  317. }
  318. }
  319. return keys.sort();
  320. }
  321. function forEachSorted(obj, iterator, context) {
  322. var keys = sortedKeys(obj);
  323. for ( var i = 0; i < keys.length; i++) {
  324. iterator.call(context, obj[keys[i]], keys[i]);
  325. }
  326. return keys;
  327. }
  328. /**
  329. * when using forEach the params are value, key, but it is often useful to have key, value.
  330. * @param {function(string, *)} iteratorFn
  331. * @returns {function(*, string)}
  332. */
  333. function reverseParams(iteratorFn) {
  334. return function(value, key) { iteratorFn(key, value); };
  335. }
  336. /**
  337. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  338. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  339. * the number string gets longer over time, and it can also overflow, where as the nextId
  340. * will grow much slower, it is a string, and it will never overflow.
  341. *
  342. * @returns {string} an unique alpha-numeric string
  343. */
  344. function nextUid() {
  345. var index = uid.length;
  346. var digit;
  347. while(index) {
  348. index--;
  349. digit = uid[index].charCodeAt(0);
  350. if (digit == 57 /*'9'*/) {
  351. uid[index] = 'A';
  352. return uid.join('');
  353. }
  354. if (digit == 90 /*'Z'*/) {
  355. uid[index] = '0';
  356. } else {
  357. uid[index] = String.fromCharCode(digit + 1);
  358. return uid.join('');
  359. }
  360. }
  361. uid.unshift('0');
  362. return uid.join('');
  363. }
  364. /**
  365. * Set or clear the hashkey for an object.
  366. * @param obj object
  367. * @param h the hashkey (!truthy to delete the hashkey)
  368. */
  369. function setHashKey(obj, h) {
  370. if (h) {
  371. obj.$$hashKey = h;
  372. }
  373. else {
  374. delete obj.$$hashKey;
  375. }
  376. }
  377. /**
  378. * @ngdoc function
  379. * @name angular.extend
  380. * @module ng
  381. * @kind function
  382. *
  383. * @description
  384. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  385. * to `dst`. You can specify multiple `src` objects.
  386. *
  387. * @param {Object} dst Destination object.
  388. * @param {...Object} src Source object(s).
  389. * @returns {Object} Reference to `dst`.
  390. */
  391. function extend(dst) {
  392. var h = dst.$$hashKey;
  393. forEach(arguments, function(obj) {
  394. if (obj !== dst) {
  395. forEach(obj, function(value, key) {
  396. dst[key] = value;
  397. });
  398. }
  399. });
  400. setHashKey(dst,h);
  401. return dst;
  402. }
  403. function int(str) {
  404. return parseInt(str, 10);
  405. }
  406. function inherit(parent, extra) {
  407. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  408. }
  409. /**
  410. * @ngdoc function
  411. * @name angular.noop
  412. * @module ng
  413. * @kind function
  414. *
  415. * @description
  416. * A function that performs no operations. This function can be useful when writing code in the
  417. * functional style.
  418. ```js
  419. function foo(callback) {
  420. var result = calculateResult();
  421. (callback || angular.noop)(result);
  422. }
  423. ```
  424. */
  425. function noop() {}
  426. noop.$inject = [];
  427. /**
  428. * @ngdoc function
  429. * @name angular.identity
  430. * @module ng
  431. * @kind function
  432. *
  433. * @description
  434. * A function that returns its first argument. This function is useful when writing code in the
  435. * functional style.
  436. *
  437. ```js
  438. function transformer(transformationFn, value) {
  439. return (transformationFn || angular.identity)(value);
  440. };
  441. ```
  442. */
  443. function identity($) {return $;}
  444. identity.$inject = [];
  445. function valueFn(value) {return function() {return value;};}
  446. /**
  447. * @ngdoc function
  448. * @name angular.isUndefined
  449. * @module ng
  450. * @kind function
  451. *
  452. * @description
  453. * Determines if a reference is undefined.
  454. *
  455. * @param {*} value Reference to check.
  456. * @returns {boolean} True if `value` is undefined.
  457. */
  458. function isUndefined(value){return typeof value === 'undefined';}
  459. /**
  460. * @ngdoc function
  461. * @name angular.isDefined
  462. * @module ng
  463. * @kind function
  464. *
  465. * @description
  466. * Determines if a reference is defined.
  467. *
  468. * @param {*} value Reference to check.
  469. * @returns {boolean} True if `value` is defined.
  470. */
  471. function isDefined(value){return typeof value !== 'undefined';}
  472. /**
  473. * @ngdoc function
  474. * @name angular.isObject
  475. * @module ng
  476. * @kind function
  477. *
  478. * @description
  479. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  480. * considered to be objects. Note that JavaScript arrays are objects.
  481. *
  482. * @param {*} value Reference to check.
  483. * @returns {boolean} True if `value` is an `Object` but not `null`.
  484. */
  485. function isObject(value){return value != null && typeof value === 'object';}
  486. /**
  487. * @ngdoc function
  488. * @name angular.isString
  489. * @module ng
  490. * @kind function
  491. *
  492. * @description
  493. * Determines if a reference is a `String`.
  494. *
  495. * @param {*} value Reference to check.
  496. * @returns {boolean} True if `value` is a `String`.
  497. */
  498. function isString(value){return typeof value === 'string';}
  499. /**
  500. * @ngdoc function
  501. * @name angular.isNumber
  502. * @module ng
  503. * @kind function
  504. *
  505. * @description
  506. * Determines if a reference is a `Number`.
  507. *
  508. * @param {*} value Reference to check.
  509. * @returns {boolean} True if `value` is a `Number`.
  510. */
  511. function isNumber(value){return typeof value === 'number';}
  512. /**
  513. * @ngdoc function
  514. * @name angular.isDate
  515. * @module ng
  516. * @kind function
  517. *
  518. * @description
  519. * Determines if a value is a date.
  520. *
  521. * @param {*} value Reference to check.
  522. * @returns {boolean} True if `value` is a `Date`.
  523. */
  524. function isDate(value) {
  525. return toString.call(value) === '[object Date]';
  526. }
  527. /**
  528. * @ngdoc function
  529. * @name angular.isArray
  530. * @module ng
  531. * @kind function
  532. *
  533. * @description
  534. * Determines if a reference is an `Array`.
  535. *
  536. * @param {*} value Reference to check.
  537. * @returns {boolean} True if `value` is an `Array`.
  538. */
  539. var isArray = (function() {
  540. if (!isFunction(Array.isArray)) {
  541. return function(value) {
  542. return toString.call(value) === '[object Array]';
  543. };
  544. }
  545. return Array.isArray;
  546. })();
  547. /**
  548. * @ngdoc function
  549. * @name angular.isFunction
  550. * @module ng
  551. * @kind function
  552. *
  553. * @description
  554. * Determines if a reference is a `Function`.
  555. *
  556. * @param {*} value Reference to check.
  557. * @returns {boolean} True if `value` is a `Function`.
  558. */
  559. function isFunction(value){return typeof value === 'function';}
  560. /**
  561. * Determines if a value is a regular expression object.
  562. *
  563. * @private
  564. * @param {*} value Reference to check.
  565. * @returns {boolean} True if `value` is a `RegExp`.
  566. */
  567. function isRegExp(value) {
  568. return toString.call(value) === '[object RegExp]';
  569. }
  570. /**
  571. * Checks if `obj` is a window object.
  572. *
  573. * @private
  574. * @param {*} obj Object to check
  575. * @returns {boolean} True if `obj` is a window obj.
  576. */
  577. function isWindow(obj) {
  578. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  579. }
  580. function isScope(obj) {
  581. return obj && obj.$evalAsync && obj.$watch;
  582. }
  583. function isFile(obj) {
  584. return toString.call(obj) === '[object File]';
  585. }
  586. function isBlob(obj) {
  587. return toString.call(obj) === '[object Blob]';
  588. }
  589. function isBoolean(value) {
  590. return typeof value === 'boolean';
  591. }
  592. function isPromiseLike(obj) {
  593. return obj && isFunction(obj.then);
  594. }
  595. var trim = (function() {
  596. // native trim is way faster: http://jsperf.com/angular-trim-test
  597. // but IE doesn't have it... :-(
  598. // TODO: we should move this into IE/ES5 polyfill
  599. if (!String.prototype.trim) {
  600. return function(value) {
  601. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  602. };
  603. }
  604. return function(value) {
  605. return isString(value) ? value.trim() : value;
  606. };
  607. })();
  608. /**
  609. * @ngdoc function
  610. * @name angular.isElement
  611. * @module ng
  612. * @kind function
  613. *
  614. * @description
  615. * Determines if a reference is a DOM element (or wrapped jQuery element).
  616. *
  617. * @param {*} value Reference to check.
  618. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  619. */
  620. function isElement(node) {
  621. return !!(node &&
  622. (node.nodeName // we are a direct element
  623. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  624. }
  625. /**
  626. * @param str 'key1,key2,...'
  627. * @returns {object} in the form of {key1:true, key2:true, ...}
  628. */
  629. function makeMap(str) {
  630. var obj = {}, items = str.split(","), i;
  631. for ( i = 0; i < items.length; i++ )
  632. obj[ items[i] ] = true;
  633. return obj;
  634. }
  635. if (msie < 9) {
  636. nodeName_ = function(element) {
  637. element = element.nodeName ? element : element[0];
  638. return (element.scopeName && element.scopeName != 'HTML')
  639. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  640. };
  641. } else {
  642. nodeName_ = function(element) {
  643. return element.nodeName ? element.nodeName : element[0].nodeName;
  644. };
  645. }
  646. function map(obj, iterator, context) {
  647. var results = [];
  648. forEach(obj, function(value, index, list) {
  649. results.push(iterator.call(context, value, index, list));
  650. });
  651. return results;
  652. }
  653. /**
  654. * @description
  655. * Determines the number of elements in an array, the number of properties an object has, or
  656. * the length of a string.
  657. *
  658. * Note: This function is used to augment the Object type in Angular expressions. See
  659. * {@link angular.Object} for more information about Angular arrays.
  660. *
  661. * @param {Object|Array|string} obj Object, array, or string to inspect.
  662. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  663. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  664. */
  665. function size(obj, ownPropsOnly) {
  666. var count = 0, key;
  667. if (isArray(obj) || isString(obj)) {
  668. return obj.length;
  669. } else if (isObject(obj)) {
  670. for (key in obj)
  671. if (!ownPropsOnly || obj.hasOwnProperty(key))
  672. count++;
  673. }
  674. return count;
  675. }
  676. function includes(array, obj) {
  677. return indexOf(array, obj) != -1;
  678. }
  679. function indexOf(array, obj) {
  680. if (array.indexOf) return array.indexOf(obj);
  681. for (var i = 0; i < array.length; i++) {
  682. if (obj === array[i]) return i;
  683. }
  684. return -1;
  685. }
  686. function arrayRemove(array, value) {
  687. var index = indexOf(array, value);
  688. if (index >=0)
  689. array.splice(index, 1);
  690. return value;
  691. }
  692. function isLeafNode (node) {
  693. if (node) {
  694. switch (node.nodeName) {
  695. case "OPTION":
  696. case "PRE":
  697. case "TITLE":
  698. return true;
  699. }
  700. }
  701. return false;
  702. }
  703. /**
  704. * @ngdoc function
  705. * @name angular.copy
  706. * @module ng
  707. * @kind function
  708. *
  709. * @description
  710. * Creates a deep copy of `source`, which should be an object or an array.
  711. *
  712. * * If no destination is supplied, a copy of the object or array is created.
  713. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  714. * are deleted and then all elements/properties from the source are copied to it.
  715. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  716. * * If `source` is identical to 'destination' an exception will be thrown.
  717. *
  718. * @param {*} source The source that will be used to make a copy.
  719. * Can be any type, including primitives, `null`, and `undefined`.
  720. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  721. * provided, must be of the same type as `source`.
  722. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  723. *
  724. * @example
  725. <example module="copyExample">
  726. <file name="index.html">
  727. <div ng-controller="ExampleController">
  728. <form novalidate class="simple-form">
  729. Name: <input type="text" ng-model="user.name" /><br />
  730. E-mail: <input type="email" ng-model="user.email" /><br />
  731. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  732. <input type="radio" ng-model="user.gender" value="female" />female<br />
  733. <button ng-click="reset()">RESET</button>
  734. <button ng-click="update(user)">SAVE</button>
  735. </form>
  736. <pre>form = {{user | json}}</pre>
  737. <pre>master = {{master | json}}</pre>
  738. </div>
  739. <script>
  740. angular.module('copyExample', [])
  741. .controller('ExampleController', ['$scope', function($scope) {
  742. $scope.master= {};
  743. $scope.update = function(user) {
  744. // Example with 1 argument
  745. $scope.master= angular.copy(user);
  746. };
  747. $scope.reset = function() {
  748. // Example with 2 arguments
  749. angular.copy($scope.master, $scope.user);
  750. };
  751. $scope.reset();
  752. }]);
  753. </script>
  754. </file>
  755. </example>
  756. */
  757. function copy(source, destination, stackSource, stackDest) {
  758. if (isWindow(source) || isScope(source)) {
  759. throw ngMinErr('cpws',
  760. "Can't copy! Making copies of Window or Scope instances is not supported.");
  761. }
  762. if (!destination) {
  763. destination = source;
  764. if (source) {
  765. if (isArray(source)) {
  766. destination = copy(source, [], stackSource, stackDest);
  767. } else if (isDate(source)) {
  768. destination = new Date(source.getTime());
  769. } else if (isRegExp(source)) {
  770. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  771. destination.lastIndex = source.lastIndex;
  772. } else if (isObject(source)) {
  773. destination = copy(source, {}, stackSource, stackDest);
  774. }
  775. }
  776. } else {
  777. if (source === destination) throw ngMinErr('cpi',
  778. "Can't copy! Source and destination are identical.");
  779. stackSource = stackSource || [];
  780. stackDest = stackDest || [];
  781. if (isObject(source)) {
  782. var index = indexOf(stackSource, source);
  783. if (index !== -1) return stackDest[index];
  784. stackSource.push(source);
  785. stackDest.push(destination);
  786. }
  787. var result;
  788. if (isArray(source)) {
  789. destination.length = 0;
  790. for ( var i = 0; i < source.length; i++) {
  791. result = copy(source[i], null, stackSource, stackDest);
  792. if (isObject(source[i])) {
  793. stackSource.push(source[i]);
  794. stackDest.push(result);
  795. }
  796. destination.push(result);
  797. }
  798. } else {
  799. var h = destination.$$hashKey;
  800. if (isArray(destination)) {
  801. destination.length = 0;
  802. } else {
  803. forEach(destination, function(value, key) {
  804. delete destination[key];
  805. });
  806. }
  807. for ( var key in source) {
  808. result = copy(source[key], null, stackSource, stackDest);
  809. if (isObject(source[key])) {
  810. stackSource.push(source[key]);
  811. stackDest.push(result);
  812. }
  813. destination[key] = result;
  814. }
  815. setHashKey(destination,h);
  816. }
  817. }
  818. return destination;
  819. }
  820. /**
  821. * Creates a shallow copy of an object, an array or a primitive
  822. */
  823. function shallowCopy(src, dst) {
  824. if (isArray(src)) {
  825. dst = dst || [];
  826. for ( var i = 0; i < src.length; i++) {
  827. dst[i] = src[i];
  828. }
  829. } else if (isObject(src)) {
  830. dst = dst || {};
  831. for (var key in src) {
  832. if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  833. dst[key] = src[key];
  834. }
  835. }
  836. }
  837. return dst || src;
  838. }
  839. /**
  840. * @ngdoc function
  841. * @name angular.equals
  842. * @module ng
  843. * @kind function
  844. *
  845. * @description
  846. * Determines if two objects or two values are equivalent. Supports value types, regular
  847. * expressions, arrays and objects.
  848. *
  849. * Two objects or values are considered equivalent if at least one of the following is true:
  850. *
  851. * * Both objects or values pass `===` comparison.
  852. * * Both objects or values are of the same type and all of their properties are equal by
  853. * comparing them with `angular.equals`.
  854. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  855. * * Both values represent the same regular expression (In JavaScript,
  856. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  857. * representation matches).
  858. *
  859. * During a property comparison, properties of `function` type and properties with names
  860. * that begin with `$` are ignored.
  861. *
  862. * Scope and DOMWindow objects are being compared only by identify (`===`).
  863. *
  864. * @param {*} o1 Object or value to compare.
  865. * @param {*} o2 Object or value to compare.
  866. * @returns {boolean} True if arguments are equal.
  867. */
  868. function equals(o1, o2) {
  869. if (o1 === o2) return true;
  870. if (o1 === null || o2 === null) return false;
  871. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  872. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  873. if (t1 == t2) {
  874. if (t1 == 'object') {
  875. if (isArray(o1)) {
  876. if (!isArray(o2)) return false;
  877. if ((length = o1.length) == o2.length) {
  878. for(key=0; key<length; key++) {
  879. if (!equals(o1[key], o2[key])) return false;
  880. }
  881. return true;
  882. }
  883. } else if (isDate(o1)) {
  884. if (!isDate(o2)) return false;
  885. return (isNaN(o1.getTime()) && isNaN(o2.getTime())) || (o1.getTime() === o2.getTime());
  886. } else if (isRegExp(o1) && isRegExp(o2)) {
  887. return o1.toString() == o2.toString();
  888. } else {
  889. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  890. keySet = {};
  891. for(key in o1) {
  892. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  893. if (!equals(o1[key], o2[key])) return false;
  894. keySet[key] = true;
  895. }
  896. for(key in o2) {
  897. if (!keySet.hasOwnProperty(key) &&
  898. key.charAt(0) !== '$' &&
  899. o2[key] !== undefined &&
  900. !isFunction(o2[key])) return false;
  901. }
  902. return true;
  903. }
  904. }
  905. }
  906. return false;
  907. }
  908. var csp = function() {
  909. if (isDefined(csp.isActive_)) return csp.isActive_;
  910. var active = !!(document.querySelector('[ng-csp]') ||
  911. document.querySelector('[data-ng-csp]'));
  912. if (!active) {
  913. try {
  914. /* jshint -W031, -W054 */
  915. new Function('');
  916. /* jshint +W031, +W054 */
  917. } catch (e) {
  918. active = true;
  919. }
  920. }
  921. return (csp.isActive_ = active);
  922. };
  923. function concat(array1, array2, index) {
  924. return array1.concat(slice.call(array2, index));
  925. }
  926. function sliceArgs(args, startIndex) {
  927. return slice.call(args, startIndex || 0);
  928. }
  929. /* jshint -W101 */
  930. /**
  931. * @ngdoc function
  932. * @name angular.bind
  933. * @module ng
  934. * @kind function
  935. *
  936. * @description
  937. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  938. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  939. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  940. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  941. *
  942. * @param {Object} self Context which `fn` should be evaluated in.
  943. * @param {function()} fn Function to be bound.
  944. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  945. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  946. */
  947. /* jshint +W101 */
  948. function bind(self, fn) {
  949. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  950. if (isFunction(fn) && !(fn instanceof RegExp)) {
  951. return curryArgs.length
  952. ? function() {
  953. return arguments.length
  954. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  955. : fn.apply(self, curryArgs);
  956. }
  957. : function() {
  958. return arguments.length
  959. ? fn.apply(self, arguments)
  960. : fn.call(self);
  961. };
  962. } else {
  963. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  964. return fn;
  965. }
  966. }
  967. function toJsonReplacer(key, value) {
  968. var val = value;
  969. if (typeof key === 'string' && key.charAt(0) === '$') {
  970. val = undefined;
  971. } else if (isWindow(value)) {
  972. val = '$WINDOW';
  973. } else if (value && document === value) {
  974. val = '$DOCUMENT';
  975. } else if (isScope(value)) {
  976. val = '$SCOPE';
  977. }
  978. return val;
  979. }
  980. /**
  981. * @ngdoc function
  982. * @name angular.toJson
  983. * @module ng
  984. * @kind function
  985. *
  986. * @description
  987. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  988. * stripped since angular uses this notation internally.
  989. *
  990. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  991. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  992. * @returns {string|undefined} JSON-ified string representing `obj`.
  993. */
  994. function toJson(obj, pretty) {
  995. if (typeof obj === 'undefined') return undefined;
  996. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  997. }
  998. /**
  999. * @ngdoc function
  1000. * @name angular.fromJson
  1001. * @module ng
  1002. * @kind function
  1003. *
  1004. * @description
  1005. * Deserializes a JSON string.
  1006. *
  1007. * @param {string} json JSON string to deserialize.
  1008. * @returns {Object|Array|string|number} Deserialized thingy.
  1009. */
  1010. function fromJson(json) {
  1011. return isString(json)
  1012. ? JSON.parse(json)
  1013. : json;
  1014. }
  1015. function toBoolean(value) {
  1016. if (typeof value === 'function') {
  1017. value = true;
  1018. } else if (value && value.length !== 0) {
  1019. var v = lowercase("" + value);
  1020. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  1021. } else {
  1022. value = false;
  1023. }
  1024. return value;
  1025. }
  1026. /**
  1027. * @returns {string} Returns the string representation of the element.
  1028. */
  1029. function startingTag(element) {
  1030. element = jqLite(element).clone();
  1031. try {
  1032. // turns out IE does not let you set .html() on elements which
  1033. // are not allowed to have children. So we just ignore it.
  1034. element.empty();
  1035. } catch(e) {}
  1036. // As Per DOM Standards
  1037. var TEXT_NODE = 3;
  1038. var elemHtml = jqLite('<div>').append(element).html();
  1039. try {
  1040. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  1041. elemHtml.
  1042. match(/^(<[^>]+>)/)[1].
  1043. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1044. } catch(e) {
  1045. return lowercase(elemHtml);
  1046. }
  1047. }
  1048. /////////////////////////////////////////////////
  1049. /**
  1050. * Tries to decode the URI component without throwing an exception.
  1051. *
  1052. * @private
  1053. * @param str value potential URI component to check.
  1054. * @returns {boolean} True if `value` can be decoded
  1055. * with the decodeURIComponent function.
  1056. */
  1057. function tryDecodeURIComponent(value) {
  1058. try {
  1059. return decodeURIComponent(value);
  1060. } catch(e) {
  1061. // Ignore any invalid uri component
  1062. }
  1063. }
  1064. /**
  1065. * Parses an escaped url query string into key-value pairs.
  1066. * @returns {Object.<string,boolean|Array>}
  1067. */
  1068. function parseKeyValue(/**string*/keyValue) {
  1069. var obj = {}, key_value, key;
  1070. forEach((keyValue || "").split('&'), function(keyValue) {
  1071. if ( keyValue ) {
  1072. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1073. key = tryDecodeURIComponent(key_value[0]);
  1074. if ( isDefined(key) ) {
  1075. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1076. if (!hasOwnProperty.call(obj, key)) {
  1077. obj[key] = val;
  1078. } else if(isArray(obj[key])) {
  1079. obj[key].push(val);
  1080. } else {
  1081. obj[key] = [obj[key],val];
  1082. }
  1083. }
  1084. }
  1085. });
  1086. return obj;
  1087. }
  1088. function toKeyValue(obj) {
  1089. var parts = [];
  1090. forEach(obj, function(value, key) {
  1091. if (isArray(value)) {
  1092. forEach(value, function(arrayValue) {
  1093. parts.push(encodeUriQuery(key, true) +
  1094. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1095. });
  1096. } else {
  1097. parts.push(encodeUriQuery(key, true) +
  1098. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1099. }
  1100. });
  1101. return parts.length ? parts.join('&') : '';
  1102. }
  1103. /**
  1104. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1105. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1106. * segments:
  1107. * segment = *pchar
  1108. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1109. * pct-encoded = "%" HEXDIG HEXDIG
  1110. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1111. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1112. * / "*" / "+" / "," / ";" / "="
  1113. */
  1114. function encodeUriSegment(val) {
  1115. return encodeUriQuery(val, true).
  1116. replace(/%26/gi, '&').
  1117. replace(/%3D/gi, '=').
  1118. replace(/%2B/gi, '+');
  1119. }
  1120. /**
  1121. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1122. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1123. * encoded per http://tools.ietf.org/html/rfc3986:
  1124. * query = *( pchar / "/" / "?" )
  1125. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1126. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1127. * pct-encoded = "%" HEXDIG HEXDIG
  1128. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1129. * / "*" / "+" / "," / ";" / "="
  1130. */
  1131. function encodeUriQuery(val, pctEncodeSpaces) {
  1132. return encodeURIComponent(val).
  1133. replace(/%40/gi, '@').
  1134. replace(/%3A/gi, ':').
  1135. replace(/%24/g, '$').
  1136. replace(/%2C/gi, ',').
  1137. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1138. }
  1139. /**
  1140. * @ngdoc directive
  1141. * @name ngApp
  1142. * @module ng
  1143. *
  1144. * @element ANY
  1145. * @param {angular.Module} ngApp an optional application
  1146. * {@link angular.module module} name to load.
  1147. *
  1148. * @description
  1149. *
  1150. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1151. * designates the **root element** of the application and is typically placed near the root element
  1152. * of the page - e.g. on the `<body>` or `<html>` tags.
  1153. *
  1154. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1155. * found in the document will be used to define the root element to auto-bootstrap as an
  1156. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1157. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1158. *
  1159. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1160. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1161. * should contain the application code needed or have dependencies on other modules that will
  1162. * contain the code. See {@link angular.module} for more information.
  1163. *
  1164. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1165. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1166. * would not be resolved to `3`.
  1167. *
  1168. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1169. *
  1170. <example module="ngAppDemo">
  1171. <file name="index.html">
  1172. <div ng-controller="ngAppDemoController">
  1173. I can add: {{a}} + {{b}} = {{ a+b }}
  1174. </div>
  1175. </file>
  1176. <file name="script.js">
  1177. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1178. $scope.a = 1;
  1179. $scope.b = 2;
  1180. });
  1181. </file>
  1182. </example>
  1183. *
  1184. */
  1185. function angularInit(element, bootstrap) {
  1186. var elements = [element],
  1187. appElement,
  1188. module,
  1189. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1190. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1191. function append(element) {
  1192. element && elements.push(element);
  1193. }
  1194. forEach(names, function(name) {
  1195. names[name] = true;
  1196. append(document.getElementById(name));
  1197. name = name.replace(':', '\\:');
  1198. if (element.querySelectorAll) {
  1199. forEach(element.querySelectorAll('.' + name), append);
  1200. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1201. forEach(element.querySelectorAll('[' + name + ']'), append);
  1202. }
  1203. });
  1204. forEach(elements, function(element) {
  1205. if (!appElement) {
  1206. var className = ' ' + element.className + ' ';
  1207. var match = NG_APP_CLASS_REGEXP.exec(className);
  1208. if (match) {
  1209. appElement = element;
  1210. module = (match[2] || '').replace(/\s+/g, ',');
  1211. } else {
  1212. forEach(element.attributes, function(attr) {
  1213. if (!appElement && names[attr.name]) {
  1214. appElement = element;
  1215. module = attr.value;
  1216. }
  1217. });
  1218. }
  1219. }
  1220. });
  1221. if (appElement) {
  1222. bootstrap(appElement, module ? [module] : []);
  1223. }
  1224. }
  1225. /**
  1226. * @ngdoc function
  1227. * @name angular.bootstrap
  1228. * @module ng
  1229. * @description
  1230. * Use this function to manually start up angular application.
  1231. *
  1232. * See: {@link guide/bootstrap Bootstrap}
  1233. *
  1234. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1235. * They must use {@link ng.directive:ngApp ngApp}.
  1236. *
  1237. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1238. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1239. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1240. * multiple instances of Angular try to work on the DOM.
  1241. *
  1242. * <example name="multi-bootstrap" module="multi-bootstrap">
  1243. * <file name="index.html">
  1244. * <script src="../../../angular.js"></script>
  1245. * <div ng-controller="BrokenTable">
  1246. * <table>
  1247. * <tr>
  1248. * <th ng-repeat="heading in headings">{{heading}}</th>
  1249. * </tr>
  1250. * <tr ng-repeat="filling in fillings">
  1251. * <td ng-repeat="fill in filling">{{fill}}</td>
  1252. * </tr>
  1253. * </table>
  1254. * </div>
  1255. * </file>
  1256. * <file name="controller.js">
  1257. * var app = angular.module('multi-bootstrap', [])
  1258. *
  1259. * .controller('BrokenTable', function($scope) {
  1260. * $scope.headings = ['One', 'Two', 'Three'];
  1261. * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
  1262. * });
  1263. * </file>
  1264. * <file name="protractor.js" type="protractor">
  1265. * it('should only insert one table cell for each item in $scope.fillings', function() {
  1266. * expect(element.all(by.css('td')).count())
  1267. * .toBe(9);
  1268. * });
  1269. * </file>
  1270. * </example>
  1271. *
  1272. * @param {DOMElement} element DOM element which is the root of angular application.
  1273. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1274. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1275. * function that will be invoked by the injector as a run block.
  1276. * See: {@link angular.module modules}
  1277. * @returns {auto.$injector} Returns the newly created injector for this app.
  1278. */
  1279. function bootstrap(element, modules) {
  1280. var doBootstrap = function() {
  1281. element = jqLite(element);
  1282. if (element.injector()) {
  1283. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1284. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1285. throw ngMinErr(
  1286. 'btstrpd',
  1287. "App Already Bootstrapped with this Element '{0}'",
  1288. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1289. }
  1290. modules = modules || [];
  1291. modules.unshift(['$provide', function($provide) {
  1292. $provide.value('$rootElement', element);
  1293. }]);
  1294. modules.unshift('ng');
  1295. var injector = createInjector(modules);
  1296. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1297. function(scope, element, compile, injector, animate) {
  1298. scope.$apply(function() {
  1299. element.data('$injector', injector);
  1300. compile(element)(scope);
  1301. });
  1302. }]
  1303. );
  1304. return injector;
  1305. };
  1306. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1307. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1308. return doBootstrap();
  1309. }
  1310. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1311. angular.resumeBootstrap = function(extraModules) {
  1312. forEach(extraModules, function(module) {
  1313. modules.push(module);
  1314. });
  1315. doBootstrap();
  1316. };
  1317. }
  1318. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1319. function snake_case(name, separator) {
  1320. separator = separator || '_';
  1321. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1322. return (pos ? separator : '') + letter.toLowerCase();
  1323. });
  1324. }
  1325. function bindJQuery() {
  1326. // bind to jQuery if present;
  1327. jQuery = window.jQuery;
  1328. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1329. // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support.
  1330. if (jQuery && jQuery.fn.on) {
  1331. jqLite = jQuery;
  1332. extend(jQuery.fn, {
  1333. scope: JQLitePrototype.scope,
  1334. isolateScope: JQLitePrototype.isolateScope,
  1335. controller: JQLitePrototype.controller,
  1336. injector: JQLitePrototype.injector,
  1337. inheritedData: JQLitePrototype.inheritedData
  1338. });
  1339. // Method signature:
  1340. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1341. jqLitePatchJQueryRemove('remove', true, true, false);
  1342. jqLitePatchJQueryRemove('empty', false, false, false);
  1343. jqLitePatchJQueryRemove('html', false, false, true);
  1344. } else {
  1345. jqLite = JQLite;
  1346. }
  1347. angular.element = jqLite;
  1348. }
  1349. /**
  1350. * throw error if the argument is falsy.
  1351. */
  1352. function assertArg(arg, name, reason) {
  1353. if (!arg) {
  1354. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1355. }
  1356. return arg;
  1357. }
  1358. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1359. if (acceptArrayAnnotation && isArray(arg)) {
  1360. arg = arg[arg.length - 1];
  1361. }
  1362. assertArg(isFunction(arg), name, 'not a function, got ' +
  1363. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1364. return arg;
  1365. }
  1366. /**
  1367. * throw error if the name given is hasOwnProperty
  1368. * @param {String} name the name to test
  1369. * @param {String} context the context in which the name is used, such as module or directive
  1370. */
  1371. function assertNotHasOwnProperty(name, context) {
  1372. if (name === 'hasOwnProperty') {
  1373. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1374. }
  1375. }
  1376. /**
  1377. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1378. * @param {Object} obj starting object
  1379. * @param {String} path path to traverse
  1380. * @param {boolean} [bindFnToScope=true]
  1381. * @returns {Object} value as accessible by path
  1382. */
  1383. //TODO(misko): this function needs to be removed
  1384. function getter(obj, path, bindFnToScope) {
  1385. if (!path) return obj;
  1386. var keys = path.split('.');
  1387. var key;
  1388. var lastInstance = obj;
  1389. var len = keys.length;
  1390. for (var i = 0; i < len; i++) {
  1391. key = keys[i];
  1392. if (obj) {
  1393. obj = (lastInstance = obj)[key];
  1394. }
  1395. }
  1396. if (!bindFnToScope && isFunction(obj)) {
  1397. return bind(lastInstance, obj);
  1398. }
  1399. return obj;
  1400. }
  1401. /**
  1402. * Return the DOM siblings between the first and last node in the given array.
  1403. * @param {Array} array like object
  1404. * @returns {DOMElement} object containing the elements
  1405. */
  1406. function getBlockElements(nodes) {
  1407. var startNode = nodes[0],
  1408. endNode = nodes[nodes.length - 1];
  1409. if (startNode === endNode) {
  1410. return jqLite(startNode);
  1411. }
  1412. var element = startNode;
  1413. var elements = [element];
  1414. do {
  1415. element = element.nextSibling;
  1416. if (!element) break;
  1417. elements.push(element);
  1418. } while (element !== endNode);
  1419. return jqLite(elements);
  1420. }
  1421. /**
  1422. * @ngdoc type
  1423. * @name angular.Module
  1424. * @module ng
  1425. * @description
  1426. *
  1427. * Interface for configuring angular {@link angular.module modules}.
  1428. */
  1429. function setupModuleLoader(window) {
  1430. var $injectorMinErr = minErr('$injector');
  1431. var ngMinErr = minErr('ng');
  1432. function ensure(obj, name, factory) {
  1433. return obj[name] || (obj[name] = factory());
  1434. }
  1435. var angular = ensure(window, 'angular', Object);
  1436. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1437. angular.$$minErr = angular.$$minErr || minErr;
  1438. return ensure(angular, 'module', function() {
  1439. /** @type {Object.<string, angular.Module>} */
  1440. var modules = {};
  1441. /**
  1442. * @ngdoc function
  1443. * @name angular.module
  1444. * @module ng
  1445. * @description
  1446. *
  1447. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1448. * modules.
  1449. * All modules (angular core or 3rd party) that should be available to an application must be
  1450. * registered using this mechanism.
  1451. *
  1452. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1453. * existing module (the name passed as the first argument to `module`) is retrieved.
  1454. *
  1455. *
  1456. * # Module
  1457. *
  1458. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1459. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1460. *
  1461. * ```js
  1462. * // Create a new module
  1463. * var myModule = angular.module('myModule', []);
  1464. *
  1465. * // register a new service
  1466. * myModule.value('appName', 'MyCoolApp');
  1467. *
  1468. * // configure existing services inside initialization blocks.
  1469. * myModule.config(['$locationProvider', function($locationProvider) {
  1470. * // Configure existing providers
  1471. * $locationProvider.hashPrefix('!');
  1472. * }]);
  1473. * ```
  1474. *
  1475. * Then you can create an injector and load your modules like this:
  1476. *
  1477. * ```js
  1478. * var injector = angular.injector(['ng', 'myModule'])
  1479. * ```
  1480. *
  1481. * However it's more likely that you'll just use
  1482. * {@link ng.directive:ngApp ngApp} or
  1483. * {@link angular.bootstrap} to simplify this process for you.
  1484. *
  1485. * @param {!string} name The name of the module to create or retrieve.
  1486. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1487. * unspecified then the module is being retrieved for further configuration.
  1488. * @param {Function=} configFn Optional configuration function for the module. Same as
  1489. * {@link angular.Module#config Module#config()}.
  1490. * @returns {module} new module with the {@link angular.Module} api.
  1491. */
  1492. return function module(name, requires, configFn) {
  1493. var assertNotHasOwnProperty = function(name, context) {
  1494. if (name === 'hasOwnProperty') {
  1495. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1496. }
  1497. };
  1498. assertNotHasOwnProperty(name, 'module');
  1499. if (requires && modules.hasOwnProperty(name)) {
  1500. modules[name] = null;
  1501. }
  1502. return ensure(modules, name, function() {
  1503. if (!requires) {
  1504. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1505. "the module name or forgot to load it. If registering a module ensure that you " +
  1506. "specify the dependencies as the second argument.", name);
  1507. }
  1508. /** @type {!Array.<Array.<*>>} */
  1509. var invokeQueue = [];
  1510. /** @type {!Array.<Function>} */
  1511. var runBlocks = [];
  1512. var config = invokeLater('$injector', 'invoke');
  1513. /** @type {angular.Module} */
  1514. var moduleInstance = {
  1515. // Private state
  1516. _invokeQueue: invokeQueue,
  1517. _runBlocks: runBlocks,
  1518. /**
  1519. * @ngdoc property
  1520. * @name angular.Module#requires
  1521. * @module ng
  1522. *
  1523. * @description
  1524. * Holds the list of modules which the injector will load before the current module is
  1525. * loaded.
  1526. */
  1527. requires: requires,
  1528. /**
  1529. * @ngdoc property
  1530. * @name angular.Module#name
  1531. * @module ng
  1532. *
  1533. * @description
  1534. * Name of the module.
  1535. */
  1536. name: name,
  1537. /**
  1538. * @ngdoc method
  1539. * @name angular.Module#provider
  1540. * @module ng
  1541. * @param {string} name service name
  1542. * @param {Function} providerType Construction function for creating new instance of the
  1543. * service.
  1544. * @description
  1545. * See {@link auto.$provide#provider $provide.provider()}.
  1546. */
  1547. provider: invokeLater('$provide', 'provider'),
  1548. /**
  1549. * @ngdoc method
  1550. * @name angular.Module#factory
  1551. * @module ng
  1552. * @param {string} name service name
  1553. * @param {Function} providerFunction Function for creating new instance of the service.
  1554. * @description
  1555. * See {@link auto.$provide#factory $provide.factory()}.
  1556. */
  1557. factory: invokeLater('$provide', 'factory'),
  1558. /**
  1559. * @ngdoc method
  1560. * @name angular.Module#service
  1561. * @module ng
  1562. * @param {string} name service name
  1563. * @param {Function} constructor A constructor function that will be instantiated.
  1564. * @description
  1565. * See {@link auto.$provide#service $provide.service()}.
  1566. */
  1567. service: invokeLater('$provide', 'service'),
  1568. /**
  1569. * @ngdoc method
  1570. * @name angular.Module#value
  1571. * @module ng
  1572. * @param {string} name service name
  1573. * @param {*} object Service instance object.
  1574. * @description
  1575. * See {@link auto.$provide#value $provide.value()}.
  1576. */
  1577. value: invokeLater('$provide', 'value'),
  1578. /**
  1579. * @ngdoc method
  1580. * @name angular.Module#constant
  1581. * @module ng
  1582. * @param {string} name constant name
  1583. * @param {*} object Constant value.
  1584. * @description
  1585. * Because the constant are fixed, they get applied before other provide methods.
  1586. * See {@link auto.$provide#constant $provide.constant()}.
  1587. */
  1588. constant: invokeLater('$provide', 'constant', 'unshift'),
  1589. /**
  1590. * @ngdoc method
  1591. * @name angular.Module#animation
  1592. * @module ng
  1593. * @param {string} name animation name
  1594. * @param {Function} animationFactory Factory function for creating new instance of an
  1595. * animation.
  1596. * @description
  1597. *
  1598. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1599. *
  1600. *
  1601. * Defines an animation hook that can be later used with
  1602. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1603. *
  1604. * ```js
  1605. * module.animation('.animation-name', function($inject1, $inject2) {
  1606. * return {
  1607. * eventName : function(element, done) {
  1608. * //code to run the animation
  1609. * //once complete, then run done()
  1610. * return function cancellationFunction(element) {
  1611. * //code to cancel the animation
  1612. * }
  1613. * }
  1614. * }
  1615. * })
  1616. * ```
  1617. *
  1618. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1619. * {@link ngAnimate ngAnimate module} for more information.
  1620. */
  1621. animation: invokeLater('$animateProvider', 'register'),
  1622. /**
  1623. * @ngdoc method
  1624. * @name angular.Module#filter
  1625. * @module ng
  1626. * @param {string} name Filter name.
  1627. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1628. * @description
  1629. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1630. */
  1631. filter: invokeLater('$filterProvider', 'register'),
  1632. /**
  1633. * @ngdoc method
  1634. * @name angular.Module#controller
  1635. * @module ng
  1636. * @param {string|Object} name Controller name, or an object map of controllers where the
  1637. * keys are the names and the values are the constructors.
  1638. * @param {Function} constructor Controller constructor function.
  1639. * @description
  1640. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1641. */
  1642. controller: invokeLater('$controllerProvider', 'register'),
  1643. /**
  1644. * @ngdoc method
  1645. * @name angular.Module#directive
  1646. * @module ng
  1647. * @param {string|Object} name Directive name, or an object map of directives where the
  1648. * keys are the names and the values are the factories.
  1649. * @param {Function} directiveFactory Factory function for creating new instance of
  1650. * directives.
  1651. * @description
  1652. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1653. */
  1654. directive: invokeLater('$compileProvider', 'directive'),
  1655. /**
  1656. * @ngdoc method
  1657. * @name angular.Module#config
  1658. * @module ng
  1659. * @param {Function} configFn Execute this function on module load. Useful for service
  1660. * configuration.
  1661. * @description
  1662. * Use this method to register work which needs to be performed on module loading.
  1663. * For more about how to configure services, see
  1664. * {@link providers#providers_provider-recipe Provider Recipe}.
  1665. */
  1666. config: config,
  1667. /**
  1668. * @ngdoc method
  1669. * @name angular.Module#run
  1670. * @module ng
  1671. * @param {Function} initializationFn Execute this function after injector creation.
  1672. * Useful for application initialization.
  1673. * @description
  1674. * Use this method to register work which should be performed when the injector is done
  1675. * loading all modules.
  1676. */
  1677. run: function(block) {
  1678. runBlocks.push(block);
  1679. return this;
  1680. }
  1681. };
  1682. if (configFn) {
  1683. config(configFn);
  1684. }
  1685. return moduleInstance;
  1686. /**
  1687. * @param {string} provider
  1688. * @param {string} method
  1689. * @param {String=} insertMethod
  1690. * @returns {angular.Module}
  1691. */
  1692. function invokeLater(provider, method, insertMethod) {
  1693. return function() {
  1694. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1695. return moduleInstance;
  1696. };
  1697. }
  1698. });
  1699. };
  1700. });
  1701. }
  1702. /* global angularModule: true,
  1703. version: true,
  1704. $LocaleProvider,
  1705. $CompileProvider,
  1706. htmlAnchorDirective,
  1707. inputDirective,
  1708. inputDirective,
  1709. formDirective,
  1710. scriptDirective,
  1711. selectDirective,
  1712. styleDirective,
  1713. optionDirective,
  1714. ngBindDirective,
  1715. ngBindHtmlDirective,
  1716. ngBindTemplateDirective,
  1717. ngClassDirective,
  1718. ngClassEvenDirective,
  1719. ngClassOddDirective,
  1720. ngCspDirective,
  1721. ngCloakDirective,
  1722. ngControllerDirective,
  1723. ngFormDirective,
  1724. ngHideDirective,
  1725. ngIfDirective,
  1726. ngIncludeDirective,
  1727. ngIncludeFillContentDirective,
  1728. ngInitDirective,
  1729. ngNonBindableDirective,
  1730. ngPluralizeDirective,
  1731. ngRepeatDirective,
  1732. ngShowDirective,
  1733. ngStyleDirective,
  1734. ngSwitchDirective,
  1735. ngSwitchWhenDirective,
  1736. ngSwitchDefaultDirective,
  1737. ngOptionsDirective,
  1738. ngTranscludeDirective,
  1739. ngModelDirective,
  1740. ngListDirective,
  1741. ngChangeDirective,
  1742. requiredDirective,
  1743. requiredDirective,
  1744. ngValueDirective,
  1745. ngAttributeAliasDirectives,
  1746. ngEventDirectives,
  1747. $AnchorScrollProvider,
  1748. $AnimateProvider,
  1749. $BrowserProvider,
  1750. $CacheFactoryProvider,
  1751. $ControllerProvider,
  1752. $DocumentProvider,
  1753. $ExceptionHandlerProvider,
  1754. $FilterProvider,
  1755. $InterpolateProvider,
  1756. $IntervalProvider,
  1757. $HttpProvider,
  1758. $HttpBackendProvider,
  1759. $LocationProvider,
  1760. $LogProvider,
  1761. $ParseProvider,
  1762. $RootScopeProvider,
  1763. $QProvider,
  1764. $$SanitizeUriProvider,
  1765. $SceProvider,
  1766. $SceDelegateProvider,
  1767. $SnifferProvider,
  1768. $TemplateCacheProvider,
  1769. $TimeoutProvider,
  1770. $$RAFProvider,
  1771. $$AsyncCallbackProvider,
  1772. $WindowProvider
  1773. */
  1774. /**
  1775. * @ngdoc object
  1776. * @name angular.version
  1777. * @module ng
  1778. * @description
  1779. * An object that contains information about the current AngularJS version. This object has the
  1780. * following properties:
  1781. *
  1782. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1783. * - `major` – `{number}` – Major version number, such as "0".
  1784. * - `minor` – `{number}` – Minor version number, such as "9".
  1785. * - `dot` – `{number}` – Dot version number, such as "18".
  1786. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1787. */
  1788. var version = {
  1789. full: '1.2.28', // all of these placeholder strings will be replaced by grunt's
  1790. major: 1, // package task
  1791. minor: 2,
  1792. dot: 28,
  1793. codeName: 'finnish-disembarkation'
  1794. };
  1795. function publishExternalAPI(angular){
  1796. extend(angular, {
  1797. 'bootstrap': bootstrap,
  1798. 'copy': copy,
  1799. 'extend': extend,
  1800. 'equals': equals,
  1801. 'element': jqLite,
  1802. 'forEach': forEach,
  1803. 'injector': createInjector,
  1804. 'noop': noop,
  1805. 'bind': bind,
  1806. 'toJson': toJson,
  1807. 'fromJson': fromJson,
  1808. 'identity': identity,
  1809. 'isUndefined': isUndefined,
  1810. 'isDefined': isDefined,
  1811. 'isString': isString,
  1812. 'isFunction': isFunction,
  1813. 'isObject': isObject,
  1814. 'isNumber': isNumber,
  1815. 'isElement': isElement,
  1816. 'isArray': isArray,
  1817. 'version': version,
  1818. 'isDate': isDate,
  1819. 'lowercase': lowercase,
  1820. 'uppercase': uppercase,
  1821. 'callbacks': {counter: 0},
  1822. '$$minErr': minErr,
  1823. '$$csp': csp
  1824. });
  1825. angularModule = setupModuleLoader(window);
  1826. try {
  1827. angularModule('ngLocale');
  1828. } catch (e) {
  1829. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1830. }
  1831. angularModule('ng', ['ngLocale'], ['$provide',
  1832. function ngModule($provide) {
  1833. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1834. $provide.provider({
  1835. $$sanitizeUri: $$SanitizeUriProvider
  1836. });
  1837. $provide.provider('$compile', $CompileProvider).
  1838. directive({
  1839. a: htmlAnchorDirective,
  1840. input: inputDirective,
  1841. textarea: inputDirective,
  1842. form: formDirective,
  1843. script: scriptDirective,
  1844. select: selectDirective,
  1845. style: styleDirective,
  1846. option: optionDirective,
  1847. ngBind: ngBindDirective,
  1848. ngBindHtml: ngBindHtmlDirective,
  1849. ngBindTemplate: ngBindTemplateDirective,
  1850. ngClass: ngClassDirective,
  1851. ngClassEven: ngClassEvenDirective,
  1852. ngClassOdd: ngClassOddDirective,
  1853. ngCloak: ngCloakDirective,
  1854. ngController: ngControllerDirective,
  1855. ngForm: ngFormDirective,
  1856. ngHide: ngHideDirective,
  1857. ngIf: ngIfDirective,
  1858. ngInclude: ngIncludeDirective,
  1859. ngInit: ngInitDirective,
  1860. ngNonBindable: ngNonBindableDirective,
  1861. ngPluralize: ngPluralizeDirective,
  1862. ngRepeat: ngRepeatDirective,
  1863. ngShow: ngShowDirective,
  1864. ngStyle: ngStyleDirective,
  1865. ngSwitch: ngSwitchDirective,
  1866. ngSwitchWhen: ngSwitchWhenDirective,
  1867. ngSwitchDefault: ngSwitchDefaultDirective,
  1868. ngOptions: ngOptionsDirective,
  1869. ngTransclude: ngTranscludeDirective,
  1870. ngModel: ngModelDirective,
  1871. ngList: ngListDirective,
  1872. ngChange: ngChangeDirective,
  1873. required: requiredDirective,
  1874. ngRequired: requiredDirective,
  1875. ngValue: ngValueDirective
  1876. }).
  1877. directive({
  1878. ngInclude: ngIncludeFillContentDirective
  1879. }).
  1880. directive(ngAttributeAliasDirectives).
  1881. directive(ngEventDirectives);
  1882. $provide.provider({
  1883. $anchorScroll: $AnchorScrollProvider,
  1884. $animate: $AnimateProvider,
  1885. $browser: $BrowserProvider,
  1886. $cacheFactory: $CacheFactoryProvider,
  1887. $controller: $ControllerProvider,
  1888. $document: $DocumentProvider,
  1889. $exceptionHandler: $ExceptionHandlerProvider,
  1890. $filter: $FilterProvider,
  1891. $interpolate: $InterpolateProvider,
  1892. $interval: $IntervalProvider,
  1893. $http: $HttpProvider,
  1894. $httpBackend: $HttpBackendProvider,
  1895. $location: $LocationProvider,
  1896. $log: $LogProvider,
  1897. $parse: $ParseProvider,
  1898. $rootScope: $RootScopeProvider,
  1899. $q: $QProvider,
  1900. $sce: $SceProvider,
  1901. $sceDelegate: $SceDelegateProvider,
  1902. $sniffer: $SnifferProvider,
  1903. $templateCache: $TemplateCacheProvider,
  1904. $timeout: $TimeoutProvider,
  1905. $window: $WindowProvider,
  1906. $$rAF: $$RAFProvider,
  1907. $$asyncCallback : $$AsyncCallbackProvider
  1908. });
  1909. }
  1910. ]);
  1911. }
  1912. /* global JQLitePrototype: true,
  1913. addEventListenerFn: true,
  1914. removeEventListenerFn: true,
  1915. BOOLEAN_ATTR: true
  1916. */
  1917. //////////////////////////////////
  1918. //JQLite
  1919. //////////////////////////////////
  1920. /**
  1921. * @ngdoc function
  1922. * @name angular.element
  1923. * @module ng
  1924. * @kind function
  1925. *
  1926. * @description
  1927. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1928. *
  1929. * If jQuery is available, `angular.element` is an alias for the
  1930. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1931. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1932. *
  1933. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1934. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1935. * commonly needed functionality with the goal of having a very small footprint.</div>
  1936. *
  1937. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1938. *
  1939. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1940. * jqLite; they are never raw DOM references.</div>
  1941. *
  1942. * ## Angular's jqLite
  1943. * jqLite provides only the following jQuery methods:
  1944. *
  1945. * - [`addClass()`](http://api.jquery.com/addClass/)
  1946. * - [`after()`](http://api.jquery.com/after/)
  1947. * - [`append()`](http://api.jquery.com/append/)
  1948. * - [`attr()`](http://api.jquery.com/attr/)
  1949. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  1950. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1951. * - [`clone()`](http://api.jquery.com/clone/)
  1952. * - [`contents()`](http://api.jquery.com/contents/)
  1953. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()`
  1954. * - [`data()`](http://api.jquery.com/data/)
  1955. * - [`empty()`](http://api.jquery.com/empty/)
  1956. * - [`eq()`](http://api.jquery.com/eq/)
  1957. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1958. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1959. * - [`html()`](http://api.jquery.com/html/)
  1960. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1961. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1962. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1963. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1964. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1965. * - [`prepend()`](http://api.jquery.com/prepend/)
  1966. * - [`prop()`](http://api.jquery.com/prop/)
  1967. * - [`ready()`](http://api.jquery.com/ready/)
  1968. * - [`remove()`](http://api.jquery.com/remove/)
  1969. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1970. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1971. * - [`removeData()`](http://api.jquery.com/removeData/)
  1972. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1973. * - [`text()`](http://api.jquery.com/text/)
  1974. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1975. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1976. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  1977. * - [`val()`](http://api.jquery.com/val/)
  1978. * - [`wrap()`](http://api.jquery.com/wrap/)
  1979. *
  1980. * ## jQuery/jqLite Extras
  1981. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1982. *
  1983. * ### Events
  1984. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1985. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1986. * element before it is removed.
  1987. *
  1988. * ### Methods
  1989. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1990. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1991. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1992. * `'ngModel'`).
  1993. * - `injector()` - retrieves the injector of the current element or its parent.
  1994. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  1995. * element or its parent.
  1996. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  1997. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1998. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1999. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2000. * parent element is reached.
  2001. *
  2002. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2003. * @returns {Object} jQuery object.
  2004. */
  2005. JQLite.expando = 'ng339';
  2006. var jqCache = JQLite.cache = {},
  2007. jqId = 1,
  2008. addEventListenerFn = (window.document.addEventListener
  2009. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  2010. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  2011. removeEventListenerFn = (window.document.removeEventListener
  2012. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  2013. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  2014. /*
  2015. * !!! This is an undocumented "private" function !!!
  2016. */
  2017. var jqData = JQLite._data = function(node) {
  2018. //jQuery always returns an object on cache miss
  2019. return this.cache[node[this.expando]] || {};
  2020. };
  2021. function jqNextId() { return ++jqId; }
  2022. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2023. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2024. var jqLiteMinErr = minErr('jqLite');
  2025. /**
  2026. * Converts snake_case to camelCase.
  2027. * Also there is special case for Moz prefix starting with upper case letter.
  2028. * @param name Name to normalize
  2029. */
  2030. function camelCase(name) {
  2031. return name.
  2032. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2033. return offset ? letter.toUpperCase() : letter;
  2034. }).
  2035. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2036. }
  2037. /////////////////////////////////////////////
  2038. // jQuery mutation patch
  2039. //
  2040. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  2041. // $destroy event on all DOM nodes being removed.
  2042. //
  2043. /////////////////////////////////////////////
  2044. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  2045. var originalJqFn = jQuery.fn[name];
  2046. originalJqFn = originalJqFn.$original || originalJqFn;
  2047. removePatch.$original = originalJqFn;
  2048. jQuery.fn[name] = removePatch;
  2049. function removePatch(param) {
  2050. // jshint -W040
  2051. var list = filterElems && param ? [this.filter(param)] : [this],
  2052. fireEvent = dispatchThis,
  2053. set, setIndex, setLength,
  2054. element, childIndex, childLength, children;
  2055. if (!getterIfNoArguments || param != null) {
  2056. while(list.length) {
  2057. set = list.shift();
  2058. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  2059. element = jqLite(set[setIndex]);
  2060. if (fireEvent) {
  2061. element.triggerHandler('$destroy');
  2062. } else {
  2063. fireEvent = !fireEvent;
  2064. }
  2065. for(childIndex = 0, childLength = (children = element.children()).length;
  2066. childIndex < childLength;
  2067. childIndex++) {
  2068. list.push(jQuery(children[childIndex]));
  2069. }
  2070. }
  2071. }
  2072. }
  2073. return originalJqFn.apply(this, arguments);
  2074. }
  2075. }
  2076. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2077. var HTML_REGEXP = /<|&#?\w+;/;
  2078. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2079. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2080. var wrapMap = {
  2081. 'option': [1, '<select multiple="multiple">', '</select>'],
  2082. 'thead': [1, '<table>', '</table>'],
  2083. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2084. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2085. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2086. '_default': [0, "", ""]
  2087. };
  2088. wrapMap.optgroup = wrapMap.option;
  2089. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2090. wrapMap.th = wrapMap.td;
  2091. function jqLiteIsTextNode(html) {
  2092. return !HTML_REGEXP.test(html);
  2093. }
  2094. function jqLiteBuildFragment(html, context) {
  2095. var elem, tmp, tag, wrap,
  2096. fragment = context.createDocumentFragment(),
  2097. nodes = [], i, j, jj;
  2098. if (jqLiteIsTextNode(html)) {
  2099. // Convert non-html into a text node
  2100. nodes.push(context.createTextNode(html));
  2101. } else {
  2102. tmp = fragment.appendChild(context.createElement('div'));
  2103. // Convert html into DOM nodes
  2104. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2105. wrap = wrapMap[tag] || wrapMap._default;
  2106. tmp.innerHTML = '<div>&#160;</div>' +
  2107. wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2108. tmp.removeChild(tmp.firstChild);
  2109. // Descend through wrappers to the right content
  2110. i = wrap[0];
  2111. while (i--) {
  2112. tmp = tmp.lastChild;
  2113. }
  2114. for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);
  2115. tmp = fragment.firstChild;
  2116. tmp.textContent = "";
  2117. }
  2118. // Remove wrapper from fragment
  2119. fragment.textContent = "";
  2120. fragment.innerHTML = ""; // Clear inner HTML
  2121. return nodes;
  2122. }
  2123. function jqLiteParseHTML(html, context) {
  2124. context = context || document;
  2125. var parsed;
  2126. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2127. return [context.createElement(parsed[1])];
  2128. }
  2129. return jqLiteBuildFragment(html, context);
  2130. }
  2131. /////////////////////////////////////////////
  2132. function JQLite(element) {
  2133. if (element instanceof JQLite) {
  2134. return element;
  2135. }
  2136. if (isString(element)) {
  2137. element = trim(element);
  2138. }
  2139. if (!(this instanceof JQLite)) {
  2140. if (isString(element) && element.charAt(0) != '<') {
  2141. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2142. }
  2143. return new JQLite(element);
  2144. }
  2145. if (isString(element)) {
  2146. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2147. var fragment = jqLite(document.createDocumentFragment());
  2148. fragment.append(this);
  2149. } else {
  2150. jqLiteAddNodes(this, element);
  2151. }
  2152. }
  2153. function jqLiteClone(element) {
  2154. return element.cloneNode(true);
  2155. }
  2156. function jqLiteDealoc(element){
  2157. jqLiteRemoveData(element);
  2158. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  2159. jqLiteDealoc(children[i]);
  2160. }
  2161. }
  2162. function jqLiteOff(element, type, fn, unsupported) {
  2163. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2164. var events = jqLiteExpandoStore(element, 'events'),
  2165. handle = jqLiteExpandoStore(element, 'handle');
  2166. if (!handle) return; //no listeners registered
  2167. if (isUndefined(type)) {
  2168. forEach(events, function(eventHandler, type) {
  2169. removeEventListenerFn(element, type, eventHandler);
  2170. delete events[type];
  2171. });
  2172. } else {
  2173. forEach(type.split(' '), function(type) {
  2174. if (isUndefined(fn)) {
  2175. removeEventListenerFn(element, type, events[type]);
  2176. delete events[type];
  2177. } else {
  2178. arrayRemove(events[type] || [], fn);
  2179. }
  2180. });
  2181. }
  2182. }
  2183. function jqLiteRemoveData(element, name) {
  2184. var expandoId = element.ng339,
  2185. expandoStore = jqCache[expandoId];
  2186. if (expandoStore) {
  2187. if (name) {
  2188. delete jqCache[expandoId].data[name];
  2189. return;
  2190. }
  2191. if (expandoStore.handle) {
  2192. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  2193. jqLiteOff(element);
  2194. }
  2195. delete jqCache[expandoId];
  2196. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2197. }
  2198. }
  2199. function jqLiteExpandoStore(element, key, value) {
  2200. var expandoId = element.ng339,
  2201. expandoStore = jqCache[expandoId || -1];
  2202. if (isDefined(value)) {
  2203. if (!expandoStore) {
  2204. element.ng339 = expandoId = jqNextId();
  2205. expandoStore = jqCache[expandoId] = {};
  2206. }
  2207. expandoStore[key] = value;
  2208. } else {
  2209. return expandoStore && expandoStore[key];
  2210. }
  2211. }
  2212. function jqLiteData(element, key, value) {
  2213. var data = jqLiteExpandoStore(element, 'data'),
  2214. isSetter = isDefined(value),
  2215. keyDefined = !isSetter && isDefined(key),
  2216. isSimpleGetter = keyDefined && !isObject(key);
  2217. if (!data && !isSimpleGetter) {
  2218. jqLiteExpandoStore(element, 'data', data = {});
  2219. }
  2220. if (isSetter) {
  2221. data[key] = value;
  2222. } else {
  2223. if (keyDefined) {
  2224. if (isSimpleGetter) {
  2225. // don't create data in this case.
  2226. return data && data[key];
  2227. } else {
  2228. extend(data, key);
  2229. }
  2230. } else {
  2231. return data;
  2232. }
  2233. }
  2234. }
  2235. function jqLiteHasClass(element, selector) {
  2236. if (!element.getAttribute) return false;
  2237. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2238. indexOf( " " + selector + " " ) > -1);
  2239. }
  2240. function jqLiteRemoveClass(element, cssClasses) {
  2241. if (cssClasses && element.setAttribute) {
  2242. forEach(cssClasses.split(' '), function(cssClass) {
  2243. element.setAttribute('class', trim(
  2244. (" " + (element.getAttribute('class') || '') + " ")
  2245. .replace(/[\n\t]/g, " ")
  2246. .replace(" " + trim(cssClass) + " ", " "))
  2247. );
  2248. });
  2249. }
  2250. }
  2251. function jqLiteAddClass(element, cssClasses) {
  2252. if (cssClasses && element.setAttribute) {
  2253. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2254. .replace(/[\n\t]/g, " ");
  2255. forEach(cssClasses.split(' '), function(cssClass) {
  2256. cssClass = trim(cssClass);
  2257. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2258. existingClasses += cssClass + ' ';
  2259. }
  2260. });
  2261. element.setAttribute('class', trim(existingClasses));
  2262. }
  2263. }
  2264. function jqLiteAddNodes(root, elements) {
  2265. if (elements) {
  2266. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2267. ? elements
  2268. : [ elements ];
  2269. for(var i=0; i < elements.length; i++) {
  2270. root.push(elements[i]);
  2271. }
  2272. }
  2273. }
  2274. function jqLiteController(element, name) {
  2275. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2276. }
  2277. function jqLiteInheritedData(element, name, value) {
  2278. // if element is the document object work with the html element instead
  2279. // this makes $(document).scope() possible
  2280. if(element.nodeType == 9) {
  2281. element = element.documentElement;
  2282. }
  2283. var names = isArray(name) ? name : [name];
  2284. while (element) {
  2285. for (var i = 0, ii = names.length; i < ii; i++) {
  2286. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2287. }
  2288. // If dealing with a document fragment node with a host element, and no parent, use the host
  2289. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2290. // to lookup parent controllers.
  2291. element = element.parentNode || (element.nodeType === 11 && element.host);
  2292. }
  2293. }
  2294. function jqLiteEmpty(element) {
  2295. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2296. jqLiteDealoc(childNodes[i]);
  2297. }
  2298. while (element.firstChild) {
  2299. element.removeChild(element.firstChild);
  2300. }
  2301. }
  2302. //////////////////////////////////////////
  2303. // Functions which are declared directly.
  2304. //////////////////////////////////////////
  2305. var JQLitePrototype = JQLite.prototype = {
  2306. ready: function(fn) {
  2307. var fired = false;
  2308. function trigger() {
  2309. if (fired) return;
  2310. fired = true;
  2311. fn();
  2312. }
  2313. // check if document already is loaded
  2314. if (document.readyState === 'complete'){
  2315. setTimeout(trigger);
  2316. } else {
  2317. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2318. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2319. // jshint -W064
  2320. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2321. // jshint +W064
  2322. }
  2323. },
  2324. toString: function() {
  2325. var value = [];
  2326. forEach(this, function(e){ value.push('' + e);});
  2327. return '[' + value.join(', ') + ']';
  2328. },
  2329. eq: function(index) {
  2330. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2331. },
  2332. length: 0,
  2333. push: push,
  2334. sort: [].sort,
  2335. splice: [].splice
  2336. };
  2337. //////////////////////////////////////////
  2338. // Functions iterating getter/setters.
  2339. // these functions return self on setter and
  2340. // value on get.
  2341. //////////////////////////////////////////
  2342. var BOOLEAN_ATTR = {};
  2343. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2344. BOOLEAN_ATTR[lowercase(value)] = value;
  2345. });
  2346. var BOOLEAN_ELEMENTS = {};
  2347. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2348. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2349. });
  2350. function getBooleanAttrName(element, name) {
  2351. // check dom last since we will most likely fail on name
  2352. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2353. // booleanAttr is here twice to minimize DOM access
  2354. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2355. }
  2356. forEach({
  2357. data: jqLiteData,
  2358. removeData: jqLiteRemoveData
  2359. }, function(fn, name) {
  2360. JQLite[name] = fn;
  2361. });
  2362. forEach({
  2363. data: jqLiteData,
  2364. inheritedData: jqLiteInheritedData,
  2365. scope: function(element) {
  2366. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2367. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2368. },
  2369. isolateScope: function(element) {
  2370. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2371. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2372. },
  2373. controller: jqLiteController,
  2374. injector: function(element) {
  2375. return jqLiteInheritedData(element, '$injector');
  2376. },
  2377. removeAttr: function(element,name) {
  2378. element.removeAttribute(name);
  2379. },
  2380. hasClass: jqLiteHasClass,
  2381. css: function(element, name, value) {
  2382. name = camelCase(name);
  2383. if (isDefined(value)) {
  2384. element.style[name] = value;
  2385. } else {
  2386. var val;
  2387. if (msie <= 8) {
  2388. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2389. val = element.currentStyle && element.currentStyle[name];
  2390. if (val === '') val = 'auto';
  2391. }
  2392. val = val || element.style[name];
  2393. if (msie <= 8) {
  2394. // jquery weirdness :-/
  2395. val = (val === '') ? undefined : val;
  2396. }
  2397. return val;
  2398. }
  2399. },
  2400. attr: function(element, name, value){
  2401. var lowercasedName = lowercase(name);
  2402. if (BOOLEAN_ATTR[lowercasedName]) {
  2403. if (isDefined(value)) {
  2404. if (!!value) {
  2405. element[name] = true;
  2406. element.setAttribute(name, lowercasedName);
  2407. } else {
  2408. element[name] = false;
  2409. element.removeAttribute(lowercasedName);
  2410. }
  2411. } else {
  2412. return (element[name] ||
  2413. (element.attributes.getNamedItem(name)|| noop).specified)
  2414. ? lowercasedName
  2415. : undefined;
  2416. }
  2417. } else if (isDefined(value)) {
  2418. element.setAttribute(name, value);
  2419. } else if (element.getAttribute) {
  2420. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2421. // some elements (e.g. Document) don't have get attribute, so return undefined
  2422. var ret = element.getAttribute(name, 2);
  2423. // normalize non-existing attributes to undefined (as jQuery)
  2424. return ret === null ? undefined : ret;
  2425. }
  2426. },
  2427. prop: function(element, name, value) {
  2428. if (isDefined(value)) {
  2429. element[name] = value;
  2430. } else {
  2431. return element[name];
  2432. }
  2433. },
  2434. text: (function() {
  2435. var NODE_TYPE_TEXT_PROPERTY = [];
  2436. if (msie < 9) {
  2437. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2438. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2439. } else {
  2440. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2441. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2442. }
  2443. getText.$dv = '';
  2444. return getText;
  2445. function getText(element, value) {
  2446. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2447. if (isUndefined(value)) {
  2448. return textProp ? element[textProp] : '';
  2449. }
  2450. element[textProp] = value;
  2451. }
  2452. })(),
  2453. val: function(element, value) {
  2454. if (isUndefined(value)) {
  2455. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2456. var result = [];
  2457. forEach(element.options, function (option) {
  2458. if (option.selected) {
  2459. result.push(option.value || option.text);
  2460. }
  2461. });
  2462. return result.length === 0 ? null : result;
  2463. }
  2464. return element.value;
  2465. }
  2466. element.value = value;
  2467. },
  2468. html: function(element, value) {
  2469. if (isUndefined(value)) {
  2470. return element.innerHTML;
  2471. }
  2472. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2473. jqLiteDealoc(childNodes[i]);
  2474. }
  2475. element.innerHTML = value;
  2476. },
  2477. empty: jqLiteEmpty
  2478. }, function(fn, name){
  2479. /**
  2480. * Properties: writes return selection, reads return first value
  2481. */
  2482. JQLite.prototype[name] = function(arg1, arg2) {
  2483. var i, key;
  2484. var nodeCount = this.length;
  2485. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2486. // in a way that survives minification.
  2487. // jqLiteEmpty takes no arguments but is a setter.
  2488. if (fn !== jqLiteEmpty &&
  2489. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2490. if (isObject(arg1)) {
  2491. // we are a write, but the object properties are the key/values
  2492. for (i = 0; i < nodeCount; i++) {
  2493. if (fn === jqLiteData) {
  2494. // data() takes the whole object in jQuery
  2495. fn(this[i], arg1);
  2496. } else {
  2497. for (key in arg1) {
  2498. fn(this[i], key, arg1[key]);
  2499. }
  2500. }
  2501. }
  2502. // return self for chaining
  2503. return this;
  2504. } else {
  2505. // we are a read, so read the first child.
  2506. // TODO: do we still need this?
  2507. var value = fn.$dv;
  2508. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2509. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2510. for (var j = 0; j < jj; j++) {
  2511. var nodeValue = fn(this[j], arg1, arg2);
  2512. value = value ? value + nodeValue : nodeValue;
  2513. }
  2514. return value;
  2515. }
  2516. } else {
  2517. // we are a write, so apply to all children
  2518. for (i = 0; i < nodeCount; i++) {
  2519. fn(this[i], arg1, arg2);
  2520. }
  2521. // return self for chaining
  2522. return this;
  2523. }
  2524. };
  2525. });
  2526. function createEventHandler(element, events) {
  2527. var eventHandler = function (event, type) {
  2528. if (!event.preventDefault) {
  2529. event.preventDefault = function() {
  2530. event.returnValue = false; //ie
  2531. };
  2532. }
  2533. if (!event.stopPropagation) {
  2534. event.stopPropagation = function() {
  2535. event.cancelBubble = true; //ie
  2536. };
  2537. }
  2538. if (!event.target) {
  2539. event.target = event.srcElement || document;
  2540. }
  2541. if (isUndefined(event.defaultPrevented)) {
  2542. var prevent = event.preventDefault;
  2543. event.preventDefault = function() {
  2544. event.defaultPrevented = true;
  2545. prevent.call(event);
  2546. };
  2547. event.defaultPrevented = false;
  2548. }
  2549. event.isDefaultPrevented = function() {
  2550. return event.defaultPrevented || event.returnValue === false;
  2551. };
  2552. // Copy event handlers in case event handlers array is modified during execution.
  2553. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2554. forEach(eventHandlersCopy, function(fn) {
  2555. fn.call(element, event);
  2556. });
  2557. // Remove monkey-patched methods (IE),
  2558. // as they would cause memory leaks in IE8.
  2559. if (msie <= 8) {
  2560. // IE7/8 does not allow to delete property on native object
  2561. event.preventDefault = null;
  2562. event.stopPropagation = null;
  2563. event.isDefaultPrevented = null;
  2564. } else {
  2565. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2566. delete event.preventDefault;
  2567. delete event.stopPropagation;
  2568. delete event.isDefaultPrevented;
  2569. }
  2570. };
  2571. eventHandler.elem = element;
  2572. return eventHandler;
  2573. }
  2574. //////////////////////////////////////////
  2575. // Functions iterating traversal.
  2576. // These functions chain results into a single
  2577. // selector.
  2578. //////////////////////////////////////////
  2579. forEach({
  2580. removeData: jqLiteRemoveData,
  2581. dealoc: jqLiteDealoc,
  2582. on: function onFn(element, type, fn, unsupported){
  2583. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2584. var events = jqLiteExpandoStore(element, 'events'),
  2585. handle = jqLiteExpandoStore(element, 'handle');
  2586. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2587. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2588. forEach(type.split(' '), function(type){
  2589. var eventFns = events[type];
  2590. if (!eventFns) {
  2591. if (type == 'mouseenter' || type == 'mouseleave') {
  2592. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2593. function( a, b ) {
  2594. // jshint bitwise: false
  2595. var adown = a.nodeType === 9 ? a.documentElement : a,
  2596. bup = b && b.parentNode;
  2597. return a === bup || !!( bup && bup.nodeType === 1 && (
  2598. adown.contains ?
  2599. adown.contains( bup ) :
  2600. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2601. ));
  2602. } :
  2603. function( a, b ) {
  2604. if ( b ) {
  2605. while ( (b = b.parentNode) ) {
  2606. if ( b === a ) {
  2607. return true;
  2608. }
  2609. }
  2610. }
  2611. return false;
  2612. };
  2613. events[type] = [];
  2614. // Refer to jQuery's implementation of mouseenter & mouseleave
  2615. // Read about mouseenter and mouseleave:
  2616. // http://www.quirksmode.org/js/events_mouse.html#link8
  2617. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2618. onFn(element, eventmap[type], function(event) {
  2619. var target = this, related = event.relatedTarget;
  2620. // For mousenter/leave call the handler if related is outside the target.
  2621. // NB: No relatedTarget if the mouse left/entered the browser window
  2622. if ( !related || (related !== target && !contains(target, related)) ){
  2623. handle(event, type);
  2624. }
  2625. });
  2626. } else {
  2627. addEventListenerFn(element, type, handle);
  2628. events[type] = [];
  2629. }
  2630. eventFns = events[type];
  2631. }
  2632. eventFns.push(fn);
  2633. });
  2634. },
  2635. off: jqLiteOff,
  2636. one: function(element, type, fn) {
  2637. element = jqLite(element);
  2638. //add the listener twice so that when it is called
  2639. //you can remove the original function and still be
  2640. //able to call element.off(ev, fn) normally
  2641. element.on(type, function onFn() {
  2642. element.off(type, fn);
  2643. element.off(type, onFn);
  2644. });
  2645. element.on(type, fn);
  2646. },
  2647. replaceWith: function(element, replaceNode) {
  2648. var index, parent = element.parentNode;
  2649. jqLiteDealoc(element);
  2650. forEach(new JQLite(replaceNode), function(node){
  2651. if (index) {
  2652. parent.insertBefore(node, index.nextSibling);
  2653. } else {
  2654. parent.replaceChild(node, element);
  2655. }
  2656. index = node;
  2657. });
  2658. },
  2659. children: function(element) {
  2660. var children = [];
  2661. forEach(element.childNodes, function(element){
  2662. if (element.nodeType === 1)
  2663. children.push(element);
  2664. });
  2665. return children;
  2666. },
  2667. contents: function(element) {
  2668. return element.contentDocument || element.childNodes || [];
  2669. },
  2670. append: function(element, node) {
  2671. forEach(new JQLite(node), function(child){
  2672. if (element.nodeType === 1 || element.nodeType === 11) {
  2673. element.appendChild(child);
  2674. }
  2675. });
  2676. },
  2677. prepend: function(element, node) {
  2678. if (element.nodeType === 1) {
  2679. var index = element.firstChild;
  2680. forEach(new JQLite(node), function(child){
  2681. element.insertBefore(child, index);
  2682. });
  2683. }
  2684. },
  2685. wrap: function(element, wrapNode) {
  2686. wrapNode = jqLite(wrapNode)[0];
  2687. var parent = element.parentNode;
  2688. if (parent) {
  2689. parent.replaceChild(wrapNode, element);
  2690. }
  2691. wrapNode.appendChild(element);
  2692. },
  2693. remove: function(element) {
  2694. jqLiteDealoc(element);
  2695. var parent = element.parentNode;
  2696. if (parent) parent.removeChild(element);
  2697. },
  2698. after: function(element, newElement) {
  2699. var index = element, parent = element.parentNode;
  2700. forEach(new JQLite(newElement), function(node){
  2701. parent.insertBefore(node, index.nextSibling);
  2702. index = node;
  2703. });
  2704. },
  2705. addClass: jqLiteAddClass,
  2706. removeClass: jqLiteRemoveClass,
  2707. toggleClass: function(element, selector, condition) {
  2708. if (selector) {
  2709. forEach(selector.split(' '), function(className){
  2710. var classCondition = condition;
  2711. if (isUndefined(classCondition)) {
  2712. classCondition = !jqLiteHasClass(element, className);
  2713. }
  2714. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2715. });
  2716. }
  2717. },
  2718. parent: function(element) {
  2719. var parent = element.parentNode;
  2720. return parent && parent.nodeType !== 11 ? parent : null;
  2721. },
  2722. next: function(element) {
  2723. if (element.nextElementSibling) {
  2724. return element.nextElementSibling;
  2725. }
  2726. // IE8 doesn't have nextElementSibling
  2727. var elm = element.nextSibling;
  2728. while (elm != null && elm.nodeType !== 1) {
  2729. elm = elm.nextSibling;
  2730. }
  2731. return elm;
  2732. },
  2733. find: function(element, selector) {
  2734. if (element.getElementsByTagName) {
  2735. return element.getElementsByTagName(selector);
  2736. } else {
  2737. return [];
  2738. }
  2739. },
  2740. clone: jqLiteClone,
  2741. triggerHandler: function(element, event, extraParameters) {
  2742. var dummyEvent, eventFnsCopy, handlerArgs;
  2743. var eventName = event.type || event;
  2744. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2745. if (eventFns) {
  2746. // Create a dummy event to pass to the handlers
  2747. dummyEvent = {
  2748. preventDefault: function() { this.defaultPrevented = true; },
  2749. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2750. stopPropagation: noop,
  2751. type: eventName,
  2752. target: element
  2753. };
  2754. // If a custom event was provided then extend our dummy event with it
  2755. if (event.type) {
  2756. dummyEvent = extend(dummyEvent, event);
  2757. }
  2758. // Copy event handlers in case event handlers array is modified during execution.
  2759. eventFnsCopy = shallowCopy(eventFns);
  2760. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2761. forEach(eventFnsCopy, function(fn) {
  2762. fn.apply(element, handlerArgs);
  2763. });
  2764. }
  2765. }
  2766. }, function(fn, name){
  2767. /**
  2768. * chaining functions
  2769. */
  2770. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2771. var value;
  2772. for(var i=0; i < this.length; i++) {
  2773. if (isUndefined(value)) {
  2774. value = fn(this[i], arg1, arg2, arg3);
  2775. if (isDefined(value)) {
  2776. // any function which returns a value needs to be wrapped
  2777. value = jqLite(value);
  2778. }
  2779. } else {
  2780. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2781. }
  2782. }
  2783. return isDefined(value) ? value : this;
  2784. };
  2785. // bind legacy bind/unbind to on/off
  2786. JQLite.prototype.bind = JQLite.prototype.on;
  2787. JQLite.prototype.unbind = JQLite.prototype.off;
  2788. });
  2789. /**
  2790. * Computes a hash of an 'obj'.
  2791. * Hash of a:
  2792. * string is string
  2793. * number is number as string
  2794. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2795. * that is also assigned to the $$hashKey property of the object.
  2796. *
  2797. * @param obj
  2798. * @returns {string} hash string such that the same input will have the same hash string.
  2799. * The resulting string key is in 'type:hashKey' format.
  2800. */
  2801. function hashKey(obj, nextUidFn) {
  2802. var objType = typeof obj,
  2803. key;
  2804. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2805. if (typeof (key = obj.$$hashKey) == 'function') {
  2806. // must invoke on object to keep the right this
  2807. key = obj.$$hashKey();
  2808. } else if (key === undefined) {
  2809. key = obj.$$hashKey = (nextUidFn || nextUid)();
  2810. }
  2811. } else {
  2812. key = obj;
  2813. }
  2814. return objType + ':' + key;
  2815. }
  2816. /**
  2817. * HashMap which can use objects as keys
  2818. */
  2819. function HashMap(array, isolatedUid) {
  2820. if (isolatedUid) {
  2821. var uid = 0;
  2822. this.nextUid = function() {
  2823. return ++uid;
  2824. };
  2825. }
  2826. forEach(array, this.put, this);
  2827. }
  2828. HashMap.prototype = {
  2829. /**
  2830. * Store key value pair
  2831. * @param key key to store can be any type
  2832. * @param value value to store can be any type
  2833. */
  2834. put: function(key, value) {
  2835. this[hashKey(key, this.nextUid)] = value;
  2836. },
  2837. /**
  2838. * @param key
  2839. * @returns {Object} the value for the key
  2840. */
  2841. get: function(key) {
  2842. return this[hashKey(key, this.nextUid)];
  2843. },
  2844. /**
  2845. * Remove the key/value pair
  2846. * @param key
  2847. */
  2848. remove: function(key) {
  2849. var value = this[key = hashKey(key, this.nextUid)];
  2850. delete this[key];
  2851. return value;
  2852. }
  2853. };
  2854. /**
  2855. * @ngdoc function
  2856. * @module ng
  2857. * @name angular.injector
  2858. * @kind function
  2859. *
  2860. * @description
  2861. * Creates an injector object that can be used for retrieving services as well as for
  2862. * dependency injection (see {@link guide/di dependency injection}).
  2863. *
  2864. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2865. * {@link angular.module}. The `ng` module must be explicitly added.
  2866. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2867. *
  2868. * @example
  2869. * Typical usage
  2870. * ```js
  2871. * // create an injector
  2872. * var $injector = angular.injector(['ng']);
  2873. *
  2874. * // use the injector to kick off your application
  2875. * // use the type inference to auto inject arguments, or use implicit injection
  2876. * $injector.invoke(function($rootScope, $compile, $document){
  2877. * $compile($document)($rootScope);
  2878. * $rootScope.$digest();
  2879. * });
  2880. * ```
  2881. *
  2882. * Sometimes you want to get access to the injector of a currently running Angular app
  2883. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2884. * application has been bootstrapped. You can do this using the extra `injector()` added
  2885. * to JQuery/jqLite elements. See {@link angular.element}.
  2886. *
  2887. * *This is fairly rare but could be the case if a third party library is injecting the
  2888. * markup.*
  2889. *
  2890. * In the following example a new block of HTML containing a `ng-controller`
  2891. * directive is added to the end of the document body by JQuery. We then compile and link
  2892. * it into the current AngularJS scope.
  2893. *
  2894. * ```js
  2895. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2896. * $(document.body).append($div);
  2897. *
  2898. * angular.element(document).injector().invoke(function($compile) {
  2899. * var scope = angular.element($div).scope();
  2900. * $compile($div)(scope);
  2901. * });
  2902. * ```
  2903. */
  2904. /**
  2905. * @ngdoc module
  2906. * @name auto
  2907. * @description
  2908. *
  2909. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2910. */
  2911. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2912. var FN_ARG_SPLIT = /,/;
  2913. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2914. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2915. var $injectorMinErr = minErr('$injector');
  2916. function annotate(fn) {
  2917. var $inject,
  2918. fnText,
  2919. argDecl,
  2920. last;
  2921. if (typeof fn === 'function') {
  2922. if (!($inject = fn.$inject)) {
  2923. $inject = [];
  2924. if (fn.length) {
  2925. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2926. argDecl = fnText.match(FN_ARGS);
  2927. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2928. arg.replace(FN_ARG, function(all, underscore, name){
  2929. $inject.push(name);
  2930. });
  2931. });
  2932. }
  2933. fn.$inject = $inject;
  2934. }
  2935. } else if (isArray(fn)) {
  2936. last = fn.length - 1;
  2937. assertArgFn(fn[last], 'fn');
  2938. $inject = fn.slice(0, last);
  2939. } else {
  2940. assertArgFn(fn, 'fn', true);
  2941. }
  2942. return $inject;
  2943. }
  2944. ///////////////////////////////////////
  2945. /**
  2946. * @ngdoc service
  2947. * @name $injector
  2948. *
  2949. * @description
  2950. *
  2951. * `$injector` is used to retrieve object instances as defined by
  2952. * {@link auto.$provide provider}, instantiate types, invoke methods,
  2953. * and load modules.
  2954. *
  2955. * The following always holds true:
  2956. *
  2957. * ```js
  2958. * var $injector = angular.injector();
  2959. * expect($injector.get('$injector')).toBe($injector);
  2960. * expect($injector.invoke(function($injector){
  2961. * return $injector;
  2962. * })).toBe($injector);
  2963. * ```
  2964. *
  2965. * # Injection Function Annotation
  2966. *
  2967. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2968. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2969. *
  2970. * ```js
  2971. * // inferred (only works if code not minified/obfuscated)
  2972. * $injector.invoke(function(serviceA){});
  2973. *
  2974. * // annotated
  2975. * function explicit(serviceA) {};
  2976. * explicit.$inject = ['serviceA'];
  2977. * $injector.invoke(explicit);
  2978. *
  2979. * // inline
  2980. * $injector.invoke(['serviceA', function(serviceA){}]);
  2981. * ```
  2982. *
  2983. * ## Inference
  2984. *
  2985. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2986. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2987. * minification, and obfuscation tools since these tools change the argument names.
  2988. *
  2989. * ## `$inject` Annotation
  2990. * By adding an `$inject` property onto a function the injection parameters can be specified.
  2991. *
  2992. * ## Inline
  2993. * As an array of injection names, where the last item in the array is the function to call.
  2994. */
  2995. /**
  2996. * @ngdoc method
  2997. * @name $injector#get
  2998. *
  2999. * @description
  3000. * Return an instance of the service.
  3001. *
  3002. * @param {string} name The name of the instance to retrieve.
  3003. * @return {*} The instance.
  3004. */
  3005. /**
  3006. * @ngdoc method
  3007. * @name $injector#invoke
  3008. *
  3009. * @description
  3010. * Invoke the method and supply the method arguments from the `$injector`.
  3011. *
  3012. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3013. * {@link guide/di $inject Annotation} rules.
  3014. * @param {Object=} self The `this` for the invoked method.
  3015. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3016. * object first, before the `$injector` is consulted.
  3017. * @returns {*} the value returned by the invoked `fn` function.
  3018. */
  3019. /**
  3020. * @ngdoc method
  3021. * @name $injector#has
  3022. *
  3023. * @description
  3024. * Allows the user to query if the particular service exists.
  3025. *
  3026. * @param {string} name Name of the service to query.
  3027. * @returns {boolean} `true` if injector has given service.
  3028. */
  3029. /**
  3030. * @ngdoc method
  3031. * @name $injector#instantiate
  3032. * @description
  3033. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3034. * operator, and supplies all of the arguments to the constructor function as specified by the
  3035. * constructor annotation.
  3036. *
  3037. * @param {Function} Type Annotated constructor function.
  3038. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3039. * object first, before the `$injector` is consulted.
  3040. * @returns {Object} new instance of `Type`.
  3041. */
  3042. /**
  3043. * @ngdoc method
  3044. * @name $injector#annotate
  3045. *
  3046. * @description
  3047. * Returns an array of service names which the function is requesting for injection. This API is
  3048. * used by the injector to determine which services need to be injected into the function when the
  3049. * function is invoked. There are three ways in which the function can be annotated with the needed
  3050. * dependencies.
  3051. *
  3052. * # Argument names
  3053. *
  3054. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3055. * by converting the function into a string using `toString()` method and extracting the argument
  3056. * names.
  3057. * ```js
  3058. * // Given
  3059. * function MyController($scope, $route) {
  3060. * // ...
  3061. * }
  3062. *
  3063. * // Then
  3064. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3065. * ```
  3066. *
  3067. * This method does not work with code minification / obfuscation. For this reason the following
  3068. * annotation strategies are supported.
  3069. *
  3070. * # The `$inject` property
  3071. *
  3072. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3073. * represent names of services to be injected into the function.
  3074. * ```js
  3075. * // Given
  3076. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3077. * // ...
  3078. * }
  3079. * // Define function dependencies
  3080. * MyController['$inject'] = ['$scope', '$route'];
  3081. *
  3082. * // Then
  3083. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3084. * ```
  3085. *
  3086. * # The array notation
  3087. *
  3088. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3089. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3090. * a way that survives minification is a better choice:
  3091. *
  3092. * ```js
  3093. * // We wish to write this (not minification / obfuscation safe)
  3094. * injector.invoke(function($compile, $rootScope) {
  3095. * // ...
  3096. * });
  3097. *
  3098. * // We are forced to write break inlining
  3099. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3100. * // ...
  3101. * };
  3102. * tmpFn.$inject = ['$compile', '$rootScope'];
  3103. * injector.invoke(tmpFn);
  3104. *
  3105. * // To better support inline function the inline annotation is supported
  3106. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3107. * // ...
  3108. * }]);
  3109. *
  3110. * // Therefore
  3111. * expect(injector.annotate(
  3112. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3113. * ).toEqual(['$compile', '$rootScope']);
  3114. * ```
  3115. *
  3116. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3117. * be retrieved as described above.
  3118. *
  3119. * @returns {Array.<string>} The names of the services which the function requires.
  3120. */
  3121. /**
  3122. * @ngdoc service
  3123. * @name $provide
  3124. *
  3125. * @description
  3126. *
  3127. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3128. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3129. * {@link angular.Module}.
  3130. *
  3131. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3132. * factories** are functions which, in turn, are created by a **service provider**.
  3133. * The **service providers** are constructor functions. When instantiated they must contain a
  3134. * property called `$get`, which holds the **service factory** function.
  3135. *
  3136. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3137. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3138. * function to get the instance of the **service**.
  3139. *
  3140. * Often services have no configuration options and there is no need to add methods to the service
  3141. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3142. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3143. * services without specifying a provider.
  3144. *
  3145. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3146. * {@link auto.$injector $injector}
  3147. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3148. * providers and services.
  3149. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3150. * services, not providers.
  3151. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3152. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3153. * given factory function.
  3154. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3155. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3156. * a new object using the given constructor function.
  3157. *
  3158. * See the individual methods for more information and examples.
  3159. */
  3160. /**
  3161. * @ngdoc method
  3162. * @name $provide#provider
  3163. * @description
  3164. *
  3165. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3166. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3167. * service.
  3168. *
  3169. * Service provider names start with the name of the service they provide followed by `Provider`.
  3170. * For example, the {@link ng.$log $log} service has a provider called
  3171. * {@link ng.$logProvider $logProvider}.
  3172. *
  3173. * Service provider objects can have additional methods which allow configuration of the provider
  3174. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3175. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3176. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3177. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3178. * console or not.
  3179. *
  3180. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3181. 'Provider'` key.
  3182. * @param {(Object|function())} provider If the provider is:
  3183. *
  3184. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3185. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3186. * - `Constructor`: a new instance of the provider will be created using
  3187. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3188. *
  3189. * @returns {Object} registered provider instance
  3190. * @example
  3191. *
  3192. * The following example shows how to create a simple event tracking service and register it using
  3193. * {@link auto.$provide#provider $provide.provider()}.
  3194. *
  3195. * ```js
  3196. * // Define the eventTracker provider
  3197. * function EventTrackerProvider() {
  3198. * var trackingUrl = '/track';
  3199. *
  3200. * // A provider method for configuring where the tracked events should been saved
  3201. * this.setTrackingUrl = function(url) {
  3202. * trackingUrl = url;
  3203. * };
  3204. *
  3205. * // The service factory function
  3206. * this.$get = ['$http', function($http) {
  3207. * var trackedEvents = {};
  3208. * return {
  3209. * // Call this to track an event
  3210. * event: function(event) {
  3211. * var count = trackedEvents[event] || 0;
  3212. * count += 1;
  3213. * trackedEvents[event] = count;
  3214. * return count;
  3215. * },
  3216. * // Call this to save the tracked events to the trackingUrl
  3217. * save: function() {
  3218. * $http.post(trackingUrl, trackedEvents);
  3219. * }
  3220. * };
  3221. * }];
  3222. * }
  3223. *
  3224. * describe('eventTracker', function() {
  3225. * var postSpy;
  3226. *
  3227. * beforeEach(module(function($provide) {
  3228. * // Register the eventTracker provider
  3229. * $provide.provider('eventTracker', EventTrackerProvider);
  3230. * }));
  3231. *
  3232. * beforeEach(module(function(eventTrackerProvider) {
  3233. * // Configure eventTracker provider
  3234. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3235. * }));
  3236. *
  3237. * it('tracks events', inject(function(eventTracker) {
  3238. * expect(eventTracker.event('login')).toEqual(1);
  3239. * expect(eventTracker.event('login')).toEqual(2);
  3240. * }));
  3241. *
  3242. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3243. * postSpy = spyOn($http, 'post');
  3244. * eventTracker.event('login');
  3245. * eventTracker.save();
  3246. * expect(postSpy).toHaveBeenCalled();
  3247. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3248. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3249. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3250. * }));
  3251. * });
  3252. * ```
  3253. */
  3254. /**
  3255. * @ngdoc method
  3256. * @name $provide#factory
  3257. * @description
  3258. *
  3259. * Register a **service factory**, which will be called to return the service instance.
  3260. * This is short for registering a service where its provider consists of only a `$get` property,
  3261. * which is the given service factory function.
  3262. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3263. * configure your service in a provider.
  3264. *
  3265. * @param {string} name The name of the instance.
  3266. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3267. * for `$provide.provider(name, {$get: $getFn})`.
  3268. * @returns {Object} registered provider instance
  3269. *
  3270. * @example
  3271. * Here is an example of registering a service
  3272. * ```js
  3273. * $provide.factory('ping', ['$http', function($http) {
  3274. * return function ping() {
  3275. * return $http.send('/ping');
  3276. * };
  3277. * }]);
  3278. * ```
  3279. * You would then inject and use this service like this:
  3280. * ```js
  3281. * someModule.controller('Ctrl', ['ping', function(ping) {
  3282. * ping();
  3283. * }]);
  3284. * ```
  3285. */
  3286. /**
  3287. * @ngdoc method
  3288. * @name $provide#service
  3289. * @description
  3290. *
  3291. * Register a **service constructor**, which will be invoked with `new` to create the service
  3292. * instance.
  3293. * This is short for registering a service where its provider's `$get` property is the service
  3294. * constructor function that will be used to instantiate the service instance.
  3295. *
  3296. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3297. * as a type/class.
  3298. *
  3299. * @param {string} name The name of the instance.
  3300. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3301. * @returns {Object} registered provider instance
  3302. *
  3303. * @example
  3304. * Here is an example of registering a service using
  3305. * {@link auto.$provide#service $provide.service(class)}.
  3306. * ```js
  3307. * var Ping = function($http) {
  3308. * this.$http = $http;
  3309. * };
  3310. *
  3311. * Ping.$inject = ['$http'];
  3312. *
  3313. * Ping.prototype.send = function() {
  3314. * return this.$http.get('/ping');
  3315. * };
  3316. * $provide.service('ping', Ping);
  3317. * ```
  3318. * You would then inject and use this service like this:
  3319. * ```js
  3320. * someModule.controller('Ctrl', ['ping', function(ping) {
  3321. * ping.send();
  3322. * }]);
  3323. * ```
  3324. */
  3325. /**
  3326. * @ngdoc method
  3327. * @name $provide#value
  3328. * @description
  3329. *
  3330. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3331. * number, an array, an object or a function. This is short for registering a service where its
  3332. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3333. * service**.
  3334. *
  3335. * Value services are similar to constant services, except that they cannot be injected into a
  3336. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3337. * an Angular
  3338. * {@link auto.$provide#decorator decorator}.
  3339. *
  3340. * @param {string} name The name of the instance.
  3341. * @param {*} value The value.
  3342. * @returns {Object} registered provider instance
  3343. *
  3344. * @example
  3345. * Here are some examples of creating value services.
  3346. * ```js
  3347. * $provide.value('ADMIN_USER', 'admin');
  3348. *
  3349. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3350. *
  3351. * $provide.value('halfOf', function(value) {
  3352. * return value / 2;
  3353. * });
  3354. * ```
  3355. */
  3356. /**
  3357. * @ngdoc method
  3358. * @name $provide#constant
  3359. * @description
  3360. *
  3361. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3362. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3363. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3364. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3365. *
  3366. * @param {string} name The name of the constant.
  3367. * @param {*} value The constant value.
  3368. * @returns {Object} registered instance
  3369. *
  3370. * @example
  3371. * Here a some examples of creating constants:
  3372. * ```js
  3373. * $provide.constant('SHARD_HEIGHT', 306);
  3374. *
  3375. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3376. *
  3377. * $provide.constant('double', function(value) {
  3378. * return value * 2;
  3379. * });
  3380. * ```
  3381. */
  3382. /**
  3383. * @ngdoc method
  3384. * @name $provide#decorator
  3385. * @description
  3386. *
  3387. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3388. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3389. * service. The object returned by the decorator may be the original service, or a new service
  3390. * object which replaces or wraps and delegates to the original service.
  3391. *
  3392. * @param {string} name The name of the service to decorate.
  3393. * @param {function()} decorator This function will be invoked when the service needs to be
  3394. * instantiated and should return the decorated service instance. The function is called using
  3395. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3396. * Local injection arguments:
  3397. *
  3398. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3399. * decorated or delegated to.
  3400. *
  3401. * @example
  3402. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3403. * calls to {@link ng.$log#error $log.warn()}.
  3404. * ```js
  3405. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3406. * $delegate.warn = $delegate.error;
  3407. * return $delegate;
  3408. * }]);
  3409. * ```
  3410. */
  3411. function createInjector(modulesToLoad) {
  3412. var INSTANTIATING = {},
  3413. providerSuffix = 'Provider',
  3414. path = [],
  3415. loadedModules = new HashMap([], true),
  3416. providerCache = {
  3417. $provide: {
  3418. provider: supportObject(provider),
  3419. factory: supportObject(factory),
  3420. service: supportObject(service),
  3421. value: supportObject(value),
  3422. constant: supportObject(constant),
  3423. decorator: decorator
  3424. }
  3425. },
  3426. providerInjector = (providerCache.$injector =
  3427. createInternalInjector(providerCache, function() {
  3428. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3429. })),
  3430. instanceCache = {},
  3431. instanceInjector = (instanceCache.$injector =
  3432. createInternalInjector(instanceCache, function(servicename) {
  3433. var provider = providerInjector.get(servicename + providerSuffix);
  3434. return instanceInjector.invoke(provider.$get, provider);
  3435. }));
  3436. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3437. return instanceInjector;
  3438. ////////////////////////////////////
  3439. // $provider
  3440. ////////////////////////////////////
  3441. function supportObject(delegate) {
  3442. return function(key, value) {
  3443. if (isObject(key)) {
  3444. forEach(key, reverseParams(delegate));
  3445. } else {
  3446. return delegate(key, value);
  3447. }
  3448. };
  3449. }
  3450. function provider(name, provider_) {
  3451. assertNotHasOwnProperty(name, 'service');
  3452. if (isFunction(provider_) || isArray(provider_)) {
  3453. provider_ = providerInjector.instantiate(provider_);
  3454. }
  3455. if (!provider_.$get) {
  3456. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3457. }
  3458. return providerCache[name + providerSuffix] = provider_;
  3459. }
  3460. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3461. function service(name, constructor) {
  3462. return factory(name, ['$injector', function($injector) {
  3463. return $injector.instantiate(constructor);
  3464. }]);
  3465. }
  3466. function value(name, val) { return factory(name, valueFn(val)); }
  3467. function constant(name, value) {
  3468. assertNotHasOwnProperty(name, 'constant');
  3469. providerCache[name] = value;
  3470. instanceCache[name] = value;
  3471. }
  3472. function decorator(serviceName, decorFn) {
  3473. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3474. orig$get = origProvider.$get;
  3475. origProvider.$get = function() {
  3476. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3477. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3478. };
  3479. }
  3480. ////////////////////////////////////
  3481. // Module Loading
  3482. ////////////////////////////////////
  3483. function loadModules(modulesToLoad){
  3484. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3485. forEach(modulesToLoad, function(module) {
  3486. if (loadedModules.get(module)) return;
  3487. loadedModules.put(module, true);
  3488. try {
  3489. if (isString(module)) {
  3490. moduleFn = angularModule(module);
  3491. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3492. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3493. var invokeArgs = invokeQueue[i],
  3494. provider = providerInjector.get(invokeArgs[0]);
  3495. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3496. }
  3497. } else if (isFunction(module)) {
  3498. runBlocks.push(providerInjector.invoke(module));
  3499. } else if (isArray(module)) {
  3500. runBlocks.push(providerInjector.invoke(module));
  3501. } else {
  3502. assertArgFn(module, 'module');
  3503. }
  3504. } catch (e) {
  3505. if (isArray(module)) {
  3506. module = module[module.length - 1];
  3507. }
  3508. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3509. // Safari & FF's stack traces don't contain error.message content
  3510. // unlike those of Chrome and IE
  3511. // So if stack doesn't contain message, we create a new string that contains both.
  3512. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3513. /* jshint -W022 */
  3514. e = e.message + '\n' + e.stack;
  3515. }
  3516. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3517. module, e.stack || e.message || e);
  3518. }
  3519. });
  3520. return runBlocks;
  3521. }
  3522. ////////////////////////////////////
  3523. // internal Injector
  3524. ////////////////////////////////////
  3525. function createInternalInjector(cache, factory) {
  3526. function getService(serviceName) {
  3527. if (cache.hasOwnProperty(serviceName)) {
  3528. if (cache[serviceName] === INSTANTIATING) {
  3529. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3530. serviceName + ' <- ' + path.join(' <- '));
  3531. }
  3532. return cache[serviceName];
  3533. } else {
  3534. try {
  3535. path.unshift(serviceName);
  3536. cache[serviceName] = INSTANTIATING;
  3537. return cache[serviceName] = factory(serviceName);
  3538. } catch (err) {
  3539. if (cache[serviceName] === INSTANTIATING) {
  3540. delete cache[serviceName];
  3541. }
  3542. throw err;
  3543. } finally {
  3544. path.shift();
  3545. }
  3546. }
  3547. }
  3548. function invoke(fn, self, locals){
  3549. var args = [],
  3550. $inject = annotate(fn),
  3551. length, i,
  3552. key;
  3553. for(i = 0, length = $inject.length; i < length; i++) {
  3554. key = $inject[i];
  3555. if (typeof key !== 'string') {
  3556. throw $injectorMinErr('itkn',
  3557. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3558. }
  3559. args.push(
  3560. locals && locals.hasOwnProperty(key)
  3561. ? locals[key]
  3562. : getService(key)
  3563. );
  3564. }
  3565. if (isArray(fn)) {
  3566. fn = fn[length];
  3567. }
  3568. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3569. // #5388
  3570. return fn.apply(self, args);
  3571. }
  3572. function instantiate(Type, locals) {
  3573. var Constructor = function() {},
  3574. instance, returnedValue;
  3575. // Check if Type is annotated and use just the given function at n-1 as parameter
  3576. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3577. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3578. instance = new Constructor();
  3579. returnedValue = invoke(Type, instance, locals);
  3580. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3581. }
  3582. return {
  3583. invoke: invoke,
  3584. instantiate: instantiate,
  3585. get: getService,
  3586. annotate: annotate,
  3587. has: function(name) {
  3588. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3589. }
  3590. };
  3591. }
  3592. }
  3593. /**
  3594. * @ngdoc service
  3595. * @name $anchorScroll
  3596. * @kind function
  3597. * @requires $window
  3598. * @requires $location
  3599. * @requires $rootScope
  3600. *
  3601. * @description
  3602. * When called, it checks current value of `$location.hash()` and scrolls to the related element,
  3603. * according to rules specified in
  3604. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3605. *
  3606. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3607. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3608. *
  3609. * @example
  3610. <example>
  3611. <file name="index.html">
  3612. <div id="scrollArea" ng-controller="ScrollCtrl">
  3613. <a ng-click="gotoBottom()">Go to bottom</a>
  3614. <a id="bottom"></a> You're at the bottom!
  3615. </div>
  3616. </file>
  3617. <file name="script.js">
  3618. function ScrollCtrl($scope, $location, $anchorScroll) {
  3619. $scope.gotoBottom = function (){
  3620. // set the location.hash to the id of
  3621. // the element you wish to scroll to.
  3622. $location.hash('bottom');
  3623. // call $anchorScroll()
  3624. $anchorScroll();
  3625. };
  3626. }
  3627. </file>
  3628. <file name="style.css">
  3629. #scrollArea {
  3630. height: 350px;
  3631. overflow: auto;
  3632. }
  3633. #bottom {
  3634. display: block;
  3635. margin-top: 2000px;
  3636. }
  3637. </file>
  3638. </example>
  3639. */
  3640. function $AnchorScrollProvider() {
  3641. var autoScrollingEnabled = true;
  3642. /**
  3643. * @ngdoc method
  3644. * @name $anchorScrollProvider#disableAutoScrolling
  3645. *
  3646. * @description
  3647. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  3648. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3649. * Use this method to disable automatic scrolling.
  3650. *
  3651. * If automatic scrolling is disabled, one must explicitly call
  3652. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3653. * current hash.
  3654. */
  3655. this.disableAutoScrolling = function() {
  3656. autoScrollingEnabled = false;
  3657. };
  3658. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3659. var document = $window.document;
  3660. // helper function to get first anchor from a NodeList
  3661. // can't use filter.filter, as it accepts only instances of Array
  3662. // and IE can't convert NodeList to an array using [].slice
  3663. // TODO(vojta): use filter if we change it to accept lists as well
  3664. function getFirstAnchor(list) {
  3665. var result = null;
  3666. forEach(list, function(element) {
  3667. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3668. });
  3669. return result;
  3670. }
  3671. function scroll() {
  3672. var hash = $location.hash(), elm;
  3673. // empty hash, scroll to the top of the page
  3674. if (!hash) $window.scrollTo(0, 0);
  3675. // element with given id
  3676. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3677. // first anchor with given name :-D
  3678. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3679. // no element and hash == 'top', scroll to the top of the page
  3680. else if (hash === 'top') $window.scrollTo(0, 0);
  3681. }
  3682. // does not scroll when user clicks on anchor link that is currently on
  3683. // (no url change, no $location.hash() change), browser native does scroll
  3684. if (autoScrollingEnabled) {
  3685. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3686. function autoScrollWatchAction() {
  3687. $rootScope.$evalAsync(scroll);
  3688. });
  3689. }
  3690. return scroll;
  3691. }];
  3692. }
  3693. var $animateMinErr = minErr('$animate');
  3694. /**
  3695. * @ngdoc provider
  3696. * @name $animateProvider
  3697. *
  3698. * @description
  3699. * Default implementation of $animate that doesn't perform any animations, instead just
  3700. * synchronously performs DOM
  3701. * updates and calls done() callbacks.
  3702. *
  3703. * In order to enable animations the ngAnimate module has to be loaded.
  3704. *
  3705. * To see the functional implementation check out src/ngAnimate/animate.js
  3706. */
  3707. var $AnimateProvider = ['$provide', function($provide) {
  3708. this.$$selectors = {};
  3709. /**
  3710. * @ngdoc method
  3711. * @name $animateProvider#register
  3712. *
  3713. * @description
  3714. * Registers a new injectable animation factory function. The factory function produces the
  3715. * animation object which contains callback functions for each event that is expected to be
  3716. * animated.
  3717. *
  3718. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3719. * must be called once the element animation is complete. If a function is returned then the
  3720. * animation service will use this function to cancel the animation whenever a cancel event is
  3721. * triggered.
  3722. *
  3723. *
  3724. * ```js
  3725. * return {
  3726. * eventFn : function(element, done) {
  3727. * //code to run the animation
  3728. * //once complete, then run done()
  3729. * return function cancellationFunction() {
  3730. * //code to cancel the animation
  3731. * }
  3732. * }
  3733. * }
  3734. * ```
  3735. *
  3736. * @param {string} name The name of the animation.
  3737. * @param {Function} factory The factory function that will be executed to return the animation
  3738. * object.
  3739. */
  3740. this.register = function(name, factory) {
  3741. var key = name + '-animation';
  3742. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3743. "Expecting class selector starting with '.' got '{0}'.", name);
  3744. this.$$selectors[name.substr(1)] = key;
  3745. $provide.factory(key, factory);
  3746. };
  3747. /**
  3748. * @ngdoc method
  3749. * @name $animateProvider#classNameFilter
  3750. *
  3751. * @description
  3752. * Sets and/or returns the CSS class regular expression that is checked when performing
  3753. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3754. * therefore enable $animate to attempt to perform an animation on any element.
  3755. * When setting the classNameFilter value, animations will only be performed on elements
  3756. * that successfully match the filter expression. This in turn can boost performance
  3757. * for low-powered devices as well as applications containing a lot of structural operations.
  3758. * @param {RegExp=} expression The className expression which will be checked against all animations
  3759. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3760. */
  3761. this.classNameFilter = function(expression) {
  3762. if(arguments.length === 1) {
  3763. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3764. }
  3765. return this.$$classNameFilter;
  3766. };
  3767. this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
  3768. function async(fn) {
  3769. fn && $$asyncCallback(fn);
  3770. }
  3771. /**
  3772. *
  3773. * @ngdoc service
  3774. * @name $animate
  3775. * @description The $animate service provides rudimentary DOM manipulation functions to
  3776. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3777. * This service is the core service used by the ngAnimate $animator service which provides
  3778. * high-level animation hooks for CSS and JavaScript.
  3779. *
  3780. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3781. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3782. * manipulation operations.
  3783. *
  3784. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3785. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3786. * page}.
  3787. */
  3788. return {
  3789. /**
  3790. *
  3791. * @ngdoc method
  3792. * @name $animate#enter
  3793. * @kind function
  3794. * @description Inserts the element into the DOM either after the `after` element or within
  3795. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3796. * @param {DOMElement} element the element which will be inserted into the DOM
  3797. * @param {DOMElement} parent the parent element which will append the element as
  3798. * a child (if the after element is not present)
  3799. * @param {DOMElement} after the sibling element which will append the element
  3800. * after itself
  3801. * @param {Function=} done callback function that will be called after the element has been
  3802. * inserted into the DOM
  3803. */
  3804. enter : function(element, parent, after, done) {
  3805. if (after) {
  3806. after.after(element);
  3807. } else {
  3808. if (!parent || !parent[0]) {
  3809. parent = after.parent();
  3810. }
  3811. parent.append(element);
  3812. }
  3813. async(done);
  3814. },
  3815. /**
  3816. *
  3817. * @ngdoc method
  3818. * @name $animate#leave
  3819. * @kind function
  3820. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3821. * fired (if provided).
  3822. * @param {DOMElement} element the element which will be removed from the DOM
  3823. * @param {Function=} done callback function that will be called after the element has been
  3824. * removed from the DOM
  3825. */
  3826. leave : function(element, done) {
  3827. element.remove();
  3828. async(done);
  3829. },
  3830. /**
  3831. *
  3832. * @ngdoc method
  3833. * @name $animate#move
  3834. * @kind function
  3835. * @description Moves the position of the provided element within the DOM to be placed
  3836. * either after the `after` element or inside of the `parent` element. Once complete, the
  3837. * done() callback will be fired (if provided).
  3838. *
  3839. * @param {DOMElement} element the element which will be moved around within the
  3840. * DOM
  3841. * @param {DOMElement} parent the parent element where the element will be
  3842. * inserted into (if the after element is not present)
  3843. * @param {DOMElement} after the sibling element where the element will be
  3844. * positioned next to
  3845. * @param {Function=} done the callback function (if provided) that will be fired after the
  3846. * element has been moved to its new position
  3847. */
  3848. move : function(element, parent, after, done) {
  3849. // Do not remove element before insert. Removing will cause data associated with the
  3850. // element to be dropped. Insert will implicitly do the remove.
  3851. this.enter(element, parent, after, done);
  3852. },
  3853. /**
  3854. *
  3855. * @ngdoc method
  3856. * @name $animate#addClass
  3857. * @kind function
  3858. * @description Adds the provided className CSS class value to the provided element. Once
  3859. * complete, the done() callback will be fired (if provided).
  3860. * @param {DOMElement} element the element which will have the className value
  3861. * added to it
  3862. * @param {string} className the CSS class which will be added to the element
  3863. * @param {Function=} done the callback function (if provided) that will be fired after the
  3864. * className value has been added to the element
  3865. */
  3866. addClass : function(element, className, done) {
  3867. className = isString(className) ?
  3868. className :
  3869. isArray(className) ? className.join(' ') : '';
  3870. forEach(element, function (element) {
  3871. jqLiteAddClass(element, className);
  3872. });
  3873. async(done);
  3874. },
  3875. /**
  3876. *
  3877. * @ngdoc method
  3878. * @name $animate#removeClass
  3879. * @kind function
  3880. * @description Removes the provided className CSS class value from the provided element.
  3881. * Once complete, the done() callback will be fired (if provided).
  3882. * @param {DOMElement} element the element which will have the className value
  3883. * removed from it
  3884. * @param {string} className the CSS class which will be removed from the element
  3885. * @param {Function=} done the callback function (if provided) that will be fired after the
  3886. * className value has been removed from the element
  3887. */
  3888. removeClass : function(element, className, done) {
  3889. className = isString(className) ?
  3890. className :
  3891. isArray(className) ? className.join(' ') : '';
  3892. forEach(element, function (element) {
  3893. jqLiteRemoveClass(element, className);
  3894. });
  3895. async(done);
  3896. },
  3897. /**
  3898. *
  3899. * @ngdoc method
  3900. * @name $animate#setClass
  3901. * @kind function
  3902. * @description Adds and/or removes the given CSS classes to and from the element.
  3903. * Once complete, the done() callback will be fired (if provided).
  3904. * @param {DOMElement} element the element which will have its CSS classes changed
  3905. * removed from it
  3906. * @param {string} add the CSS classes which will be added to the element
  3907. * @param {string} remove the CSS class which will be removed from the element
  3908. * @param {Function=} done the callback function (if provided) that will be fired after the
  3909. * CSS classes have been set on the element
  3910. */
  3911. setClass : function(element, add, remove, done) {
  3912. forEach(element, function (element) {
  3913. jqLiteAddClass(element, add);
  3914. jqLiteRemoveClass(element, remove);
  3915. });
  3916. async(done);
  3917. },
  3918. enabled : noop
  3919. };
  3920. }];
  3921. }];
  3922. function $$AsyncCallbackProvider(){
  3923. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  3924. return $$rAF.supported
  3925. ? function(fn) { return $$rAF(fn); }
  3926. : function(fn) {
  3927. return $timeout(fn, 0, false);
  3928. };
  3929. }];
  3930. }
  3931. /* global stripHash: true */
  3932. /**
  3933. * ! This is a private undocumented service !
  3934. *
  3935. * @name $browser
  3936. * @requires $log
  3937. * @description
  3938. * This object has two goals:
  3939. *
  3940. * - hide all the global state in the browser caused by the window object
  3941. * - abstract away all the browser specific features and inconsistencies
  3942. *
  3943. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3944. * service, which can be used for convenient testing of the application without the interaction with
  3945. * the real browser apis.
  3946. */
  3947. /**
  3948. * @param {object} window The global window object.
  3949. * @param {object} document jQuery wrapped document.
  3950. * @param {function()} XHR XMLHttpRequest constructor.
  3951. * @param {object} $log console.log or an object with the same interface.
  3952. * @param {object} $sniffer $sniffer service
  3953. */
  3954. function Browser(window, document, $log, $sniffer) {
  3955. var self = this,
  3956. rawDocument = document[0],
  3957. location = window.location,
  3958. history = window.history,
  3959. setTimeout = window.setTimeout,
  3960. clearTimeout = window.clearTimeout,
  3961. pendingDeferIds = {};
  3962. self.isMock = false;
  3963. var outstandingRequestCount = 0;
  3964. var outstandingRequestCallbacks = [];
  3965. // TODO(vojta): remove this temporary api
  3966. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3967. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3968. /**
  3969. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3970. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3971. */
  3972. function completeOutstandingRequest(fn) {
  3973. try {
  3974. fn.apply(null, sliceArgs(arguments, 1));
  3975. } finally {
  3976. outstandingRequestCount--;
  3977. if (outstandingRequestCount === 0) {
  3978. while(outstandingRequestCallbacks.length) {
  3979. try {
  3980. outstandingRequestCallbacks.pop()();
  3981. } catch (e) {
  3982. $log.error(e);
  3983. }
  3984. }
  3985. }
  3986. }
  3987. }
  3988. /**
  3989. * @private
  3990. * Note: this method is used only by scenario runner
  3991. * TODO(vojta): prefix this method with $$ ?
  3992. * @param {function()} callback Function that will be called when no outstanding request
  3993. */
  3994. self.notifyWhenNoOutstandingRequests = function(callback) {
  3995. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3996. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3997. // regular poller would result in flaky tests.
  3998. forEach(pollFns, function(pollFn){ pollFn(); });
  3999. if (outstandingRequestCount === 0) {
  4000. callback();
  4001. } else {
  4002. outstandingRequestCallbacks.push(callback);
  4003. }
  4004. };
  4005. //////////////////////////////////////////////////////////////
  4006. // Poll Watcher API
  4007. //////////////////////////////////////////////////////////////
  4008. var pollFns = [],
  4009. pollTimeout;
  4010. /**
  4011. * @name $browser#addPollFn
  4012. *
  4013. * @param {function()} fn Poll function to add
  4014. *
  4015. * @description
  4016. * Adds a function to the list of functions that poller periodically executes,
  4017. * and starts polling if not started yet.
  4018. *
  4019. * @returns {function()} the added function
  4020. */
  4021. self.addPollFn = function(fn) {
  4022. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4023. pollFns.push(fn);
  4024. return fn;
  4025. };
  4026. /**
  4027. * @param {number} interval How often should browser call poll functions (ms)
  4028. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4029. *
  4030. * @description
  4031. * Configures the poller to run in the specified intervals, using the specified
  4032. * setTimeout fn and kicks it off.
  4033. */
  4034. function startPoller(interval, setTimeout) {
  4035. (function check() {
  4036. forEach(pollFns, function(pollFn){ pollFn(); });
  4037. pollTimeout = setTimeout(check, interval);
  4038. })();
  4039. }
  4040. //////////////////////////////////////////////////////////////
  4041. // URL API
  4042. //////////////////////////////////////////////////////////////
  4043. var lastBrowserUrl = location.href,
  4044. baseElement = document.find('base'),
  4045. reloadLocation = null;
  4046. /**
  4047. * @name $browser#url
  4048. *
  4049. * @description
  4050. * GETTER:
  4051. * Without any argument, this method just returns current value of location.href.
  4052. *
  4053. * SETTER:
  4054. * With at least one argument, this method sets url to new value.
  4055. * If html5 history api supported, pushState/replaceState is used, otherwise
  4056. * location.href/location.replace is used.
  4057. * Returns its own instance to allow chaining
  4058. *
  4059. * NOTE: this api is intended for use only by the $location service. Please use the
  4060. * {@link ng.$location $location service} to change url.
  4061. *
  4062. * @param {string} url New url (when used as setter)
  4063. * @param {boolean=} replace Should new url replace current history record ?
  4064. */
  4065. self.url = function(url, replace) {
  4066. // Android Browser BFCache causes location, history reference to become stale.
  4067. if (location !== window.location) location = window.location;
  4068. if (history !== window.history) history = window.history;
  4069. // setter
  4070. if (url) {
  4071. if (lastBrowserUrl == url) return;
  4072. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4073. lastBrowserUrl = url;
  4074. // Don't use history API if only the hash changed
  4075. // due to a bug in IE10/IE11 which leads
  4076. // to not firing a `hashchange` nor `popstate` event
  4077. // in some cases (see #9143).
  4078. if (!sameBase && $sniffer.history) {
  4079. if (replace) history.replaceState(null, '', url);
  4080. else {
  4081. history.pushState(null, '', url);
  4082. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  4083. baseElement.attr('href', baseElement.attr('href'));
  4084. }
  4085. } else {
  4086. if (!sameBase) {
  4087. reloadLocation = url;
  4088. }
  4089. if (replace) {
  4090. location.replace(url);
  4091. } else {
  4092. location.href = url;
  4093. }
  4094. }
  4095. return self;
  4096. // getter
  4097. } else {
  4098. // - reloadLocation is needed as browsers don't allow to read out
  4099. // the new location.href if a reload happened.
  4100. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4101. return reloadLocation || location.href.replace(/%27/g,"'");
  4102. }
  4103. };
  4104. var urlChangeListeners = [],
  4105. urlChangeInit = false;
  4106. function fireUrlChange() {
  4107. if (lastBrowserUrl == self.url()) return;
  4108. lastBrowserUrl = self.url();
  4109. forEach(urlChangeListeners, function(listener) {
  4110. listener(self.url());
  4111. });
  4112. }
  4113. /**
  4114. * @name $browser#onUrlChange
  4115. *
  4116. * @description
  4117. * Register callback function that will be called, when url changes.
  4118. *
  4119. * It's only called when the url is changed from outside of angular:
  4120. * - user types different url into address bar
  4121. * - user clicks on history (forward/back) button
  4122. * - user clicks on a link
  4123. *
  4124. * It's not called when url is changed by $browser.url() method
  4125. *
  4126. * The listener gets called with new url as parameter.
  4127. *
  4128. * NOTE: this api is intended for use only by the $location service. Please use the
  4129. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4130. *
  4131. * @param {function(string)} listener Listener function to be called when url changes.
  4132. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4133. */
  4134. self.onUrlChange = function(callback) {
  4135. // TODO(vojta): refactor to use node's syntax for events
  4136. if (!urlChangeInit) {
  4137. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4138. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4139. // changed by push/replaceState
  4140. // html5 history api - popstate event
  4141. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  4142. // hashchange event
  4143. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  4144. // polling
  4145. else self.addPollFn(fireUrlChange);
  4146. urlChangeInit = true;
  4147. }
  4148. urlChangeListeners.push(callback);
  4149. return callback;
  4150. };
  4151. /**
  4152. * Checks whether the url has changed outside of Angular.
  4153. * Needs to be exported to be able to check for changes that have been done in sync,
  4154. * as hashchange/popstate events fire in async.
  4155. */
  4156. self.$$checkUrlChange = fireUrlChange;
  4157. //////////////////////////////////////////////////////////////
  4158. // Misc API
  4159. //////////////////////////////////////////////////////////////
  4160. /**
  4161. * @name $browser#baseHref
  4162. *
  4163. * @description
  4164. * Returns current <base href>
  4165. * (always relative - without domain)
  4166. *
  4167. * @returns {string} The current base href
  4168. */
  4169. self.baseHref = function() {
  4170. var href = baseElement.attr('href');
  4171. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4172. };
  4173. //////////////////////////////////////////////////////////////
  4174. // Cookies API
  4175. //////////////////////////////////////////////////////////////
  4176. var lastCookies = {};
  4177. var lastCookieString = '';
  4178. var cookiePath = self.baseHref();
  4179. /**
  4180. * @name $browser#cookies
  4181. *
  4182. * @param {string=} name Cookie name
  4183. * @param {string=} value Cookie value
  4184. *
  4185. * @description
  4186. * The cookies method provides a 'private' low level access to browser cookies.
  4187. * It is not meant to be used directly, use the $cookie service instead.
  4188. *
  4189. * The return values vary depending on the arguments that the method was called with as follows:
  4190. *
  4191. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4192. * it
  4193. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4194. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4195. * way)
  4196. *
  4197. * @returns {Object} Hash of all cookies (if called without any parameter)
  4198. */
  4199. self.cookies = function(name, value) {
  4200. /* global escape: false, unescape: false */
  4201. var cookieLength, cookieArray, cookie, i, index;
  4202. if (name) {
  4203. if (value === undefined) {
  4204. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  4205. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4206. } else {
  4207. if (isString(value)) {
  4208. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  4209. ';path=' + cookiePath).length + 1;
  4210. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4211. // - 300 cookies
  4212. // - 20 cookies per unique domain
  4213. // - 4096 bytes per cookie
  4214. if (cookieLength > 4096) {
  4215. $log.warn("Cookie '"+ name +
  4216. "' possibly not set or overflowed because it was too large ("+
  4217. cookieLength + " > 4096 bytes)!");
  4218. }
  4219. }
  4220. }
  4221. } else {
  4222. if (rawDocument.cookie !== lastCookieString) {
  4223. lastCookieString = rawDocument.cookie;
  4224. cookieArray = lastCookieString.split("; ");
  4225. lastCookies = {};
  4226. for (i = 0; i < cookieArray.length; i++) {
  4227. cookie = cookieArray[i];
  4228. index = cookie.indexOf('=');
  4229. if (index > 0) { //ignore nameless cookies
  4230. name = unescape(cookie.substring(0, index));
  4231. // the first value that is seen for a cookie is the most
  4232. // specific one. values for the same cookie name that
  4233. // follow are for less specific paths.
  4234. if (lastCookies[name] === undefined) {
  4235. lastCookies[name] = unescape(cookie.substring(index + 1));
  4236. }
  4237. }
  4238. }
  4239. }
  4240. return lastCookies;
  4241. }
  4242. };
  4243. /**
  4244. * @name $browser#defer
  4245. * @param {function()} fn A function, who's execution should be deferred.
  4246. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4247. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4248. *
  4249. * @description
  4250. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4251. *
  4252. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4253. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4254. * via `$browser.defer.flush()`.
  4255. *
  4256. */
  4257. self.defer = function(fn, delay) {
  4258. var timeoutId;
  4259. outstandingRequestCount++;
  4260. timeoutId = setTimeout(function() {
  4261. delete pendingDeferIds[timeoutId];
  4262. completeOutstandingRequest(fn);
  4263. }, delay || 0);
  4264. pendingDeferIds[timeoutId] = true;
  4265. return timeoutId;
  4266. };
  4267. /**
  4268. * @name $browser#defer.cancel
  4269. *
  4270. * @description
  4271. * Cancels a deferred task identified with `deferId`.
  4272. *
  4273. * @param {*} deferId Token returned by the `$browser.defer` function.
  4274. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4275. * canceled.
  4276. */
  4277. self.defer.cancel = function(deferId) {
  4278. if (pendingDeferIds[deferId]) {
  4279. delete pendingDeferIds[deferId];
  4280. clearTimeout(deferId);
  4281. completeOutstandingRequest(noop);
  4282. return true;
  4283. }
  4284. return false;
  4285. };
  4286. }
  4287. function $BrowserProvider(){
  4288. this.$get = ['$window', '$log', '$sniffer', '$document',
  4289. function( $window, $log, $sniffer, $document){
  4290. return new Browser($window, $document, $log, $sniffer);
  4291. }];
  4292. }
  4293. /**
  4294. * @ngdoc service
  4295. * @name $cacheFactory
  4296. *
  4297. * @description
  4298. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4299. * them.
  4300. *
  4301. * ```js
  4302. *
  4303. * var cache = $cacheFactory('cacheId');
  4304. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4305. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4306. *
  4307. * cache.put("key", "value");
  4308. * cache.put("another key", "another value");
  4309. *
  4310. * // We've specified no options on creation
  4311. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4312. *
  4313. * ```
  4314. *
  4315. *
  4316. * @param {string} cacheId Name or id of the newly created cache.
  4317. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4318. *
  4319. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4320. *
  4321. * @returns {object} Newly created cache object with the following set of methods:
  4322. *
  4323. * - `{object}` `info()` — Returns id, size, and options of cache.
  4324. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4325. * it.
  4326. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4327. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4328. * - `{void}` `removeAll()` — Removes all cached values.
  4329. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4330. *
  4331. * @example
  4332. <example module="cacheExampleApp">
  4333. <file name="index.html">
  4334. <div ng-controller="CacheController">
  4335. <input ng-model="newCacheKey" placeholder="Key">
  4336. <input ng-model="newCacheValue" placeholder="Value">
  4337. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4338. <p ng-if="keys.length">Cached Values</p>
  4339. <div ng-repeat="key in keys">
  4340. <span ng-bind="key"></span>
  4341. <span>: </span>
  4342. <b ng-bind="cache.get(key)"></b>
  4343. </div>
  4344. <p>Cache Info</p>
  4345. <div ng-repeat="(key, value) in cache.info()">
  4346. <span ng-bind="key"></span>
  4347. <span>: </span>
  4348. <b ng-bind="value"></b>
  4349. </div>
  4350. </div>
  4351. </file>
  4352. <file name="script.js">
  4353. angular.module('cacheExampleApp', []).
  4354. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4355. $scope.keys = [];
  4356. $scope.cache = $cacheFactory('cacheId');
  4357. $scope.put = function(key, value) {
  4358. if ($scope.cache.get(key) === undefined) {
  4359. $scope.keys.push(key);
  4360. }
  4361. $scope.cache.put(key, value === undefined ? null : value);
  4362. };
  4363. }]);
  4364. </file>
  4365. <file name="style.css">
  4366. p {
  4367. margin: 10px 0 3px;
  4368. }
  4369. </file>
  4370. </example>
  4371. */
  4372. function $CacheFactoryProvider() {
  4373. this.$get = function() {
  4374. var caches = {};
  4375. function cacheFactory(cacheId, options) {
  4376. if (cacheId in caches) {
  4377. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4378. }
  4379. var size = 0,
  4380. stats = extend({}, options, {id: cacheId}),
  4381. data = {},
  4382. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4383. lruHash = {},
  4384. freshEnd = null,
  4385. staleEnd = null;
  4386. /**
  4387. * @ngdoc type
  4388. * @name $cacheFactory.Cache
  4389. *
  4390. * @description
  4391. * A cache object used to store and retrieve data, primarily used by
  4392. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4393. * templates and other data.
  4394. *
  4395. * ```js
  4396. * angular.module('superCache')
  4397. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4398. * return $cacheFactory('super-cache');
  4399. * }]);
  4400. * ```
  4401. *
  4402. * Example test:
  4403. *
  4404. * ```js
  4405. * it('should behave like a cache', inject(function(superCache) {
  4406. * superCache.put('key', 'value');
  4407. * superCache.put('another key', 'another value');
  4408. *
  4409. * expect(superCache.info()).toEqual({
  4410. * id: 'super-cache',
  4411. * size: 2
  4412. * });
  4413. *
  4414. * superCache.remove('another key');
  4415. * expect(superCache.get('another key')).toBeUndefined();
  4416. *
  4417. * superCache.removeAll();
  4418. * expect(superCache.info()).toEqual({
  4419. * id: 'super-cache',
  4420. * size: 0
  4421. * });
  4422. * }));
  4423. * ```
  4424. */
  4425. return caches[cacheId] = {
  4426. /**
  4427. * @ngdoc method
  4428. * @name $cacheFactory.Cache#put
  4429. * @kind function
  4430. *
  4431. * @description
  4432. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4433. * retrieved later, and incrementing the size of the cache if the key was not already
  4434. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4435. * entries from the set.
  4436. *
  4437. * It will not insert undefined values into the cache.
  4438. *
  4439. * @param {string} key the key under which the cached data is stored.
  4440. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4441. * will not be stored.
  4442. * @returns {*} the value stored.
  4443. */
  4444. put: function(key, value) {
  4445. if (capacity < Number.MAX_VALUE) {
  4446. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4447. refresh(lruEntry);
  4448. }
  4449. if (isUndefined(value)) return;
  4450. if (!(key in data)) size++;
  4451. data[key] = value;
  4452. if (size > capacity) {
  4453. this.remove(staleEnd.key);
  4454. }
  4455. return value;
  4456. },
  4457. /**
  4458. * @ngdoc method
  4459. * @name $cacheFactory.Cache#get
  4460. * @kind function
  4461. *
  4462. * @description
  4463. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4464. *
  4465. * @param {string} key the key of the data to be retrieved
  4466. * @returns {*} the value stored.
  4467. */
  4468. get: function(key) {
  4469. if (capacity < Number.MAX_VALUE) {
  4470. var lruEntry = lruHash[key];
  4471. if (!lruEntry) return;
  4472. refresh(lruEntry);
  4473. }
  4474. return data[key];
  4475. },
  4476. /**
  4477. * @ngdoc method
  4478. * @name $cacheFactory.Cache#remove
  4479. * @kind function
  4480. *
  4481. * @description
  4482. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4483. *
  4484. * @param {string} key the key of the entry to be removed
  4485. */
  4486. remove: function(key) {
  4487. if (capacity < Number.MAX_VALUE) {
  4488. var lruEntry = lruHash[key];
  4489. if (!lruEntry) return;
  4490. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4491. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4492. link(lruEntry.n,lruEntry.p);
  4493. delete lruHash[key];
  4494. }
  4495. delete data[key];
  4496. size--;
  4497. },
  4498. /**
  4499. * @ngdoc method
  4500. * @name $cacheFactory.Cache#removeAll
  4501. * @kind function
  4502. *
  4503. * @description
  4504. * Clears the cache object of any entries.
  4505. */
  4506. removeAll: function() {
  4507. data = {};
  4508. size = 0;
  4509. lruHash = {};
  4510. freshEnd = staleEnd = null;
  4511. },
  4512. /**
  4513. * @ngdoc method
  4514. * @name $cacheFactory.Cache#destroy
  4515. * @kind function
  4516. *
  4517. * @description
  4518. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4519. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4520. */
  4521. destroy: function() {
  4522. data = null;
  4523. stats = null;
  4524. lruHash = null;
  4525. delete caches[cacheId];
  4526. },
  4527. /**
  4528. * @ngdoc method
  4529. * @name $cacheFactory.Cache#info
  4530. * @kind function
  4531. *
  4532. * @description
  4533. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4534. *
  4535. * @returns {object} an object with the following properties:
  4536. * <ul>
  4537. * <li>**id**: the id of the cache instance</li>
  4538. * <li>**size**: the number of entries kept in the cache instance</li>
  4539. * <li>**...**: any additional properties from the options object when creating the
  4540. * cache.</li>
  4541. * </ul>
  4542. */
  4543. info: function() {
  4544. return extend({}, stats, {size: size});
  4545. }
  4546. };
  4547. /**
  4548. * makes the `entry` the freshEnd of the LRU linked list
  4549. */
  4550. function refresh(entry) {
  4551. if (entry != freshEnd) {
  4552. if (!staleEnd) {
  4553. staleEnd = entry;
  4554. } else if (staleEnd == entry) {
  4555. staleEnd = entry.n;
  4556. }
  4557. link(entry.n, entry.p);
  4558. link(entry, freshEnd);
  4559. freshEnd = entry;
  4560. freshEnd.n = null;
  4561. }
  4562. }
  4563. /**
  4564. * bidirectionally links two entries of the LRU linked list
  4565. */
  4566. function link(nextEntry, prevEntry) {
  4567. if (nextEntry != prevEntry) {
  4568. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4569. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4570. }
  4571. }
  4572. }
  4573. /**
  4574. * @ngdoc method
  4575. * @name $cacheFactory#info
  4576. *
  4577. * @description
  4578. * Get information about all the caches that have been created
  4579. *
  4580. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4581. */
  4582. cacheFactory.info = function() {
  4583. var info = {};
  4584. forEach(caches, function(cache, cacheId) {
  4585. info[cacheId] = cache.info();
  4586. });
  4587. return info;
  4588. };
  4589. /**
  4590. * @ngdoc method
  4591. * @name $cacheFactory#get
  4592. *
  4593. * @description
  4594. * Get access to a cache object by the `cacheId` used when it was created.
  4595. *
  4596. * @param {string} cacheId Name or id of a cache to access.
  4597. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4598. */
  4599. cacheFactory.get = function(cacheId) {
  4600. return caches[cacheId];
  4601. };
  4602. return cacheFactory;
  4603. };
  4604. }
  4605. /**
  4606. * @ngdoc service
  4607. * @name $templateCache
  4608. *
  4609. * @description
  4610. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4611. * can load templates directly into the cache in a `script` tag, or by consuming the
  4612. * `$templateCache` service directly.
  4613. *
  4614. * Adding via the `script` tag:
  4615. *
  4616. * ```html
  4617. * <script type="text/ng-template" id="templateId.html">
  4618. * <p>This is the content of the template</p>
  4619. * </script>
  4620. * ```
  4621. *
  4622. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4623. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  4624. * element with ng-app attribute), otherwise the template will be ignored.
  4625. *
  4626. * Adding via the $templateCache service:
  4627. *
  4628. * ```js
  4629. * var myApp = angular.module('myApp', []);
  4630. * myApp.run(function($templateCache) {
  4631. * $templateCache.put('templateId.html', 'This is the content of the template');
  4632. * });
  4633. * ```
  4634. *
  4635. * To retrieve the template later, simply use it in your HTML:
  4636. * ```html
  4637. * <div ng-include=" 'templateId.html' "></div>
  4638. * ```
  4639. *
  4640. * or get it via Javascript:
  4641. * ```js
  4642. * $templateCache.get('templateId.html')
  4643. * ```
  4644. *
  4645. * See {@link ng.$cacheFactory $cacheFactory}.
  4646. *
  4647. */
  4648. function $TemplateCacheProvider() {
  4649. this.$get = ['$cacheFactory', function($cacheFactory) {
  4650. return $cacheFactory('templates');
  4651. }];
  4652. }
  4653. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4654. *
  4655. * DOM-related variables:
  4656. *
  4657. * - "node" - DOM Node
  4658. * - "element" - DOM Element or Node
  4659. * - "$node" or "$element" - jqLite-wrapped node or element
  4660. *
  4661. *
  4662. * Compiler related stuff:
  4663. *
  4664. * - "linkFn" - linking fn of a single directive
  4665. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4666. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4667. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4668. */
  4669. /**
  4670. * @ngdoc service
  4671. * @name $compile
  4672. * @kind function
  4673. *
  4674. * @description
  4675. * Compiles an HTML string or DOM into a template and produces a template function, which
  4676. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4677. *
  4678. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4679. * {@link ng.$compileProvider#directive directives}.
  4680. *
  4681. * <div class="alert alert-warning">
  4682. * **Note:** This document is an in-depth reference of all directive options.
  4683. * For a gentle introduction to directives with examples of common use cases,
  4684. * see the {@link guide/directive directive guide}.
  4685. * </div>
  4686. *
  4687. * ## Comprehensive Directive API
  4688. *
  4689. * There are many different options for a directive.
  4690. *
  4691. * The difference resides in the return value of the factory function.
  4692. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4693. * or just the `postLink` function (all other properties will have the default values).
  4694. *
  4695. * <div class="alert alert-success">
  4696. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4697. * </div>
  4698. *
  4699. * Here's an example directive declared with a Directive Definition Object:
  4700. *
  4701. * ```js
  4702. * var myModule = angular.module(...);
  4703. *
  4704. * myModule.directive('directiveName', function factory(injectables) {
  4705. * var directiveDefinitionObject = {
  4706. * priority: 0,
  4707. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4708. * // or
  4709. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4710. * transclude: false,
  4711. * restrict: 'A',
  4712. * scope: false,
  4713. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4714. * controllerAs: 'stringAlias',
  4715. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4716. * compile: function compile(tElement, tAttrs, transclude) {
  4717. * return {
  4718. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4719. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4720. * }
  4721. * // or
  4722. * // return function postLink( ... ) { ... }
  4723. * },
  4724. * // or
  4725. * // link: {
  4726. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4727. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4728. * // }
  4729. * // or
  4730. * // link: function postLink( ... ) { ... }
  4731. * };
  4732. * return directiveDefinitionObject;
  4733. * });
  4734. * ```
  4735. *
  4736. * <div class="alert alert-warning">
  4737. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4738. * </div>
  4739. *
  4740. * Therefore the above can be simplified as:
  4741. *
  4742. * ```js
  4743. * var myModule = angular.module(...);
  4744. *
  4745. * myModule.directive('directiveName', function factory(injectables) {
  4746. * var directiveDefinitionObject = {
  4747. * link: function postLink(scope, iElement, iAttrs) { ... }
  4748. * };
  4749. * return directiveDefinitionObject;
  4750. * // or
  4751. * // return function postLink(scope, iElement, iAttrs) { ... }
  4752. * });
  4753. * ```
  4754. *
  4755. *
  4756. *
  4757. * ### Directive Definition Object
  4758. *
  4759. * The directive definition object provides instructions to the {@link ng.$compile
  4760. * compiler}. The attributes are:
  4761. *
  4762. * #### `priority`
  4763. * When there are multiple directives defined on a single DOM element, sometimes it
  4764. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4765. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4766. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4767. * are also run in priority order, but post-link functions are run in reverse order. The order
  4768. * of directives with the same priority is undefined. The default priority is `0`.
  4769. *
  4770. * #### `terminal`
  4771. * If set to true then the current `priority` will be the last set of directives
  4772. * which will execute (any directives at the current priority will still execute
  4773. * as the order of execution on same `priority` is undefined).
  4774. *
  4775. * #### `scope`
  4776. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4777. * same element request a new scope, only one new scope is created. The new scope rule does not
  4778. * apply for the root of the template since the root of the template always gets a new scope.
  4779. *
  4780. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4781. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4782. * when creating reusable components, which should not accidentally read or modify data in the
  4783. * parent scope.
  4784. *
  4785. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4786. * derived from the parent scope. These local properties are useful for aliasing values for
  4787. * templates. Locals definition is a hash of local scope property to its source:
  4788. *
  4789. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4790. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4791. * attribute name is assumed to be the same as the local name.
  4792. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4793. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4794. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4795. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4796. * component scope).
  4797. *
  4798. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4799. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4800. * name is specified then the attribute name is assumed to be the same as the local name.
  4801. * Given `<widget my-attr="parentModel">` and widget definition of
  4802. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4803. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4804. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4805. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4806. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4807. *
  4808. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4809. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4810. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4811. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4812. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4813. * pass data from the isolated scope via an expression to the parent scope, this can be
  4814. * done by passing a map of local variable names and values into the expression wrapper fn.
  4815. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4816. * by calling the `localFn` as `localFn({amount: 22})`.
  4817. *
  4818. *
  4819. *
  4820. * #### `controller`
  4821. * Controller constructor function. The controller is instantiated before the
  4822. * pre-linking phase and it is shared with other directives (see
  4823. * `require` attribute). This allows the directives to communicate with each other and augment
  4824. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4825. *
  4826. * * `$scope` - Current scope associated with the element
  4827. * * `$element` - Current element
  4828. * * `$attrs` - Current attributes object for the element
  4829. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4830. * The scope can be overridden by an optional first argument.
  4831. * `function([scope], cloneLinkingFn)`.
  4832. *
  4833. *
  4834. * #### `require`
  4835. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4836. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4837. * injected argument will be an array in corresponding order. If no such directive can be
  4838. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4839. *
  4840. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4841. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4842. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  4843. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  4844. * `null` to the `link` fn if not found.
  4845. *
  4846. *
  4847. * #### `controllerAs`
  4848. * Controller alias at the directive scope. An alias for the controller so it
  4849. * can be referenced at the directive template. The directive needs to define a scope for this
  4850. * configuration to be used. Useful in the case when directive is used as component.
  4851. *
  4852. *
  4853. * #### `restrict`
  4854. * String of subset of `EACM` which restricts the directive to a specific directive
  4855. * declaration style. If omitted, the default (attributes only) is used.
  4856. *
  4857. * * `E` - Element name: `<my-directive></my-directive>`
  4858. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4859. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4860. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4861. *
  4862. *
  4863. * #### `template`
  4864. * HTML markup that may:
  4865. * * Replace the contents of the directive's element (default).
  4866. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  4867. * * Wrap the contents of the directive's element (if `transclude` is true).
  4868. *
  4869. * Value may be:
  4870. *
  4871. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  4872. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  4873. * function api below) and returns a string value.
  4874. *
  4875. *
  4876. * #### `templateUrl`
  4877. * Same as `template` but the template is loaded from the specified URL. Because
  4878. * the template loading is asynchronous the compilation/linking is suspended until the template
  4879. * is loaded.
  4880. *
  4881. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4882. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4883. * a string value representing the url. In either case, the template URL is passed through {@link
  4884. * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4885. *
  4886. *
  4887. * #### `replace` ([*DEPRECATED*!], will be removed in next major release)
  4888. * specify what the template should replace. Defaults to `false`.
  4889. *
  4890. * * `true` - the template will replace the directive's element.
  4891. * * `false` - the template will replace the contents of the directive's element.
  4892. *
  4893. * The replacement process migrates all of the attributes / classes from the old element to the new
  4894. * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4895. * Directives Guide} for an example.
  4896. *
  4897. * #### `transclude`
  4898. * compile the content of the element and make it available to the directive.
  4899. * Typically used with {@link ng.directive:ngTransclude
  4900. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4901. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4902. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4903. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4904. * be bound to the parent (pre-`isolate`) scope.
  4905. *
  4906. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  4907. * directive's element or the entire element:
  4908. *
  4909. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  4910. * * `'element'` - transclude the whole of the directive's element including any directives on this
  4911. * element that defined at a lower priority than this directive. When used, the `template`
  4912. * property is ignored.
  4913. *
  4914. * <div class="alert alert-warning">
  4915. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  4916. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  4917. * Testing Transclusion Directives}.
  4918. * </div>
  4919. *
  4920. * #### `compile`
  4921. *
  4922. * ```js
  4923. * function compile(tElement, tAttrs, transclude) { ... }
  4924. * ```
  4925. *
  4926. * The compile function deals with transforming the template DOM. Since most directives do not do
  4927. * template transformation, it is not used often. The compile function takes the following arguments:
  4928. *
  4929. * * `tElement` - template element - The element where the directive has been declared. It is
  4930. * safe to do template transformation on the element and child elements only.
  4931. *
  4932. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4933. * between all directive compile functions.
  4934. *
  4935. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4936. *
  4937. * <div class="alert alert-warning">
  4938. * **Note:** The template instance and the link instance may be different objects if the template has
  4939. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4940. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4941. * should be done in a linking function rather than in a compile function.
  4942. * </div>
  4943. * <div class="alert alert-warning">
  4944. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  4945. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  4946. * stack overflow errors.
  4947. *
  4948. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  4949. * a directive's template instead of relying on automatic template compilation via `template` or
  4950. * `templateUrl` declaration or manual compilation inside the compile function.
  4951. * </div>
  4952. *
  4953. * <div class="alert alert-error">
  4954. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4955. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4956. * to the link function instead.
  4957. * </div>
  4958. * A compile function can have a return value which can be either a function or an object.
  4959. *
  4960. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4961. * `link` property of the config object when the compile function is empty.
  4962. *
  4963. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4964. * control when a linking function should be called during the linking phase. See info about
  4965. * pre-linking and post-linking functions below.
  4966. *
  4967. *
  4968. * #### `link`
  4969. * This property is used only if the `compile` property is not defined.
  4970. *
  4971. * ```js
  4972. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4973. * ```
  4974. *
  4975. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4976. * executed after the template has been cloned. This is where most of the directive logic will be
  4977. * put.
  4978. *
  4979. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  4980. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  4981. *
  4982. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4983. * manipulate the children of the element only in `postLink` function since the children have
  4984. * already been linked.
  4985. *
  4986. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4987. * between all directive linking functions.
  4988. *
  4989. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4990. * element defines a controller. The controller is shared among all the directives, which allows
  4991. * the directives to use the controllers as a communication channel.
  4992. *
  4993. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4994. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4995. * parameter of directive controllers.
  4996. * `function([scope], cloneLinkingFn)`.
  4997. *
  4998. *
  4999. * #### Pre-linking function
  5000. *
  5001. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5002. * compiler linking function will fail to locate the correct elements for linking.
  5003. *
  5004. * #### Post-linking function
  5005. *
  5006. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  5007. *
  5008. * <a name="Attributes"></a>
  5009. * ### Attributes
  5010. *
  5011. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5012. * `link()` or `compile()` functions. It has a variety of uses.
  5013. *
  5014. * accessing *Normalized attribute names:*
  5015. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5016. * the attributes object allows for normalized access to
  5017. * the attributes.
  5018. *
  5019. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5020. * object which allows the directives to use the attributes object as inter directive
  5021. * communication.
  5022. *
  5023. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5024. * allowing other directives to read the interpolated value.
  5025. *
  5026. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5027. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5028. * the only way to easily get the actual value because during the linking phase the interpolation
  5029. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5030. *
  5031. * ```js
  5032. * function linkingFn(scope, elm, attrs, ctrl) {
  5033. * // get the attribute value
  5034. * console.log(attrs.ngModel);
  5035. *
  5036. * // change the attribute
  5037. * attrs.$set('ngModel', 'new value');
  5038. *
  5039. * // observe changes to interpolated attribute
  5040. * attrs.$observe('ngModel', function(value) {
  5041. * console.log('ngModel has changed value to ' + value);
  5042. * });
  5043. * }
  5044. * ```
  5045. *
  5046. * ## Example
  5047. *
  5048. * <div class="alert alert-warning">
  5049. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5050. * to illustrate how `$compile` works.
  5051. * </div>
  5052. *
  5053. <example module="compileExample">
  5054. <file name="index.html">
  5055. <script>
  5056. angular.module('compileExample', [], function($compileProvider) {
  5057. // configure new 'compile' directive by passing a directive
  5058. // factory function. The factory function injects the '$compile'
  5059. $compileProvider.directive('compile', function($compile) {
  5060. // directive factory creates a link function
  5061. return function(scope, element, attrs) {
  5062. scope.$watch(
  5063. function(scope) {
  5064. // watch the 'compile' expression for changes
  5065. return scope.$eval(attrs.compile);
  5066. },
  5067. function(value) {
  5068. // when the 'compile' expression changes
  5069. // assign it into the current DOM
  5070. element.html(value);
  5071. // compile the new DOM and link it to the current
  5072. // scope.
  5073. // NOTE: we only compile .childNodes so that
  5074. // we don't get into infinite loop compiling ourselves
  5075. $compile(element.contents())(scope);
  5076. }
  5077. );
  5078. };
  5079. });
  5080. })
  5081. .controller('GreeterController', ['$scope', function($scope) {
  5082. $scope.name = 'Angular';
  5083. $scope.html = 'Hello {{name}}';
  5084. }]);
  5085. </script>
  5086. <div ng-controller="GreeterController">
  5087. <input ng-model="name"> <br>
  5088. <textarea ng-model="html"></textarea> <br>
  5089. <div compile="html"></div>
  5090. </div>
  5091. </file>
  5092. <file name="protractor.js" type="protractor">
  5093. it('should auto compile', function() {
  5094. var textarea = $('textarea');
  5095. var output = $('div[compile]');
  5096. // The initial state reads 'Hello Angular'.
  5097. expect(output.getText()).toBe('Hello Angular');
  5098. textarea.clear();
  5099. textarea.sendKeys('{{name}}!');
  5100. expect(output.getText()).toBe('Angular!');
  5101. });
  5102. </file>
  5103. </example>
  5104. *
  5105. *
  5106. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5107. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  5108. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5109. * root element(s), not their children)
  5110. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  5111. * (a DOM element/tree) to a scope. Where:
  5112. *
  5113. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5114. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5115. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5116. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5117. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5118. *
  5119. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5120. * * `scope` - is the current scope with which the linking function is working with.
  5121. *
  5122. * Calling the linking function returns the element of the template. It is either the original
  5123. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5124. *
  5125. * After linking the view is not updated until after a call to $digest which typically is done by
  5126. * Angular automatically.
  5127. *
  5128. * If you need access to the bound view, there are two ways to do it:
  5129. *
  5130. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5131. * before you send them to the compiler and keep this reference around.
  5132. * ```js
  5133. * var element = $compile('<p>{{total}}</p>')(scope);
  5134. * ```
  5135. *
  5136. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5137. * example would not point to the clone, but rather to the original template that was cloned. In
  5138. * this case, you can access the clone via the cloneAttachFn:
  5139. * ```js
  5140. * var templateElement = angular.element('<p>{{total}}</p>'),
  5141. * scope = ....;
  5142. *
  5143. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5144. * //attach the clone to DOM document at the right place
  5145. * });
  5146. *
  5147. * //now we have reference to the cloned DOM via `clonedElement`
  5148. * ```
  5149. *
  5150. *
  5151. * For information on how the compiler works, see the
  5152. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5153. */
  5154. var $compileMinErr = minErr('$compile');
  5155. /**
  5156. * @ngdoc provider
  5157. * @name $compileProvider
  5158. * @kind function
  5159. *
  5160. * @description
  5161. */
  5162. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5163. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5164. var hasDirectives = {},
  5165. Suffix = 'Directive',
  5166. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
  5167. CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/;
  5168. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5169. // The assumption is that future DOM event attribute names will begin with
  5170. // 'on' and be composed of only English letters.
  5171. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5172. /**
  5173. * @ngdoc method
  5174. * @name $compileProvider#directive
  5175. * @kind function
  5176. *
  5177. * @description
  5178. * Register a new directive with the compiler.
  5179. *
  5180. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5181. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5182. * names and the values are the factories.
  5183. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5184. * {@link guide/directive} for more info.
  5185. * @returns {ng.$compileProvider} Self for chaining.
  5186. */
  5187. this.directive = function registerDirective(name, directiveFactory) {
  5188. assertNotHasOwnProperty(name, 'directive');
  5189. if (isString(name)) {
  5190. assertArg(directiveFactory, 'directiveFactory');
  5191. if (!hasDirectives.hasOwnProperty(name)) {
  5192. hasDirectives[name] = [];
  5193. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5194. function($injector, $exceptionHandler) {
  5195. var directives = [];
  5196. forEach(hasDirectives[name], function(directiveFactory, index) {
  5197. try {
  5198. var directive = $injector.invoke(directiveFactory);
  5199. if (isFunction(directive)) {
  5200. directive = { compile: valueFn(directive) };
  5201. } else if (!directive.compile && directive.link) {
  5202. directive.compile = valueFn(directive.link);
  5203. }
  5204. directive.priority = directive.priority || 0;
  5205. directive.index = index;
  5206. directive.name = directive.name || name;
  5207. directive.require = directive.require || (directive.controller && directive.name);
  5208. directive.restrict = directive.restrict || 'A';
  5209. directives.push(directive);
  5210. } catch (e) {
  5211. $exceptionHandler(e);
  5212. }
  5213. });
  5214. return directives;
  5215. }]);
  5216. }
  5217. hasDirectives[name].push(directiveFactory);
  5218. } else {
  5219. forEach(name, reverseParams(registerDirective));
  5220. }
  5221. return this;
  5222. };
  5223. /**
  5224. * @ngdoc method
  5225. * @name $compileProvider#aHrefSanitizationWhitelist
  5226. * @kind function
  5227. *
  5228. * @description
  5229. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5230. * urls during a[href] sanitization.
  5231. *
  5232. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5233. *
  5234. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5235. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5236. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5237. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5238. *
  5239. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5240. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5241. * chaining otherwise.
  5242. */
  5243. this.aHrefSanitizationWhitelist = function(regexp) {
  5244. if (isDefined(regexp)) {
  5245. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5246. return this;
  5247. } else {
  5248. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5249. }
  5250. };
  5251. /**
  5252. * @ngdoc method
  5253. * @name $compileProvider#imgSrcSanitizationWhitelist
  5254. * @kind function
  5255. *
  5256. * @description
  5257. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5258. * urls during img[src] sanitization.
  5259. *
  5260. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5261. *
  5262. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5263. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5264. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5265. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5266. *
  5267. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5268. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5269. * chaining otherwise.
  5270. */
  5271. this.imgSrcSanitizationWhitelist = function(regexp) {
  5272. if (isDefined(regexp)) {
  5273. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5274. return this;
  5275. } else {
  5276. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5277. }
  5278. };
  5279. this.$get = [
  5280. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  5281. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5282. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  5283. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5284. var Attributes = function(element, attr) {
  5285. this.$$element = element;
  5286. this.$attr = attr || {};
  5287. };
  5288. Attributes.prototype = {
  5289. /**
  5290. * @ngdoc method
  5291. * @name $compile.directive.Attributes#$normalize
  5292. * @kind function
  5293. *
  5294. * @description
  5295. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  5296. * `data-`) to its normalized, camelCase form.
  5297. *
  5298. * Also there is special case for Moz prefix starting with upper case letter.
  5299. *
  5300. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  5301. *
  5302. * @param {string} name Name to normalize
  5303. */
  5304. $normalize: directiveNormalize,
  5305. /**
  5306. * @ngdoc method
  5307. * @name $compile.directive.Attributes#$addClass
  5308. * @kind function
  5309. *
  5310. * @description
  5311. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5312. * are enabled then an animation will be triggered for the class addition.
  5313. *
  5314. * @param {string} classVal The className value that will be added to the element
  5315. */
  5316. $addClass : function(classVal) {
  5317. if(classVal && classVal.length > 0) {
  5318. $animate.addClass(this.$$element, classVal);
  5319. }
  5320. },
  5321. /**
  5322. * @ngdoc method
  5323. * @name $compile.directive.Attributes#$removeClass
  5324. * @kind function
  5325. *
  5326. * @description
  5327. * Removes the CSS class value specified by the classVal parameter from the element. If
  5328. * animations are enabled then an animation will be triggered for the class removal.
  5329. *
  5330. * @param {string} classVal The className value that will be removed from the element
  5331. */
  5332. $removeClass : function(classVal) {
  5333. if(classVal && classVal.length > 0) {
  5334. $animate.removeClass(this.$$element, classVal);
  5335. }
  5336. },
  5337. /**
  5338. * @ngdoc method
  5339. * @name $compile.directive.Attributes#$updateClass
  5340. * @kind function
  5341. *
  5342. * @description
  5343. * Adds and removes the appropriate CSS class values to the element based on the difference
  5344. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5345. *
  5346. * @param {string} newClasses The current CSS className value
  5347. * @param {string} oldClasses The former CSS className value
  5348. */
  5349. $updateClass : function(newClasses, oldClasses) {
  5350. var toAdd = tokenDifference(newClasses, oldClasses);
  5351. var toRemove = tokenDifference(oldClasses, newClasses);
  5352. if(toAdd.length === 0) {
  5353. $animate.removeClass(this.$$element, toRemove);
  5354. } else if(toRemove.length === 0) {
  5355. $animate.addClass(this.$$element, toAdd);
  5356. } else {
  5357. $animate.setClass(this.$$element, toAdd, toRemove);
  5358. }
  5359. },
  5360. /**
  5361. * Set a normalized attribute on the element in a way such that all directives
  5362. * can share the attribute. This function properly handles boolean attributes.
  5363. * @param {string} key Normalized key. (ie ngAttribute)
  5364. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5365. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5366. * Defaults to true.
  5367. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5368. */
  5369. $set: function(key, value, writeAttr, attrName) {
  5370. // TODO: decide whether or not to throw an error if "class"
  5371. //is set through this function since it may cause $updateClass to
  5372. //become unstable.
  5373. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5374. normalizedVal,
  5375. nodeName;
  5376. if (booleanKey) {
  5377. this.$$element.prop(key, value);
  5378. attrName = booleanKey;
  5379. }
  5380. this[key] = value;
  5381. // translate normalized key to actual key
  5382. if (attrName) {
  5383. this.$attr[key] = attrName;
  5384. } else {
  5385. attrName = this.$attr[key];
  5386. if (!attrName) {
  5387. this.$attr[key] = attrName = snake_case(key, '-');
  5388. }
  5389. }
  5390. nodeName = nodeName_(this.$$element);
  5391. // sanitize a[href] and img[src] values
  5392. if ((nodeName === 'A' && key === 'href') ||
  5393. (nodeName === 'IMG' && key === 'src')) {
  5394. this[key] = value = $$sanitizeUri(value, key === 'src');
  5395. }
  5396. if (writeAttr !== false) {
  5397. if (value === null || value === undefined) {
  5398. this.$$element.removeAttr(attrName);
  5399. } else {
  5400. this.$$element.attr(attrName, value);
  5401. }
  5402. }
  5403. // fire observers
  5404. var $$observers = this.$$observers;
  5405. $$observers && forEach($$observers[key], function(fn) {
  5406. try {
  5407. fn(value);
  5408. } catch (e) {
  5409. $exceptionHandler(e);
  5410. }
  5411. });
  5412. },
  5413. /**
  5414. * @ngdoc method
  5415. * @name $compile.directive.Attributes#$observe
  5416. * @kind function
  5417. *
  5418. * @description
  5419. * Observes an interpolated attribute.
  5420. *
  5421. * The observer function will be invoked once during the next `$digest` following
  5422. * compilation. The observer is then invoked whenever the interpolated value
  5423. * changes.
  5424. *
  5425. * @param {string} key Normalized key. (ie ngAttribute) .
  5426. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5427. the interpolated value of the attribute changes.
  5428. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5429. * @returns {function()} the `fn` parameter.
  5430. */
  5431. $observe: function(key, fn) {
  5432. var attrs = this,
  5433. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5434. listeners = ($$observers[key] || ($$observers[key] = []));
  5435. listeners.push(fn);
  5436. $rootScope.$evalAsync(function() {
  5437. if (!listeners.$$inter) {
  5438. // no one registered attribute interpolation function, so lets call it manually
  5439. fn(attrs[key]);
  5440. }
  5441. });
  5442. return fn;
  5443. }
  5444. };
  5445. var startSymbol = $interpolate.startSymbol(),
  5446. endSymbol = $interpolate.endSymbol(),
  5447. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5448. ? identity
  5449. : function denormalizeTemplate(template) {
  5450. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5451. },
  5452. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5453. return compile;
  5454. //================================
  5455. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5456. previousCompileContext) {
  5457. if (!($compileNodes instanceof jqLite)) {
  5458. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5459. // modify it.
  5460. $compileNodes = jqLite($compileNodes);
  5461. }
  5462. // We can not compile top level text elements since text nodes can be merged and we will
  5463. // not be able to attach scope data to them, so we will wrap them in <span>
  5464. forEach($compileNodes, function(node, index){
  5465. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5466. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5467. }
  5468. });
  5469. var compositeLinkFn =
  5470. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5471. maxPriority, ignoreDirective, previousCompileContext);
  5472. safeAddClass($compileNodes, 'ng-scope');
  5473. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){
  5474. assertArg(scope, 'scope');
  5475. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5476. // and sometimes changes the structure of the DOM.
  5477. var $linkNode = cloneConnectFn
  5478. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5479. : $compileNodes;
  5480. forEach(transcludeControllers, function(instance, name) {
  5481. $linkNode.data('$' + name + 'Controller', instance);
  5482. });
  5483. // Attach scope only to non-text nodes.
  5484. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5485. var node = $linkNode[i],
  5486. nodeType = node.nodeType;
  5487. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5488. $linkNode.eq(i).data('$scope', scope);
  5489. }
  5490. }
  5491. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5492. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  5493. return $linkNode;
  5494. };
  5495. }
  5496. function safeAddClass($element, className) {
  5497. try {
  5498. $element.addClass(className);
  5499. } catch(e) {
  5500. // ignore, since it means that we are trying to set class on
  5501. // SVG element, where class name is read-only.
  5502. }
  5503. }
  5504. /**
  5505. * Compile function matches each node in nodeList against the directives. Once all directives
  5506. * for a particular node are collected their compile functions are executed. The compile
  5507. * functions return values - the linking functions - are combined into a composite linking
  5508. * function, which is the a linking function for the node.
  5509. *
  5510. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5511. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5512. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5513. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5514. * the rootElement must be set the jqLite collection of the compile root. This is
  5515. * needed so that the jqLite collection items can be replaced with widgets.
  5516. * @param {number=} maxPriority Max directive priority.
  5517. * @returns {Function} A composite linking function of all of the matched directives or null.
  5518. */
  5519. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5520. previousCompileContext) {
  5521. var linkFns = [],
  5522. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5523. for (var i = 0; i < nodeList.length; i++) {
  5524. attrs = new Attributes();
  5525. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5526. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5527. ignoreDirective);
  5528. nodeLinkFn = (directives.length)
  5529. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5530. null, [], [], previousCompileContext)
  5531. : null;
  5532. if (nodeLinkFn && nodeLinkFn.scope) {
  5533. safeAddClass(attrs.$$element, 'ng-scope');
  5534. }
  5535. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5536. !(childNodes = nodeList[i].childNodes) ||
  5537. !childNodes.length)
  5538. ? null
  5539. : compileNodes(childNodes,
  5540. nodeLinkFn ? (
  5541. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  5542. && nodeLinkFn.transclude) : transcludeFn);
  5543. linkFns.push(nodeLinkFn, childLinkFn);
  5544. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5545. //use the previous context only for the first element in the virtual group
  5546. previousCompileContext = null;
  5547. }
  5548. // return a linking function if we have found anything, null otherwise
  5549. return linkFnFound ? compositeLinkFn : null;
  5550. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  5551. var nodeLinkFn, childLinkFn, node, childScope, i, ii, n, childBoundTranscludeFn;
  5552. // copy nodeList so that linking doesn't break due to live list updates.
  5553. var nodeListLength = nodeList.length,
  5554. stableNodeList = new Array(nodeListLength);
  5555. for (i = 0; i < nodeListLength; i++) {
  5556. stableNodeList[i] = nodeList[i];
  5557. }
  5558. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5559. node = stableNodeList[n];
  5560. nodeLinkFn = linkFns[i++];
  5561. childLinkFn = linkFns[i++];
  5562. if (nodeLinkFn) {
  5563. if (nodeLinkFn.scope) {
  5564. childScope = scope.$new();
  5565. jqLite.data(node, '$scope', childScope);
  5566. } else {
  5567. childScope = scope;
  5568. }
  5569. if ( nodeLinkFn.transcludeOnThisElement ) {
  5570. childBoundTranscludeFn = createBoundTranscludeFn(scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  5571. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  5572. childBoundTranscludeFn = parentBoundTranscludeFn;
  5573. } else if (!parentBoundTranscludeFn && transcludeFn) {
  5574. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  5575. } else {
  5576. childBoundTranscludeFn = null;
  5577. }
  5578. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  5579. } else if (childLinkFn) {
  5580. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  5581. }
  5582. }
  5583. }
  5584. }
  5585. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  5586. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers) {
  5587. var scopeCreated = false;
  5588. if (!transcludedScope) {
  5589. transcludedScope = scope.$new();
  5590. transcludedScope.$$transcluded = true;
  5591. scopeCreated = true;
  5592. }
  5593. var clone = transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn);
  5594. if (scopeCreated) {
  5595. clone.on('$destroy', function() { transcludedScope.$destroy(); });
  5596. }
  5597. return clone;
  5598. };
  5599. return boundTranscludeFn;
  5600. }
  5601. /**
  5602. * Looks for directives on the given node and adds them to the directive collection which is
  5603. * sorted.
  5604. *
  5605. * @param node Node to search.
  5606. * @param directives An array to which the directives are added to. This array is sorted before
  5607. * the function returns.
  5608. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5609. * @param {number=} maxPriority Max directive priority.
  5610. */
  5611. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5612. var nodeType = node.nodeType,
  5613. attrsMap = attrs.$attr,
  5614. match,
  5615. className;
  5616. switch(nodeType) {
  5617. case 1: /* Element */
  5618. // use the node name: <directive>
  5619. addDirective(directives,
  5620. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5621. // iterate over the attributes
  5622. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  5623. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5624. var attrStartName = false;
  5625. var attrEndName = false;
  5626. attr = nAttrs[j];
  5627. if (!msie || msie >= 8 || attr.specified) {
  5628. name = attr.name;
  5629. value = trim(attr.value);
  5630. // support ngAttr attribute binding
  5631. ngAttrName = directiveNormalize(name);
  5632. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  5633. name = snake_case(ngAttrName.substr(6), '-');
  5634. }
  5635. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5636. if (ngAttrName === directiveNName + 'Start') {
  5637. attrStartName = name;
  5638. attrEndName = name.substr(0, name.length - 5) + 'end';
  5639. name = name.substr(0, name.length - 6);
  5640. }
  5641. nName = directiveNormalize(name.toLowerCase());
  5642. attrsMap[nName] = name;
  5643. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  5644. attrs[nName] = value;
  5645. if (getBooleanAttrName(node, nName)) {
  5646. attrs[nName] = true; // presence means true
  5647. }
  5648. }
  5649. addAttrInterpolateDirective(node, directives, value, nName);
  5650. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5651. attrEndName);
  5652. }
  5653. }
  5654. // use class as directive
  5655. className = node.className;
  5656. if (isString(className) && className !== '') {
  5657. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5658. nName = directiveNormalize(match[2]);
  5659. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5660. attrs[nName] = trim(match[3]);
  5661. }
  5662. className = className.substr(match.index + match[0].length);
  5663. }
  5664. }
  5665. break;
  5666. case 3: /* Text Node */
  5667. addTextInterpolateDirective(directives, node.nodeValue);
  5668. break;
  5669. case 8: /* Comment */
  5670. try {
  5671. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5672. if (match) {
  5673. nName = directiveNormalize(match[1]);
  5674. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5675. attrs[nName] = trim(match[2]);
  5676. }
  5677. }
  5678. } catch (e) {
  5679. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5680. // comment's node value.
  5681. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5682. }
  5683. break;
  5684. }
  5685. directives.sort(byPriority);
  5686. return directives;
  5687. }
  5688. /**
  5689. * Given a node with an directive-start it collects all of the siblings until it finds
  5690. * directive-end.
  5691. * @param node
  5692. * @param attrStart
  5693. * @param attrEnd
  5694. * @returns {*}
  5695. */
  5696. function groupScan(node, attrStart, attrEnd) {
  5697. var nodes = [];
  5698. var depth = 0;
  5699. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5700. var startNode = node;
  5701. do {
  5702. if (!node) {
  5703. throw $compileMinErr('uterdir',
  5704. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5705. attrStart, attrEnd);
  5706. }
  5707. if (node.nodeType == 1 /** Element **/) {
  5708. if (node.hasAttribute(attrStart)) depth++;
  5709. if (node.hasAttribute(attrEnd)) depth--;
  5710. }
  5711. nodes.push(node);
  5712. node = node.nextSibling;
  5713. } while (depth > 0);
  5714. } else {
  5715. nodes.push(node);
  5716. }
  5717. return jqLite(nodes);
  5718. }
  5719. /**
  5720. * Wrapper for linking function which converts normal linking function into a grouped
  5721. * linking function.
  5722. * @param linkFn
  5723. * @param attrStart
  5724. * @param attrEnd
  5725. * @returns {Function}
  5726. */
  5727. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5728. return function(scope, element, attrs, controllers, transcludeFn) {
  5729. element = groupScan(element[0], attrStart, attrEnd);
  5730. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5731. };
  5732. }
  5733. /**
  5734. * Once the directives have been collected, their compile functions are executed. This method
  5735. * is responsible for inlining directive templates as well as terminating the application
  5736. * of the directives if the terminal directive has been reached.
  5737. *
  5738. * @param {Array} directives Array of collected directives to execute their compile function.
  5739. * this needs to be pre-sorted by priority order.
  5740. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5741. * @param {Object} templateAttrs The shared attribute function
  5742. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5743. * scope argument is auto-generated to the new
  5744. * child of the transcluded parent scope.
  5745. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5746. * argument has the root jqLite array so that we can replace nodes
  5747. * on it.
  5748. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5749. * compiling the transclusion.
  5750. * @param {Array.<Function>} preLinkFns
  5751. * @param {Array.<Function>} postLinkFns
  5752. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5753. * node
  5754. * @returns {Function} linkFn
  5755. */
  5756. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5757. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5758. previousCompileContext) {
  5759. previousCompileContext = previousCompileContext || {};
  5760. var terminalPriority = -Number.MAX_VALUE,
  5761. newScopeDirective,
  5762. controllerDirectives = previousCompileContext.controllerDirectives,
  5763. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5764. templateDirective = previousCompileContext.templateDirective,
  5765. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5766. hasTranscludeDirective = false,
  5767. hasTemplate = false,
  5768. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5769. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5770. directive,
  5771. directiveName,
  5772. $template,
  5773. replaceDirective = originalReplaceDirective,
  5774. childTranscludeFn = transcludeFn,
  5775. linkFn,
  5776. directiveValue;
  5777. // executes all directives on the current element
  5778. for(var i = 0, ii = directives.length; i < ii; i++) {
  5779. directive = directives[i];
  5780. var attrStart = directive.$$start;
  5781. var attrEnd = directive.$$end;
  5782. // collect multiblock sections
  5783. if (attrStart) {
  5784. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5785. }
  5786. $template = undefined;
  5787. if (terminalPriority > directive.priority) {
  5788. break; // prevent further processing of directives
  5789. }
  5790. if (directiveValue = directive.scope) {
  5791. newScopeDirective = newScopeDirective || directive;
  5792. // skip the check for directives with async templates, we'll check the derived sync
  5793. // directive when the template arrives
  5794. if (!directive.templateUrl) {
  5795. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5796. $compileNode);
  5797. if (isObject(directiveValue)) {
  5798. newIsolateScopeDirective = directive;
  5799. }
  5800. }
  5801. }
  5802. directiveName = directive.name;
  5803. if (!directive.templateUrl && directive.controller) {
  5804. directiveValue = directive.controller;
  5805. controllerDirectives = controllerDirectives || {};
  5806. assertNoDuplicate("'" + directiveName + "' controller",
  5807. controllerDirectives[directiveName], directive, $compileNode);
  5808. controllerDirectives[directiveName] = directive;
  5809. }
  5810. if (directiveValue = directive.transclude) {
  5811. hasTranscludeDirective = true;
  5812. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5813. // This option should only be used by directives that know how to safely handle element transclusion,
  5814. // where the transcluded nodes are added or replaced after linking.
  5815. if (!directive.$$tlb) {
  5816. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5817. nonTlbTranscludeDirective = directive;
  5818. }
  5819. if (directiveValue == 'element') {
  5820. hasElementTranscludeDirective = true;
  5821. terminalPriority = directive.priority;
  5822. $template = $compileNode;
  5823. $compileNode = templateAttrs.$$element =
  5824. jqLite(document.createComment(' ' + directiveName + ': ' +
  5825. templateAttrs[directiveName] + ' '));
  5826. compileNode = $compileNode[0];
  5827. replaceWith(jqCollection, sliceArgs($template), compileNode);
  5828. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5829. replaceDirective && replaceDirective.name, {
  5830. // Don't pass in:
  5831. // - controllerDirectives - otherwise we'll create duplicates controllers
  5832. // - newIsolateScopeDirective or templateDirective - combining templates with
  5833. // element transclusion doesn't make sense.
  5834. //
  5835. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5836. // on the same element more than once.
  5837. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5838. });
  5839. } else {
  5840. $template = jqLite(jqLiteClone(compileNode)).contents();
  5841. $compileNode.empty(); // clear contents
  5842. childTranscludeFn = compile($template, transcludeFn);
  5843. }
  5844. }
  5845. if (directive.template) {
  5846. hasTemplate = true;
  5847. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5848. templateDirective = directive;
  5849. directiveValue = (isFunction(directive.template))
  5850. ? directive.template($compileNode, templateAttrs)
  5851. : directive.template;
  5852. directiveValue = denormalizeTemplate(directiveValue);
  5853. if (directive.replace) {
  5854. replaceDirective = directive;
  5855. if (jqLiteIsTextNode(directiveValue)) {
  5856. $template = [];
  5857. } else {
  5858. $template = jqLite(trim(directiveValue));
  5859. }
  5860. compileNode = $template[0];
  5861. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5862. throw $compileMinErr('tplrt',
  5863. "Template for directive '{0}' must have exactly one root element. {1}",
  5864. directiveName, '');
  5865. }
  5866. replaceWith(jqCollection, $compileNode, compileNode);
  5867. var newTemplateAttrs = {$attr: {}};
  5868. // combine directives from the original node and from the template:
  5869. // - take the array of directives for this element
  5870. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5871. // - collect directives from the template and sort them by priority
  5872. // - combine directives as: processed + template + unprocessed
  5873. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5874. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5875. if (newIsolateScopeDirective) {
  5876. markDirectivesAsIsolate(templateDirectives);
  5877. }
  5878. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5879. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5880. ii = directives.length;
  5881. } else {
  5882. $compileNode.html(directiveValue);
  5883. }
  5884. }
  5885. if (directive.templateUrl) {
  5886. hasTemplate = true;
  5887. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5888. templateDirective = directive;
  5889. if (directive.replace) {
  5890. replaceDirective = directive;
  5891. }
  5892. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5893. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  5894. controllerDirectives: controllerDirectives,
  5895. newIsolateScopeDirective: newIsolateScopeDirective,
  5896. templateDirective: templateDirective,
  5897. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5898. });
  5899. ii = directives.length;
  5900. } else if (directive.compile) {
  5901. try {
  5902. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5903. if (isFunction(linkFn)) {
  5904. addLinkFns(null, linkFn, attrStart, attrEnd);
  5905. } else if (linkFn) {
  5906. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5907. }
  5908. } catch (e) {
  5909. $exceptionHandler(e, startingTag($compileNode));
  5910. }
  5911. }
  5912. if (directive.terminal) {
  5913. nodeLinkFn.terminal = true;
  5914. terminalPriority = Math.max(terminalPriority, directive.priority);
  5915. }
  5916. }
  5917. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5918. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  5919. nodeLinkFn.templateOnThisElement = hasTemplate;
  5920. nodeLinkFn.transclude = childTranscludeFn;
  5921. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5922. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5923. return nodeLinkFn;
  5924. ////////////////////
  5925. function addLinkFns(pre, post, attrStart, attrEnd) {
  5926. if (pre) {
  5927. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5928. pre.require = directive.require;
  5929. pre.directiveName = directiveName;
  5930. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5931. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5932. }
  5933. preLinkFns.push(pre);
  5934. }
  5935. if (post) {
  5936. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5937. post.require = directive.require;
  5938. post.directiveName = directiveName;
  5939. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5940. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5941. }
  5942. postLinkFns.push(post);
  5943. }
  5944. }
  5945. function getControllers(directiveName, require, $element, elementControllers) {
  5946. var value, retrievalMethod = 'data', optional = false;
  5947. if (isString(require)) {
  5948. while((value = require.charAt(0)) == '^' || value == '?') {
  5949. require = require.substr(1);
  5950. if (value == '^') {
  5951. retrievalMethod = 'inheritedData';
  5952. }
  5953. optional = optional || value == '?';
  5954. }
  5955. value = null;
  5956. if (elementControllers && retrievalMethod === 'data') {
  5957. value = elementControllers[require];
  5958. }
  5959. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5960. if (!value && !optional) {
  5961. throw $compileMinErr('ctreq',
  5962. "Controller '{0}', required by directive '{1}', can't be found!",
  5963. require, directiveName);
  5964. }
  5965. return value;
  5966. } else if (isArray(require)) {
  5967. value = [];
  5968. forEach(require, function(require) {
  5969. value.push(getControllers(directiveName, require, $element, elementControllers));
  5970. });
  5971. }
  5972. return value;
  5973. }
  5974. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5975. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5976. attrs = (compileNode === linkNode)
  5977. ? templateAttrs
  5978. : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5979. $element = attrs.$$element;
  5980. if (newIsolateScopeDirective) {
  5981. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5982. isolateScope = scope.$new(true);
  5983. if (templateDirective && (templateDirective === newIsolateScopeDirective ||
  5984. templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5985. $element.data('$isolateScope', isolateScope);
  5986. } else {
  5987. $element.data('$isolateScopeNoTemplate', isolateScope);
  5988. }
  5989. safeAddClass($element, 'ng-isolate-scope');
  5990. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5991. var match = definition.match(LOCAL_REGEXP) || [],
  5992. attrName = match[3] || scopeName,
  5993. optional = (match[2] == '?'),
  5994. mode = match[1], // @, =, or &
  5995. lastValue,
  5996. parentGet, parentSet, compare;
  5997. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5998. switch (mode) {
  5999. case '@':
  6000. attrs.$observe(attrName, function(value) {
  6001. isolateScope[scopeName] = value;
  6002. });
  6003. attrs.$$observers[attrName].$$scope = scope;
  6004. if( attrs[attrName] ) {
  6005. // If the attribute has been provided then we trigger an interpolation to ensure
  6006. // the value is there for use in the link fn
  6007. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  6008. }
  6009. break;
  6010. case '=':
  6011. if (optional && !attrs[attrName]) {
  6012. return;
  6013. }
  6014. parentGet = $parse(attrs[attrName]);
  6015. if (parentGet.literal) {
  6016. compare = equals;
  6017. } else {
  6018. compare = function(a,b) { return a === b || (a !== a && b !== b); };
  6019. }
  6020. parentSet = parentGet.assign || function() {
  6021. // reset the change, or we will throw this exception on every $digest
  6022. lastValue = isolateScope[scopeName] = parentGet(scope);
  6023. throw $compileMinErr('nonassign',
  6024. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6025. attrs[attrName], newIsolateScopeDirective.name);
  6026. };
  6027. lastValue = isolateScope[scopeName] = parentGet(scope);
  6028. isolateScope.$watch(function parentValueWatch() {
  6029. var parentValue = parentGet(scope);
  6030. if (!compare(parentValue, isolateScope[scopeName])) {
  6031. // we are out of sync and need to copy
  6032. if (!compare(parentValue, lastValue)) {
  6033. // parent changed and it has precedence
  6034. isolateScope[scopeName] = parentValue;
  6035. } else {
  6036. // if the parent can be assigned then do so
  6037. parentSet(scope, parentValue = isolateScope[scopeName]);
  6038. }
  6039. }
  6040. return lastValue = parentValue;
  6041. }, null, parentGet.literal);
  6042. break;
  6043. case '&':
  6044. parentGet = $parse(attrs[attrName]);
  6045. isolateScope[scopeName] = function(locals) {
  6046. return parentGet(scope, locals);
  6047. };
  6048. break;
  6049. default:
  6050. throw $compileMinErr('iscp',
  6051. "Invalid isolate scope definition for directive '{0}'." +
  6052. " Definition: {... {1}: '{2}' ...}",
  6053. newIsolateScopeDirective.name, scopeName, definition);
  6054. }
  6055. });
  6056. }
  6057. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  6058. if (controllerDirectives) {
  6059. forEach(controllerDirectives, function(directive) {
  6060. var locals = {
  6061. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6062. $element: $element,
  6063. $attrs: attrs,
  6064. $transclude: transcludeFn
  6065. }, controllerInstance;
  6066. controller = directive.controller;
  6067. if (controller == '@') {
  6068. controller = attrs[directive.name];
  6069. }
  6070. controllerInstance = $controller(controller, locals);
  6071. // For directives with element transclusion the element is a comment,
  6072. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6073. // clean up (http://bugs.jquery.com/ticket/8335).
  6074. // Instead, we save the controllers for the element in a local hash and attach to .data
  6075. // later, once we have the actual element.
  6076. elementControllers[directive.name] = controllerInstance;
  6077. if (!hasElementTranscludeDirective) {
  6078. $element.data('$' + directive.name + 'Controller', controllerInstance);
  6079. }
  6080. if (directive.controllerAs) {
  6081. locals.$scope[directive.controllerAs] = controllerInstance;
  6082. }
  6083. });
  6084. }
  6085. // PRELINKING
  6086. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  6087. try {
  6088. linkFn = preLinkFns[i];
  6089. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6090. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6091. } catch (e) {
  6092. $exceptionHandler(e, startingTag($element));
  6093. }
  6094. }
  6095. // RECURSION
  6096. // We only pass the isolate scope, if the isolate directive has a template,
  6097. // otherwise the child elements do not belong to the isolate directive.
  6098. var scopeToChild = scope;
  6099. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6100. scopeToChild = isolateScope;
  6101. }
  6102. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6103. // POSTLINKING
  6104. for(i = postLinkFns.length - 1; i >= 0; i--) {
  6105. try {
  6106. linkFn = postLinkFns[i];
  6107. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6108. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6109. } catch (e) {
  6110. $exceptionHandler(e, startingTag($element));
  6111. }
  6112. }
  6113. // This is the function that is injected as `$transclude`.
  6114. function controllersBoundTransclude(scope, cloneAttachFn) {
  6115. var transcludeControllers;
  6116. // no scope passed
  6117. if (arguments.length < 2) {
  6118. cloneAttachFn = scope;
  6119. scope = undefined;
  6120. }
  6121. if (hasElementTranscludeDirective) {
  6122. transcludeControllers = elementControllers;
  6123. }
  6124. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  6125. }
  6126. }
  6127. }
  6128. function markDirectivesAsIsolate(directives) {
  6129. // mark all directives as needing isolate scope.
  6130. for (var j = 0, jj = directives.length; j < jj; j++) {
  6131. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6132. }
  6133. }
  6134. /**
  6135. * looks up the directive and decorates it with exception handling and proper parameters. We
  6136. * call this the boundDirective.
  6137. *
  6138. * @param {string} name name of the directive to look up.
  6139. * @param {string} location The directive must be found in specific format.
  6140. * String containing any of theses characters:
  6141. *
  6142. * * `E`: element name
  6143. * * `A': attribute
  6144. * * `C`: class
  6145. * * `M`: comment
  6146. * @returns {boolean} true if directive was added.
  6147. */
  6148. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6149. endAttrName) {
  6150. if (name === ignoreDirective) return null;
  6151. var match = null;
  6152. if (hasDirectives.hasOwnProperty(name)) {
  6153. for(var directive, directives = $injector.get(name + Suffix),
  6154. i = 0, ii = directives.length; i<ii; i++) {
  6155. try {
  6156. directive = directives[i];
  6157. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6158. directive.restrict.indexOf(location) != -1) {
  6159. if (startAttrName) {
  6160. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6161. }
  6162. tDirectives.push(directive);
  6163. match = directive;
  6164. }
  6165. } catch(e) { $exceptionHandler(e); }
  6166. }
  6167. }
  6168. return match;
  6169. }
  6170. /**
  6171. * When the element is replaced with HTML template then the new attributes
  6172. * on the template need to be merged with the existing attributes in the DOM.
  6173. * The desired effect is to have both of the attributes present.
  6174. *
  6175. * @param {object} dst destination attributes (original DOM)
  6176. * @param {object} src source attributes (from the directive template)
  6177. */
  6178. function mergeTemplateAttributes(dst, src) {
  6179. var srcAttr = src.$attr,
  6180. dstAttr = dst.$attr,
  6181. $element = dst.$$element;
  6182. // reapply the old attributes to the new element
  6183. forEach(dst, function(value, key) {
  6184. if (key.charAt(0) != '$') {
  6185. if (src[key] && src[key] !== value) {
  6186. value += (key === 'style' ? ';' : ' ') + src[key];
  6187. }
  6188. dst.$set(key, value, true, srcAttr[key]);
  6189. }
  6190. });
  6191. // copy the new attributes on the old attrs object
  6192. forEach(src, function(value, key) {
  6193. if (key == 'class') {
  6194. safeAddClass($element, value);
  6195. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6196. } else if (key == 'style') {
  6197. $element.attr('style', $element.attr('style') + ';' + value);
  6198. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6199. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6200. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6201. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6202. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6203. dst[key] = value;
  6204. dstAttr[key] = srcAttr[key];
  6205. }
  6206. });
  6207. }
  6208. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6209. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6210. var linkQueue = [],
  6211. afterTemplateNodeLinkFn,
  6212. afterTemplateChildLinkFn,
  6213. beforeTemplateCompileNode = $compileNode[0],
  6214. origAsyncDirective = directives.shift(),
  6215. // The fact that we have to copy and patch the directive seems wrong!
  6216. derivedSyncDirective = extend({}, origAsyncDirective, {
  6217. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6218. }),
  6219. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6220. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6221. : origAsyncDirective.templateUrl;
  6222. $compileNode.empty();
  6223. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6224. success(function(content) {
  6225. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6226. content = denormalizeTemplate(content);
  6227. if (origAsyncDirective.replace) {
  6228. if (jqLiteIsTextNode(content)) {
  6229. $template = [];
  6230. } else {
  6231. $template = jqLite(trim(content));
  6232. }
  6233. compileNode = $template[0];
  6234. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6235. throw $compileMinErr('tplrt',
  6236. "Template for directive '{0}' must have exactly one root element. {1}",
  6237. origAsyncDirective.name, templateUrl);
  6238. }
  6239. tempTemplateAttrs = {$attr: {}};
  6240. replaceWith($rootElement, $compileNode, compileNode);
  6241. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6242. if (isObject(origAsyncDirective.scope)) {
  6243. markDirectivesAsIsolate(templateDirectives);
  6244. }
  6245. directives = templateDirectives.concat(directives);
  6246. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6247. } else {
  6248. compileNode = beforeTemplateCompileNode;
  6249. $compileNode.html(content);
  6250. }
  6251. directives.unshift(derivedSyncDirective);
  6252. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6253. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6254. previousCompileContext);
  6255. forEach($rootElement, function(node, i) {
  6256. if (node == compileNode) {
  6257. $rootElement[i] = $compileNode[0];
  6258. }
  6259. });
  6260. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6261. while(linkQueue.length) {
  6262. var scope = linkQueue.shift(),
  6263. beforeTemplateLinkNode = linkQueue.shift(),
  6264. linkRootElement = linkQueue.shift(),
  6265. boundTranscludeFn = linkQueue.shift(),
  6266. linkNode = $compileNode[0];
  6267. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6268. var oldClasses = beforeTemplateLinkNode.className;
  6269. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6270. origAsyncDirective.replace)) {
  6271. // it was cloned therefore we have to clone as well.
  6272. linkNode = jqLiteClone(compileNode);
  6273. }
  6274. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6275. // Copy in CSS classes from original node
  6276. safeAddClass(jqLite(linkNode), oldClasses);
  6277. }
  6278. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6279. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6280. } else {
  6281. childBoundTranscludeFn = boundTranscludeFn;
  6282. }
  6283. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6284. childBoundTranscludeFn);
  6285. }
  6286. linkQueue = null;
  6287. }).
  6288. error(function(response, code, headers, config) {
  6289. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6290. });
  6291. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6292. var childBoundTranscludeFn = boundTranscludeFn;
  6293. if (linkQueue) {
  6294. linkQueue.push(scope);
  6295. linkQueue.push(node);
  6296. linkQueue.push(rootElement);
  6297. linkQueue.push(childBoundTranscludeFn);
  6298. } else {
  6299. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6300. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6301. }
  6302. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  6303. }
  6304. };
  6305. }
  6306. /**
  6307. * Sorting function for bound directives.
  6308. */
  6309. function byPriority(a, b) {
  6310. var diff = b.priority - a.priority;
  6311. if (diff !== 0) return diff;
  6312. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6313. return a.index - b.index;
  6314. }
  6315. function assertNoDuplicate(what, previousDirective, directive, element) {
  6316. if (previousDirective) {
  6317. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6318. previousDirective.name, directive.name, what, startingTag(element));
  6319. }
  6320. }
  6321. function addTextInterpolateDirective(directives, text) {
  6322. var interpolateFn = $interpolate(text, true);
  6323. if (interpolateFn) {
  6324. directives.push({
  6325. priority: 0,
  6326. compile: function textInterpolateCompileFn(templateNode) {
  6327. // when transcluding a template that has bindings in the root
  6328. // then we don't have a parent and should do this in the linkFn
  6329. var parent = templateNode.parent(), hasCompileParent = parent.length;
  6330. if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding');
  6331. return function textInterpolateLinkFn(scope, node) {
  6332. var parent = node.parent(),
  6333. bindings = parent.data('$binding') || [];
  6334. bindings.push(interpolateFn);
  6335. parent.data('$binding', bindings);
  6336. if (!hasCompileParent) safeAddClass(parent, 'ng-binding');
  6337. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6338. node[0].nodeValue = value;
  6339. });
  6340. };
  6341. }
  6342. });
  6343. }
  6344. }
  6345. function getTrustedContext(node, attrNormalizedName) {
  6346. if (attrNormalizedName == "srcdoc") {
  6347. return $sce.HTML;
  6348. }
  6349. var tag = nodeName_(node);
  6350. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6351. if (attrNormalizedName == "xlinkHref" ||
  6352. (tag == "FORM" && attrNormalizedName == "action") ||
  6353. (tag != "IMG" && (attrNormalizedName == "src" ||
  6354. attrNormalizedName == "ngSrc"))) {
  6355. return $sce.RESOURCE_URL;
  6356. }
  6357. }
  6358. function addAttrInterpolateDirective(node, directives, value, name) {
  6359. var interpolateFn = $interpolate(value, true);
  6360. // no interpolation found -> ignore
  6361. if (!interpolateFn) return;
  6362. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6363. throw $compileMinErr("selmulti",
  6364. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6365. startingTag(node));
  6366. }
  6367. directives.push({
  6368. priority: 100,
  6369. compile: function() {
  6370. return {
  6371. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6372. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6373. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6374. throw $compileMinErr('nodomevents',
  6375. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6376. "ng- versions (such as ng-click instead of onclick) instead.");
  6377. }
  6378. // we need to interpolate again, in case the attribute value has been updated
  6379. // (e.g. by another directive's compile function)
  6380. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6381. // if attribute was updated so that there is no interpolation going on we don't want to
  6382. // register any observers
  6383. if (!interpolateFn) return;
  6384. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6385. // actual attr value
  6386. attr[name] = interpolateFn(scope);
  6387. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6388. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6389. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6390. //special case for class attribute addition + removal
  6391. //so that class changes can tap into the animation
  6392. //hooks provided by the $animate service. Be sure to
  6393. //skip animations when the first digest occurs (when
  6394. //both the new and the old values are the same) since
  6395. //the CSS classes are the non-interpolated values
  6396. if(name === 'class' && newValue != oldValue) {
  6397. attr.$updateClass(newValue, oldValue);
  6398. } else {
  6399. attr.$set(name, newValue);
  6400. }
  6401. });
  6402. }
  6403. };
  6404. }
  6405. });
  6406. }
  6407. /**
  6408. * This is a special jqLite.replaceWith, which can replace items which
  6409. * have no parents, provided that the containing jqLite collection is provided.
  6410. *
  6411. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6412. * in the root of the tree.
  6413. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6414. * the shell, but replace its DOM node reference.
  6415. * @param {Node} newNode The new DOM node.
  6416. */
  6417. function replaceWith($rootElement, elementsToRemove, newNode) {
  6418. var firstElementToRemove = elementsToRemove[0],
  6419. removeCount = elementsToRemove.length,
  6420. parent = firstElementToRemove.parentNode,
  6421. i, ii;
  6422. if ($rootElement) {
  6423. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6424. if ($rootElement[i] == firstElementToRemove) {
  6425. $rootElement[i++] = newNode;
  6426. for (var j = i, j2 = j + removeCount - 1,
  6427. jj = $rootElement.length;
  6428. j < jj; j++, j2++) {
  6429. if (j2 < jj) {
  6430. $rootElement[j] = $rootElement[j2];
  6431. } else {
  6432. delete $rootElement[j];
  6433. }
  6434. }
  6435. $rootElement.length -= removeCount - 1;
  6436. break;
  6437. }
  6438. }
  6439. }
  6440. if (parent) {
  6441. parent.replaceChild(newNode, firstElementToRemove);
  6442. }
  6443. var fragment = document.createDocumentFragment();
  6444. fragment.appendChild(firstElementToRemove);
  6445. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6446. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6447. var element = elementsToRemove[k];
  6448. jqLite(element).remove(); // must do this way to clean up expando
  6449. fragment.appendChild(element);
  6450. delete elementsToRemove[k];
  6451. }
  6452. elementsToRemove[0] = newNode;
  6453. elementsToRemove.length = 1;
  6454. }
  6455. function cloneAndAnnotateFn(fn, annotation) {
  6456. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6457. }
  6458. }];
  6459. }
  6460. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6461. /**
  6462. * Converts all accepted directives format into proper directive name.
  6463. * @param name Name to normalize
  6464. */
  6465. function directiveNormalize(name) {
  6466. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6467. }
  6468. /**
  6469. * @ngdoc type
  6470. * @name $compile.directive.Attributes
  6471. *
  6472. * @description
  6473. * A shared object between directive compile / linking functions which contains normalized DOM
  6474. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6475. * needed since all of these are treated as equivalent in Angular:
  6476. *
  6477. * ```
  6478. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6479. * ```
  6480. */
  6481. /**
  6482. * @ngdoc property
  6483. * @name $compile.directive.Attributes#$attr
  6484. *
  6485. * @description
  6486. * A map of DOM element attribute names to the normalized name. This is
  6487. * needed to do reverse lookup from normalized name back to actual name.
  6488. */
  6489. /**
  6490. * @ngdoc method
  6491. * @name $compile.directive.Attributes#$set
  6492. * @kind function
  6493. *
  6494. * @description
  6495. * Set DOM element attribute value.
  6496. *
  6497. *
  6498. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6499. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6500. * property to the original name.
  6501. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6502. */
  6503. /**
  6504. * Closure compiler type information
  6505. */
  6506. function nodesetLinkingFn(
  6507. /* angular.Scope */ scope,
  6508. /* NodeList */ nodeList,
  6509. /* Element */ rootElement,
  6510. /* function(Function) */ boundTranscludeFn
  6511. ){}
  6512. function directiveLinkingFn(
  6513. /* nodesetLinkingFn */ nodesetLinkingFn,
  6514. /* angular.Scope */ scope,
  6515. /* Node */ node,
  6516. /* Element */ rootElement,
  6517. /* function(Function) */ boundTranscludeFn
  6518. ){}
  6519. function tokenDifference(str1, str2) {
  6520. var values = '',
  6521. tokens1 = str1.split(/\s+/),
  6522. tokens2 = str2.split(/\s+/);
  6523. outer:
  6524. for(var i = 0; i < tokens1.length; i++) {
  6525. var token = tokens1[i];
  6526. for(var j = 0; j < tokens2.length; j++) {
  6527. if(token == tokens2[j]) continue outer;
  6528. }
  6529. values += (values.length > 0 ? ' ' : '') + token;
  6530. }
  6531. return values;
  6532. }
  6533. /**
  6534. * @ngdoc provider
  6535. * @name $controllerProvider
  6536. * @description
  6537. * The {@link ng.$controller $controller service} is used by Angular to create new
  6538. * controllers.
  6539. *
  6540. * This provider allows controller registration via the
  6541. * {@link ng.$controllerProvider#register register} method.
  6542. */
  6543. function $ControllerProvider() {
  6544. var controllers = {},
  6545. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6546. /**
  6547. * @ngdoc method
  6548. * @name $controllerProvider#register
  6549. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6550. * the names and the values are the constructors.
  6551. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6552. * annotations in the array notation).
  6553. */
  6554. this.register = function(name, constructor) {
  6555. assertNotHasOwnProperty(name, 'controller');
  6556. if (isObject(name)) {
  6557. extend(controllers, name);
  6558. } else {
  6559. controllers[name] = constructor;
  6560. }
  6561. };
  6562. this.$get = ['$injector', '$window', function($injector, $window) {
  6563. /**
  6564. * @ngdoc service
  6565. * @name $controller
  6566. * @requires $injector
  6567. *
  6568. * @param {Function|string} constructor If called with a function then it's considered to be the
  6569. * controller constructor function. Otherwise it's considered to be a string which is used
  6570. * to retrieve the controller constructor using the following steps:
  6571. *
  6572. * * check if a controller with given name is registered via `$controllerProvider`
  6573. * * check if evaluating the string on the current scope returns a constructor
  6574. * * check `window[constructor]` on the global `window` object
  6575. *
  6576. * @param {Object} locals Injection locals for Controller.
  6577. * @return {Object} Instance of given controller.
  6578. *
  6579. * @description
  6580. * `$controller` service is responsible for instantiating controllers.
  6581. *
  6582. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6583. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6584. */
  6585. return function(expression, locals) {
  6586. var instance, match, constructor, identifier;
  6587. if(isString(expression)) {
  6588. match = expression.match(CNTRL_REG),
  6589. constructor = match[1],
  6590. identifier = match[3];
  6591. expression = controllers.hasOwnProperty(constructor)
  6592. ? controllers[constructor]
  6593. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6594. assertArgFn(expression, constructor, true);
  6595. }
  6596. instance = $injector.instantiate(expression, locals);
  6597. if (identifier) {
  6598. if (!(locals && typeof locals.$scope === 'object')) {
  6599. throw minErr('$controller')('noscp',
  6600. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6601. constructor || expression.name, identifier);
  6602. }
  6603. locals.$scope[identifier] = instance;
  6604. }
  6605. return instance;
  6606. };
  6607. }];
  6608. }
  6609. /**
  6610. * @ngdoc service
  6611. * @name $document
  6612. * @requires $window
  6613. *
  6614. * @description
  6615. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6616. *
  6617. * @example
  6618. <example module="documentExample">
  6619. <file name="index.html">
  6620. <div ng-controller="ExampleController">
  6621. <p>$document title: <b ng-bind="title"></b></p>
  6622. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6623. </div>
  6624. </file>
  6625. <file name="script.js">
  6626. angular.module('documentExample', [])
  6627. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  6628. $scope.title = $document[0].title;
  6629. $scope.windowTitle = angular.element(window.document)[0].title;
  6630. }]);
  6631. </file>
  6632. </example>
  6633. */
  6634. function $DocumentProvider(){
  6635. this.$get = ['$window', function(window){
  6636. return jqLite(window.document);
  6637. }];
  6638. }
  6639. /**
  6640. * @ngdoc service
  6641. * @name $exceptionHandler
  6642. * @requires ng.$log
  6643. *
  6644. * @description
  6645. * Any uncaught exception in angular expressions is delegated to this service.
  6646. * The default implementation simply delegates to `$log.error` which logs it into
  6647. * the browser console.
  6648. *
  6649. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6650. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6651. *
  6652. * ## Example:
  6653. *
  6654. * ```js
  6655. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6656. * return function (exception, cause) {
  6657. * exception.message += ' (caused by "' + cause + '")';
  6658. * throw exception;
  6659. * };
  6660. * });
  6661. * ```
  6662. *
  6663. * This example will override the normal action of `$exceptionHandler`, to make angular
  6664. * exceptions fail hard when they happen, instead of just logging to the console.
  6665. *
  6666. * @param {Error} exception Exception associated with the error.
  6667. * @param {string=} cause optional information about the context in which
  6668. * the error was thrown.
  6669. *
  6670. */
  6671. function $ExceptionHandlerProvider() {
  6672. this.$get = ['$log', function($log) {
  6673. return function(exception, cause) {
  6674. $log.error.apply($log, arguments);
  6675. };
  6676. }];
  6677. }
  6678. /**
  6679. * Parse headers into key value object
  6680. *
  6681. * @param {string} headers Raw headers as a string
  6682. * @returns {Object} Parsed headers as key value object
  6683. */
  6684. function parseHeaders(headers) {
  6685. var parsed = {}, key, val, i;
  6686. if (!headers) return parsed;
  6687. forEach(headers.split('\n'), function(line) {
  6688. i = line.indexOf(':');
  6689. key = lowercase(trim(line.substr(0, i)));
  6690. val = trim(line.substr(i + 1));
  6691. if (key) {
  6692. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6693. }
  6694. });
  6695. return parsed;
  6696. }
  6697. /**
  6698. * Returns a function that provides access to parsed headers.
  6699. *
  6700. * Headers are lazy parsed when first requested.
  6701. * @see parseHeaders
  6702. *
  6703. * @param {(string|Object)} headers Headers to provide access to.
  6704. * @returns {function(string=)} Returns a getter function which if called with:
  6705. *
  6706. * - if called with single an argument returns a single header value or null
  6707. * - if called with no arguments returns an object containing all headers.
  6708. */
  6709. function headersGetter(headers) {
  6710. var headersObj = isObject(headers) ? headers : undefined;
  6711. return function(name) {
  6712. if (!headersObj) headersObj = parseHeaders(headers);
  6713. if (name) {
  6714. return headersObj[lowercase(name)] || null;
  6715. }
  6716. return headersObj;
  6717. };
  6718. }
  6719. /**
  6720. * Chain all given functions
  6721. *
  6722. * This function is used for both request and response transforming
  6723. *
  6724. * @param {*} data Data to transform.
  6725. * @param {function(string=)} headers Http headers getter fn.
  6726. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6727. * @returns {*} Transformed data.
  6728. */
  6729. function transformData(data, headers, fns) {
  6730. if (isFunction(fns))
  6731. return fns(data, headers);
  6732. forEach(fns, function(fn) {
  6733. data = fn(data, headers);
  6734. });
  6735. return data;
  6736. }
  6737. function isSuccess(status) {
  6738. return 200 <= status && status < 300;
  6739. }
  6740. /**
  6741. * @ngdoc provider
  6742. * @name $httpProvider
  6743. * @description
  6744. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  6745. * */
  6746. function $HttpProvider() {
  6747. var JSON_START = /^\s*(\[|\{[^\{])/,
  6748. JSON_END = /[\}\]]\s*$/,
  6749. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6750. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6751. /**
  6752. * @ngdoc property
  6753. * @name $httpProvider#defaults
  6754. * @description
  6755. *
  6756. * Object containing default values for all {@link ng.$http $http} requests.
  6757. *
  6758. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  6759. * Defaults value is `'XSRF-TOKEN'`.
  6760. *
  6761. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  6762. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  6763. *
  6764. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  6765. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  6766. * setting default headers.
  6767. * - **`defaults.headers.common`**
  6768. * - **`defaults.headers.post`**
  6769. * - **`defaults.headers.put`**
  6770. * - **`defaults.headers.patch`**
  6771. **/
  6772. var defaults = this.defaults = {
  6773. // transform incoming response data
  6774. transformResponse: [function(data) {
  6775. if (isString(data)) {
  6776. // strip json vulnerability protection prefix
  6777. data = data.replace(PROTECTION_PREFIX, '');
  6778. if (JSON_START.test(data) && JSON_END.test(data))
  6779. data = fromJson(data);
  6780. }
  6781. return data;
  6782. }],
  6783. // transform outgoing request data
  6784. transformRequest: [function(d) {
  6785. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6786. }],
  6787. // default headers
  6788. headers: {
  6789. common: {
  6790. 'Accept': 'application/json, text/plain, */*'
  6791. },
  6792. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6793. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6794. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  6795. },
  6796. xsrfCookieName: 'XSRF-TOKEN',
  6797. xsrfHeaderName: 'X-XSRF-TOKEN'
  6798. };
  6799. /**
  6800. * @ngdoc property
  6801. * @name $httpProvider#interceptors
  6802. * @description
  6803. *
  6804. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  6805. * pre-processing of request or postprocessing of responses.
  6806. *
  6807. * These service factories are ordered by request, i.e. they are applied in the same order as the
  6808. * array, on request, but reverse order, on response.
  6809. *
  6810. * {@link ng.$http#interceptors Interceptors detailed info}
  6811. **/
  6812. var interceptorFactories = this.interceptors = [];
  6813. /**
  6814. * For historical reasons, response interceptors are ordered by the order in which
  6815. * they are applied to the response. (This is the opposite of interceptorFactories)
  6816. */
  6817. var responseInterceptorFactories = this.responseInterceptors = [];
  6818. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6819. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6820. var defaultCache = $cacheFactory('$http');
  6821. /**
  6822. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6823. * The reversal is needed so that we can build up the interception chain around the
  6824. * server request.
  6825. */
  6826. var reversedInterceptors = [];
  6827. forEach(interceptorFactories, function(interceptorFactory) {
  6828. reversedInterceptors.unshift(isString(interceptorFactory)
  6829. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6830. });
  6831. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6832. var responseFn = isString(interceptorFactory)
  6833. ? $injector.get(interceptorFactory)
  6834. : $injector.invoke(interceptorFactory);
  6835. /**
  6836. * Response interceptors go before "around" interceptors (no real reason, just
  6837. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6838. * the splice.
  6839. */
  6840. reversedInterceptors.splice(index, 0, {
  6841. response: function(response) {
  6842. return responseFn($q.when(response));
  6843. },
  6844. responseError: function(response) {
  6845. return responseFn($q.reject(response));
  6846. }
  6847. });
  6848. });
  6849. /**
  6850. * @ngdoc service
  6851. * @kind function
  6852. * @name $http
  6853. * @requires ng.$httpBackend
  6854. * @requires $cacheFactory
  6855. * @requires $rootScope
  6856. * @requires $q
  6857. * @requires $injector
  6858. *
  6859. * @description
  6860. * The `$http` service is a core Angular service that facilitates communication with the remote
  6861. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6862. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6863. *
  6864. * For unit testing applications that use `$http` service, see
  6865. * {@link ngMock.$httpBackend $httpBackend mock}.
  6866. *
  6867. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6868. * $resource} service.
  6869. *
  6870. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6871. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6872. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6873. *
  6874. *
  6875. * # General usage
  6876. * The `$http` service is a function which takes a single argument — a configuration object —
  6877. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6878. * with two $http specific methods: `success` and `error`.
  6879. *
  6880. * ```js
  6881. * $http({method: 'GET', url: '/someUrl'}).
  6882. * success(function(data, status, headers, config) {
  6883. * // this callback will be called asynchronously
  6884. * // when the response is available
  6885. * }).
  6886. * error(function(data, status, headers, config) {
  6887. * // called asynchronously if an error occurs
  6888. * // or server returns response with an error status.
  6889. * });
  6890. * ```
  6891. *
  6892. * Since the returned value of calling the $http function is a `promise`, you can also use
  6893. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6894. * an object representing the response. See the API signature and type info below for more
  6895. * details.
  6896. *
  6897. * A response status code between 200 and 299 is considered a success status and
  6898. * will result in the success callback being called. Note that if the response is a redirect,
  6899. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6900. * called for such responses.
  6901. *
  6902. * # Writing Unit Tests that use $http
  6903. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6904. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6905. * request using trained responses.
  6906. *
  6907. * ```
  6908. * $httpBackend.expectGET(...);
  6909. * $http.get(...);
  6910. * $httpBackend.flush();
  6911. * ```
  6912. *
  6913. * # Shortcut methods
  6914. *
  6915. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6916. * request data must be passed in for POST/PUT requests.
  6917. *
  6918. * ```js
  6919. * $http.get('/someUrl').success(successCallback);
  6920. * $http.post('/someUrl', data).success(successCallback);
  6921. * ```
  6922. *
  6923. * Complete list of shortcut methods:
  6924. *
  6925. * - {@link ng.$http#get $http.get}
  6926. * - {@link ng.$http#head $http.head}
  6927. * - {@link ng.$http#post $http.post}
  6928. * - {@link ng.$http#put $http.put}
  6929. * - {@link ng.$http#delete $http.delete}
  6930. * - {@link ng.$http#jsonp $http.jsonp}
  6931. * - {@link ng.$http#patch $http.patch}
  6932. *
  6933. *
  6934. * # Setting HTTP Headers
  6935. *
  6936. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6937. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6938. * object, which currently contains this default configuration:
  6939. *
  6940. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6941. * - `Accept: application/json, text/plain, * / *`
  6942. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6943. * - `Content-Type: application/json`
  6944. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6945. * - `Content-Type: application/json`
  6946. *
  6947. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6948. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6949. * with the lowercased HTTP method name as the key, e.g.
  6950. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6951. *
  6952. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6953. * fashion. For example:
  6954. *
  6955. * ```
  6956. * module.run(function($http) {
  6957. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6958. * });
  6959. * ```
  6960. *
  6961. * In addition, you can supply a `headers` property in the config object passed when
  6962. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6963. *
  6964. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  6965. * Use the `headers` property, setting the desired header to `undefined`. For example:
  6966. *
  6967. * ```js
  6968. * var req = {
  6969. * method: 'POST',
  6970. * url: 'http://example.com',
  6971. * headers: {
  6972. * 'Content-Type': undefined
  6973. * },
  6974. * data: { test: 'test' },
  6975. * }
  6976. *
  6977. * $http(req).success(function(){...}).error(function(){...});
  6978. * ```
  6979. *
  6980. * # Transforming Requests and Responses
  6981. *
  6982. * Both requests and responses can be transformed using transform functions. By default, Angular
  6983. * applies these transformations:
  6984. *
  6985. * Request transformations:
  6986. *
  6987. * - If the `data` property of the request configuration object contains an object, serialize it
  6988. * into JSON format.
  6989. *
  6990. * Response transformations:
  6991. *
  6992. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6993. * - If JSON response is detected, deserialize it using a JSON parser.
  6994. *
  6995. * To globally augment or override the default transforms, modify the
  6996. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6997. * properties. These properties are by default an array of transform functions, which allows you
  6998. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6999. * also decide to completely override any default transformations by assigning your
  7000. * transformation functions to these properties directly without the array wrapper. These defaults
  7001. * are again available on the $http factory at run-time, which may be useful if you have run-time
  7002. * services you wish to be involved in your transformations.
  7003. *
  7004. * Similarly, to locally override the request/response transforms, augment the
  7005. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  7006. * into `$http`.
  7007. *
  7008. *
  7009. * # Caching
  7010. *
  7011. * To enable caching, set the request configuration `cache` property to `true` (to use default
  7012. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  7013. * When the cache is enabled, `$http` stores the response from the server in the specified
  7014. * cache. The next time the same request is made, the response is served from the cache without
  7015. * sending a request to the server.
  7016. *
  7017. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  7018. * the same way that real requests are.
  7019. *
  7020. * If there are multiple GET requests for the same URL that should be cached using the same
  7021. * cache, but the cache is not populated yet, only one request to the server will be made and
  7022. * the remaining requests will be fulfilled using the response from the first request.
  7023. *
  7024. * You can change the default cache to a new object (built with
  7025. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  7026. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  7027. * their `cache` property to `true` will now use this cache object.
  7028. *
  7029. * If you set the default cache to `false` then only requests that specify their own custom
  7030. * cache object will be cached.
  7031. *
  7032. * # Interceptors
  7033. *
  7034. * Before you start creating interceptors, be sure to understand the
  7035. * {@link ng.$q $q and deferred/promise APIs}.
  7036. *
  7037. * For purposes of global error handling, authentication, or any kind of synchronous or
  7038. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  7039. * able to intercept requests before they are handed to the server and
  7040. * responses before they are handed over to the application code that
  7041. * initiated these requests. The interceptors leverage the {@link ng.$q
  7042. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  7043. *
  7044. * The interceptors are service factories that are registered with the `$httpProvider` by
  7045. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  7046. * injected with dependencies (if specified) and returns the interceptor.
  7047. *
  7048. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  7049. *
  7050. * * `request`: interceptors get called with a http `config` object. The function is free to
  7051. * modify the `config` object or create a new one. The function needs to return the `config`
  7052. * object directly, or a promise containing the `config` or a new `config` object.
  7053. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  7054. * resolved with a rejection.
  7055. * * `response`: interceptors get called with http `response` object. The function is free to
  7056. * modify the `response` object or create a new one. The function needs to return the `response`
  7057. * object directly, or as a promise containing the `response` or a new `response` object.
  7058. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  7059. * resolved with a rejection.
  7060. *
  7061. *
  7062. * ```js
  7063. * // register the interceptor as a service
  7064. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7065. * return {
  7066. * // optional method
  7067. * 'request': function(config) {
  7068. * // do something on success
  7069. * return config;
  7070. * },
  7071. *
  7072. * // optional method
  7073. * 'requestError': function(rejection) {
  7074. * // do something on error
  7075. * if (canRecover(rejection)) {
  7076. * return responseOrNewPromise
  7077. * }
  7078. * return $q.reject(rejection);
  7079. * },
  7080. *
  7081. *
  7082. *
  7083. * // optional method
  7084. * 'response': function(response) {
  7085. * // do something on success
  7086. * return response;
  7087. * },
  7088. *
  7089. * // optional method
  7090. * 'responseError': function(rejection) {
  7091. * // do something on error
  7092. * if (canRecover(rejection)) {
  7093. * return responseOrNewPromise
  7094. * }
  7095. * return $q.reject(rejection);
  7096. * }
  7097. * };
  7098. * });
  7099. *
  7100. * $httpProvider.interceptors.push('myHttpInterceptor');
  7101. *
  7102. *
  7103. * // alternatively, register the interceptor via an anonymous factory
  7104. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  7105. * return {
  7106. * 'request': function(config) {
  7107. * // same as above
  7108. * },
  7109. *
  7110. * 'response': function(response) {
  7111. * // same as above
  7112. * }
  7113. * };
  7114. * });
  7115. * ```
  7116. *
  7117. * # Response interceptors (DEPRECATED)
  7118. *
  7119. * Before you start creating interceptors, be sure to understand the
  7120. * {@link ng.$q $q and deferred/promise APIs}.
  7121. *
  7122. * For purposes of global error handling, authentication or any kind of synchronous or
  7123. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  7124. * responses for http requests before they are handed over to the application code that
  7125. * initiated these requests. The response interceptors leverage the {@link ng.$q
  7126. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  7127. *
  7128. * The interceptors are service factories that are registered with the $httpProvider by
  7129. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  7130. * injected with dependencies (if specified) and returns the interceptor — a function that
  7131. * takes a {@link ng.$q promise} and returns the original or a new promise.
  7132. *
  7133. * ```js
  7134. * // register the interceptor as a service
  7135. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7136. * return function(promise) {
  7137. * return promise.then(function(response) {
  7138. * // do something on success
  7139. * return response;
  7140. * }, function(response) {
  7141. * // do something on error
  7142. * if (canRecover(response)) {
  7143. * return responseOrNewPromise
  7144. * }
  7145. * return $q.reject(response);
  7146. * });
  7147. * }
  7148. * });
  7149. *
  7150. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  7151. *
  7152. *
  7153. * // register the interceptor via an anonymous factory
  7154. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  7155. * return function(promise) {
  7156. * // same as above
  7157. * }
  7158. * });
  7159. * ```
  7160. *
  7161. *
  7162. * # Security Considerations
  7163. *
  7164. * When designing web applications, consider security threats from:
  7165. *
  7166. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7167. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  7168. *
  7169. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  7170. * pre-configured with strategies that address these issues, but for this to work backend server
  7171. * cooperation is required.
  7172. *
  7173. * ## JSON Vulnerability Protection
  7174. *
  7175. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7176. * allows third party website to turn your JSON resource URL into
  7177. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  7178. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  7179. * Angular will automatically strip the prefix before processing it as JSON.
  7180. *
  7181. * For example if your server needs to return:
  7182. * ```js
  7183. * ['one','two']
  7184. * ```
  7185. *
  7186. * which is vulnerable to attack, your server can return:
  7187. * ```js
  7188. * )]}',
  7189. * ['one','two']
  7190. * ```
  7191. *
  7192. * Angular will strip the prefix, before processing the JSON.
  7193. *
  7194. *
  7195. * ## Cross Site Request Forgery (XSRF) Protection
  7196. *
  7197. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  7198. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  7199. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  7200. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  7201. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  7202. * the XHR came from JavaScript running on your domain. The header will not be set for
  7203. * cross-domain requests.
  7204. *
  7205. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7206. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7207. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7208. * that only JavaScript running on your domain could have sent the request. The token must be
  7209. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7210. * making up its own tokens). We recommend that the token is a digest of your site's
  7211. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  7212. * for added security.
  7213. *
  7214. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7215. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7216. * or the per-request config object.
  7217. *
  7218. *
  7219. * @param {object} config Object describing the request to be made and how it should be
  7220. * processed. The object has following properties:
  7221. *
  7222. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7223. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7224. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7225. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7226. * JSONified.
  7227. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7228. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7229. * HTTP headers to send to the server. If the return value of a function is null, the
  7230. * header will not be sent.
  7231. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7232. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7233. * - **transformRequest** –
  7234. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7235. * transform function or an array of such functions. The transform function takes the http
  7236. * request body and headers and returns its transformed (typically serialized) version.
  7237. * - **transformResponse** –
  7238. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7239. * transform function or an array of such functions. The transform function takes the http
  7240. * response body and headers and returns its transformed (typically deserialized) version.
  7241. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7242. * GET request, otherwise if a cache instance built with
  7243. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7244. * caching.
  7245. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7246. * that should abort the request when resolved.
  7247. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  7248. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  7249. * for more information.
  7250. * - **responseType** - `{string}` - see
  7251. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7252. *
  7253. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7254. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7255. * method takes two arguments a success and an error callback which will be called with a
  7256. * response object. The `success` and `error` methods take a single argument - a function that
  7257. * will be called when the request succeeds or fails respectively. The arguments passed into
  7258. * these functions are destructured representation of the response object passed into the
  7259. * `then` method. The response object has these properties:
  7260. *
  7261. * - **data** – `{string|Object}` – The response body transformed with the transform
  7262. * functions.
  7263. * - **status** – `{number}` – HTTP status code of the response.
  7264. * - **headers** – `{function([headerName])}` – Header getter function.
  7265. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7266. * - **statusText** – `{string}` – HTTP status text of the response.
  7267. *
  7268. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7269. * requests. This is primarily meant to be used for debugging purposes.
  7270. *
  7271. *
  7272. * @example
  7273. <example module="httpExample">
  7274. <file name="index.html">
  7275. <div ng-controller="FetchController">
  7276. <select ng-model="method">
  7277. <option>GET</option>
  7278. <option>JSONP</option>
  7279. </select>
  7280. <input type="text" ng-model="url" size="80"/>
  7281. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7282. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7283. <button id="samplejsonpbtn"
  7284. ng-click="updateModel('JSONP',
  7285. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7286. Sample JSONP
  7287. </button>
  7288. <button id="invalidjsonpbtn"
  7289. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7290. Invalid JSONP
  7291. </button>
  7292. <pre>http status code: {{status}}</pre>
  7293. <pre>http response data: {{data}}</pre>
  7294. </div>
  7295. </file>
  7296. <file name="script.js">
  7297. angular.module('httpExample', [])
  7298. .controller('FetchController', ['$scope', '$http', '$templateCache',
  7299. function($scope, $http, $templateCache) {
  7300. $scope.method = 'GET';
  7301. $scope.url = 'http-hello.html';
  7302. $scope.fetch = function() {
  7303. $scope.code = null;
  7304. $scope.response = null;
  7305. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7306. success(function(data, status) {
  7307. $scope.status = status;
  7308. $scope.data = data;
  7309. }).
  7310. error(function(data, status) {
  7311. $scope.data = data || "Request failed";
  7312. $scope.status = status;
  7313. });
  7314. };
  7315. $scope.updateModel = function(method, url) {
  7316. $scope.method = method;
  7317. $scope.url = url;
  7318. };
  7319. }]);
  7320. </file>
  7321. <file name="http-hello.html">
  7322. Hello, $http!
  7323. </file>
  7324. <file name="protractor.js" type="protractor">
  7325. var status = element(by.binding('status'));
  7326. var data = element(by.binding('data'));
  7327. var fetchBtn = element(by.id('fetchbtn'));
  7328. var sampleGetBtn = element(by.id('samplegetbtn'));
  7329. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7330. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7331. it('should make an xhr GET request', function() {
  7332. sampleGetBtn.click();
  7333. fetchBtn.click();
  7334. expect(status.getText()).toMatch('200');
  7335. expect(data.getText()).toMatch(/Hello, \$http!/);
  7336. });
  7337. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  7338. // it('should make a JSONP request to angularjs.org', function() {
  7339. // sampleJsonpBtn.click();
  7340. // fetchBtn.click();
  7341. // expect(status.getText()).toMatch('200');
  7342. // expect(data.getText()).toMatch(/Super Hero!/);
  7343. // });
  7344. it('should make JSONP request to invalid URL and invoke the error handler',
  7345. function() {
  7346. invalidJsonpBtn.click();
  7347. fetchBtn.click();
  7348. expect(status.getText()).toMatch('0');
  7349. expect(data.getText()).toMatch('Request failed');
  7350. });
  7351. </file>
  7352. </example>
  7353. */
  7354. function $http(requestConfig) {
  7355. var config = {
  7356. method: 'get',
  7357. transformRequest: defaults.transformRequest,
  7358. transformResponse: defaults.transformResponse
  7359. };
  7360. var headers = mergeHeaders(requestConfig);
  7361. extend(config, requestConfig);
  7362. config.headers = headers;
  7363. config.method = uppercase(config.method);
  7364. var serverRequest = function(config) {
  7365. headers = config.headers;
  7366. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7367. // strip content-type if data is undefined
  7368. if (isUndefined(reqData)) {
  7369. forEach(headers, function(value, header) {
  7370. if (lowercase(header) === 'content-type') {
  7371. delete headers[header];
  7372. }
  7373. });
  7374. }
  7375. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7376. config.withCredentials = defaults.withCredentials;
  7377. }
  7378. // send request
  7379. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7380. };
  7381. var chain = [serverRequest, undefined];
  7382. var promise = $q.when(config);
  7383. // apply interceptors
  7384. forEach(reversedInterceptors, function(interceptor) {
  7385. if (interceptor.request || interceptor.requestError) {
  7386. chain.unshift(interceptor.request, interceptor.requestError);
  7387. }
  7388. if (interceptor.response || interceptor.responseError) {
  7389. chain.push(interceptor.response, interceptor.responseError);
  7390. }
  7391. });
  7392. while(chain.length) {
  7393. var thenFn = chain.shift();
  7394. var rejectFn = chain.shift();
  7395. promise = promise.then(thenFn, rejectFn);
  7396. }
  7397. promise.success = function(fn) {
  7398. promise.then(function(response) {
  7399. fn(response.data, response.status, response.headers, config);
  7400. });
  7401. return promise;
  7402. };
  7403. promise.error = function(fn) {
  7404. promise.then(null, function(response) {
  7405. fn(response.data, response.status, response.headers, config);
  7406. });
  7407. return promise;
  7408. };
  7409. return promise;
  7410. function transformResponse(response) {
  7411. // make a copy since the response must be cacheable
  7412. var resp = extend({}, response, {
  7413. data: transformData(response.data, response.headers, config.transformResponse)
  7414. });
  7415. return (isSuccess(response.status))
  7416. ? resp
  7417. : $q.reject(resp);
  7418. }
  7419. function mergeHeaders(config) {
  7420. var defHeaders = defaults.headers,
  7421. reqHeaders = extend({}, config.headers),
  7422. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7423. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7424. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7425. defaultHeadersIteration:
  7426. for (defHeaderName in defHeaders) {
  7427. lowercaseDefHeaderName = lowercase(defHeaderName);
  7428. for (reqHeaderName in reqHeaders) {
  7429. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7430. continue defaultHeadersIteration;
  7431. }
  7432. }
  7433. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7434. }
  7435. // execute if header value is a function for merged headers
  7436. execHeaders(reqHeaders);
  7437. return reqHeaders;
  7438. function execHeaders(headers) {
  7439. var headerContent;
  7440. forEach(headers, function(headerFn, header) {
  7441. if (isFunction(headerFn)) {
  7442. headerContent = headerFn();
  7443. if (headerContent != null) {
  7444. headers[header] = headerContent;
  7445. } else {
  7446. delete headers[header];
  7447. }
  7448. }
  7449. });
  7450. }
  7451. }
  7452. }
  7453. $http.pendingRequests = [];
  7454. /**
  7455. * @ngdoc method
  7456. * @name $http#get
  7457. *
  7458. * @description
  7459. * Shortcut method to perform `GET` request.
  7460. *
  7461. * @param {string} url Relative or absolute URL specifying the destination of the request
  7462. * @param {Object=} config Optional configuration object
  7463. * @returns {HttpPromise} Future object
  7464. */
  7465. /**
  7466. * @ngdoc method
  7467. * @name $http#delete
  7468. *
  7469. * @description
  7470. * Shortcut method to perform `DELETE` request.
  7471. *
  7472. * @param {string} url Relative or absolute URL specifying the destination of the request
  7473. * @param {Object=} config Optional configuration object
  7474. * @returns {HttpPromise} Future object
  7475. */
  7476. /**
  7477. * @ngdoc method
  7478. * @name $http#head
  7479. *
  7480. * @description
  7481. * Shortcut method to perform `HEAD` request.
  7482. *
  7483. * @param {string} url Relative or absolute URL specifying the destination of the request
  7484. * @param {Object=} config Optional configuration object
  7485. * @returns {HttpPromise} Future object
  7486. */
  7487. /**
  7488. * @ngdoc method
  7489. * @name $http#jsonp
  7490. *
  7491. * @description
  7492. * Shortcut method to perform `JSONP` request.
  7493. *
  7494. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7495. * The name of the callback should be the string `JSON_CALLBACK`.
  7496. * @param {Object=} config Optional configuration object
  7497. * @returns {HttpPromise} Future object
  7498. */
  7499. createShortMethods('get', 'delete', 'head', 'jsonp');
  7500. /**
  7501. * @ngdoc method
  7502. * @name $http#post
  7503. *
  7504. * @description
  7505. * Shortcut method to perform `POST` request.
  7506. *
  7507. * @param {string} url Relative or absolute URL specifying the destination of the request
  7508. * @param {*} data Request content
  7509. * @param {Object=} config Optional configuration object
  7510. * @returns {HttpPromise} Future object
  7511. */
  7512. /**
  7513. * @ngdoc method
  7514. * @name $http#put
  7515. *
  7516. * @description
  7517. * Shortcut method to perform `PUT` request.
  7518. *
  7519. * @param {string} url Relative or absolute URL specifying the destination of the request
  7520. * @param {*} data Request content
  7521. * @param {Object=} config Optional configuration object
  7522. * @returns {HttpPromise} Future object
  7523. */
  7524. /**
  7525. * @ngdoc method
  7526. * @name $http#patch
  7527. *
  7528. * @description
  7529. * Shortcut method to perform `PATCH` request.
  7530. *
  7531. * @param {string} url Relative or absolute URL specifying the destination of the request
  7532. * @param {*} data Request content
  7533. * @param {Object=} config Optional configuration object
  7534. * @returns {HttpPromise} Future object
  7535. */
  7536. createShortMethodsWithData('post', 'put', 'patch');
  7537. /**
  7538. * @ngdoc property
  7539. * @name $http#defaults
  7540. *
  7541. * @description
  7542. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7543. * default headers, withCredentials as well as request and response transformations.
  7544. *
  7545. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7546. */
  7547. $http.defaults = defaults;
  7548. return $http;
  7549. function createShortMethods(names) {
  7550. forEach(arguments, function(name) {
  7551. $http[name] = function(url, config) {
  7552. return $http(extend(config || {}, {
  7553. method: name,
  7554. url: url
  7555. }));
  7556. };
  7557. });
  7558. }
  7559. function createShortMethodsWithData(name) {
  7560. forEach(arguments, function(name) {
  7561. $http[name] = function(url, data, config) {
  7562. return $http(extend(config || {}, {
  7563. method: name,
  7564. url: url,
  7565. data: data
  7566. }));
  7567. };
  7568. });
  7569. }
  7570. /**
  7571. * Makes the request.
  7572. *
  7573. * !!! ACCESSES CLOSURE VARS:
  7574. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7575. */
  7576. function sendReq(config, reqData, reqHeaders) {
  7577. var deferred = $q.defer(),
  7578. promise = deferred.promise,
  7579. cache,
  7580. cachedResp,
  7581. url = buildUrl(config.url, config.params);
  7582. $http.pendingRequests.push(config);
  7583. promise.then(removePendingReq, removePendingReq);
  7584. if ((config.cache || defaults.cache) && config.cache !== false &&
  7585. (config.method === 'GET' || config.method === 'JSONP')) {
  7586. cache = isObject(config.cache) ? config.cache
  7587. : isObject(defaults.cache) ? defaults.cache
  7588. : defaultCache;
  7589. }
  7590. if (cache) {
  7591. cachedResp = cache.get(url);
  7592. if (isDefined(cachedResp)) {
  7593. if (isPromiseLike(cachedResp)) {
  7594. // cached request has already been sent, but there is no response yet
  7595. cachedResp.then(removePendingReq, removePendingReq);
  7596. return cachedResp;
  7597. } else {
  7598. // serving from cache
  7599. if (isArray(cachedResp)) {
  7600. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  7601. } else {
  7602. resolvePromise(cachedResp, 200, {}, 'OK');
  7603. }
  7604. }
  7605. } else {
  7606. // put the promise for the non-transformed response into cache as a placeholder
  7607. cache.put(url, promise);
  7608. }
  7609. }
  7610. // if we won't have the response in cache, set the xsrf headers and
  7611. // send the request to the backend
  7612. if (isUndefined(cachedResp)) {
  7613. var xsrfValue = urlIsSameOrigin(config.url)
  7614. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7615. : undefined;
  7616. if (xsrfValue) {
  7617. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7618. }
  7619. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7620. config.withCredentials, config.responseType);
  7621. }
  7622. return promise;
  7623. /**
  7624. * Callback registered to $httpBackend():
  7625. * - caches the response if desired
  7626. * - resolves the raw $http promise
  7627. * - calls $apply
  7628. */
  7629. function done(status, response, headersString, statusText) {
  7630. if (cache) {
  7631. if (isSuccess(status)) {
  7632. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7633. } else {
  7634. // remove promise from the cache
  7635. cache.remove(url);
  7636. }
  7637. }
  7638. resolvePromise(response, status, headersString, statusText);
  7639. if (!$rootScope.$$phase) $rootScope.$apply();
  7640. }
  7641. /**
  7642. * Resolves the raw $http promise.
  7643. */
  7644. function resolvePromise(response, status, headers, statusText) {
  7645. // normalize internal statuses to 0
  7646. status = Math.max(status, 0);
  7647. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7648. data: response,
  7649. status: status,
  7650. headers: headersGetter(headers),
  7651. config: config,
  7652. statusText : statusText
  7653. });
  7654. }
  7655. function removePendingReq() {
  7656. var idx = indexOf($http.pendingRequests, config);
  7657. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7658. }
  7659. }
  7660. function buildUrl(url, params) {
  7661. if (!params) return url;
  7662. var parts = [];
  7663. forEachSorted(params, function(value, key) {
  7664. if (value === null || isUndefined(value)) return;
  7665. if (!isArray(value)) value = [value];
  7666. forEach(value, function(v) {
  7667. if (isObject(v)) {
  7668. if (isDate(v)){
  7669. v = v.toISOString();
  7670. } else {
  7671. v = toJson(v);
  7672. }
  7673. }
  7674. parts.push(encodeUriQuery(key) + '=' +
  7675. encodeUriQuery(v));
  7676. });
  7677. });
  7678. if(parts.length > 0) {
  7679. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7680. }
  7681. return url;
  7682. }
  7683. }];
  7684. }
  7685. function createXhr(method) {
  7686. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7687. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7688. //if it is available
  7689. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7690. !window.XMLHttpRequest)) {
  7691. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7692. } else if (window.XMLHttpRequest) {
  7693. return new window.XMLHttpRequest();
  7694. }
  7695. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7696. }
  7697. /**
  7698. * @ngdoc service
  7699. * @name $httpBackend
  7700. * @requires $window
  7701. * @requires $document
  7702. *
  7703. * @description
  7704. * HTTP backend used by the {@link ng.$http service} that delegates to
  7705. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7706. *
  7707. * You should never need to use this service directly, instead use the higher-level abstractions:
  7708. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7709. *
  7710. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7711. * $httpBackend} which can be trained with responses.
  7712. */
  7713. function $HttpBackendProvider() {
  7714. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7715. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7716. }];
  7717. }
  7718. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7719. var ABORTED = -1;
  7720. // TODO(vojta): fix the signature
  7721. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7722. var status;
  7723. $browser.$$incOutstandingRequestCount();
  7724. url = url || $browser.url();
  7725. if (lowercase(method) == 'jsonp') {
  7726. var callbackId = '_' + (callbacks.counter++).toString(36);
  7727. callbacks[callbackId] = function(data) {
  7728. callbacks[callbackId].data = data;
  7729. callbacks[callbackId].called = true;
  7730. };
  7731. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7732. callbackId, function(status, text) {
  7733. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  7734. callbacks[callbackId] = noop;
  7735. });
  7736. } else {
  7737. var xhr = createXhr(method);
  7738. xhr.open(method, url, true);
  7739. forEach(headers, function(value, key) {
  7740. if (isDefined(value)) {
  7741. xhr.setRequestHeader(key, value);
  7742. }
  7743. });
  7744. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7745. // response is in the cache. the promise api will ensure that to the app code the api is
  7746. // always async
  7747. xhr.onreadystatechange = function() {
  7748. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7749. // xhrs that are resolved while the app is in the background (see #5426).
  7750. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7751. // continuing
  7752. //
  7753. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7754. // Safari respectively.
  7755. if (xhr && xhr.readyState == 4) {
  7756. var responseHeaders = null,
  7757. response = null,
  7758. statusText = '';
  7759. if(status !== ABORTED) {
  7760. responseHeaders = xhr.getAllResponseHeaders();
  7761. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7762. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7763. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7764. }
  7765. // Accessing statusText on an aborted xhr object will
  7766. // throw an 'c00c023f error' in IE9 and lower, don't touch it.
  7767. if (!(status === ABORTED && msie < 10)) {
  7768. statusText = xhr.statusText;
  7769. }
  7770. completeRequest(callback,
  7771. status || xhr.status,
  7772. response,
  7773. responseHeaders,
  7774. statusText);
  7775. }
  7776. };
  7777. if (withCredentials) {
  7778. xhr.withCredentials = true;
  7779. }
  7780. if (responseType) {
  7781. try {
  7782. xhr.responseType = responseType;
  7783. } catch (e) {
  7784. // WebKit added support for the json responseType value on 09/03/2013
  7785. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7786. // known to throw when setting the value "json" as the response type. Other older
  7787. // browsers implementing the responseType
  7788. //
  7789. // The json response type can be ignored if not supported, because JSON payloads are
  7790. // parsed on the client-side regardless.
  7791. if (responseType !== 'json') {
  7792. throw e;
  7793. }
  7794. }
  7795. }
  7796. xhr.send(post || null);
  7797. }
  7798. if (timeout > 0) {
  7799. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7800. } else if (isPromiseLike(timeout)) {
  7801. timeout.then(timeoutRequest);
  7802. }
  7803. function timeoutRequest() {
  7804. status = ABORTED;
  7805. jsonpDone && jsonpDone();
  7806. xhr && xhr.abort();
  7807. }
  7808. function completeRequest(callback, status, response, headersString, statusText) {
  7809. // cancel timeout and subsequent timeout promise resolution
  7810. timeoutId && $browserDefer.cancel(timeoutId);
  7811. jsonpDone = xhr = null;
  7812. // fix status code when it is 0 (0 status is undocumented).
  7813. // Occurs when accessing file resources or on Android 4.1 stock browser
  7814. // while retrieving files from application cache.
  7815. if (status === 0) {
  7816. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7817. }
  7818. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7819. status = status === 1223 ? 204 : status;
  7820. statusText = statusText || '';
  7821. callback(status, response, headersString, statusText);
  7822. $browser.$$completeOutstandingRequest(noop);
  7823. }
  7824. };
  7825. function jsonpReq(url, callbackId, done) {
  7826. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7827. // - fetches local scripts via XHR and evals them
  7828. // - adds and immediately removes script elements from the document
  7829. var script = rawDocument.createElement('script'), callback = null;
  7830. script.type = "text/javascript";
  7831. script.src = url;
  7832. script.async = true;
  7833. callback = function(event) {
  7834. removeEventListenerFn(script, "load", callback);
  7835. removeEventListenerFn(script, "error", callback);
  7836. rawDocument.body.removeChild(script);
  7837. script = null;
  7838. var status = -1;
  7839. var text = "unknown";
  7840. if (event) {
  7841. if (event.type === "load" && !callbacks[callbackId].called) {
  7842. event = { type: "error" };
  7843. }
  7844. text = event.type;
  7845. status = event.type === "error" ? 404 : 200;
  7846. }
  7847. if (done) {
  7848. done(status, text);
  7849. }
  7850. };
  7851. addEventListenerFn(script, "load", callback);
  7852. addEventListenerFn(script, "error", callback);
  7853. if (msie <= 8) {
  7854. script.onreadystatechange = function() {
  7855. if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) {
  7856. script.onreadystatechange = null;
  7857. callback({
  7858. type: 'load'
  7859. });
  7860. }
  7861. };
  7862. }
  7863. rawDocument.body.appendChild(script);
  7864. return callback;
  7865. }
  7866. }
  7867. var $interpolateMinErr = minErr('$interpolate');
  7868. /**
  7869. * @ngdoc provider
  7870. * @name $interpolateProvider
  7871. * @kind function
  7872. *
  7873. * @description
  7874. *
  7875. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7876. *
  7877. * @example
  7878. <example module="customInterpolationApp">
  7879. <file name="index.html">
  7880. <script>
  7881. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7882. customInterpolationApp.config(function($interpolateProvider) {
  7883. $interpolateProvider.startSymbol('//');
  7884. $interpolateProvider.endSymbol('//');
  7885. });
  7886. customInterpolationApp.controller('DemoController', function() {
  7887. this.label = "This binding is brought you by // interpolation symbols.";
  7888. });
  7889. </script>
  7890. <div ng-app="App" ng-controller="DemoController as demo">
  7891. //demo.label//
  7892. </div>
  7893. </file>
  7894. <file name="protractor.js" type="protractor">
  7895. it('should interpolate binding with custom symbols', function() {
  7896. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7897. });
  7898. </file>
  7899. </example>
  7900. */
  7901. function $InterpolateProvider() {
  7902. var startSymbol = '{{';
  7903. var endSymbol = '}}';
  7904. /**
  7905. * @ngdoc method
  7906. * @name $interpolateProvider#startSymbol
  7907. * @description
  7908. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7909. *
  7910. * @param {string=} value new value to set the starting symbol to.
  7911. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7912. */
  7913. this.startSymbol = function(value){
  7914. if (value) {
  7915. startSymbol = value;
  7916. return this;
  7917. } else {
  7918. return startSymbol;
  7919. }
  7920. };
  7921. /**
  7922. * @ngdoc method
  7923. * @name $interpolateProvider#endSymbol
  7924. * @description
  7925. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7926. *
  7927. * @param {string=} value new value to set the ending symbol to.
  7928. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7929. */
  7930. this.endSymbol = function(value){
  7931. if (value) {
  7932. endSymbol = value;
  7933. return this;
  7934. } else {
  7935. return endSymbol;
  7936. }
  7937. };
  7938. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7939. var startSymbolLength = startSymbol.length,
  7940. endSymbolLength = endSymbol.length;
  7941. /**
  7942. * @ngdoc service
  7943. * @name $interpolate
  7944. * @kind function
  7945. *
  7946. * @requires $parse
  7947. * @requires $sce
  7948. *
  7949. * @description
  7950. *
  7951. * Compiles a string with markup into an interpolation function. This service is used by the
  7952. * HTML {@link ng.$compile $compile} service for data binding. See
  7953. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7954. * interpolation markup.
  7955. *
  7956. *
  7957. * ```js
  7958. * var $interpolate = ...; // injected
  7959. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7960. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7961. * ```
  7962. *
  7963. *
  7964. * @param {string} text The text with markup to interpolate.
  7965. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7966. * embedded expression in order to return an interpolation function. Strings with no
  7967. * embedded expression will return null for the interpolation function.
  7968. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7969. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7970. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7971. * provides Strict Contextual Escaping for details.
  7972. * @returns {function(context)} an interpolation function which is used to compute the
  7973. * interpolated string. The function has these parameters:
  7974. *
  7975. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7976. * against.
  7977. *
  7978. */
  7979. function $interpolate(text, mustHaveExpression, trustedContext) {
  7980. var startIndex,
  7981. endIndex,
  7982. index = 0,
  7983. parts = [],
  7984. length = text.length,
  7985. hasInterpolation = false,
  7986. fn,
  7987. exp,
  7988. concat = [];
  7989. while(index < length) {
  7990. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7991. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7992. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7993. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7994. fn.exp = exp;
  7995. index = endIndex + endSymbolLength;
  7996. hasInterpolation = true;
  7997. } else {
  7998. // we did not find anything, so we have to add the remainder to the parts array
  7999. (index != length) && parts.push(text.substring(index));
  8000. index = length;
  8001. }
  8002. }
  8003. if (!(length = parts.length)) {
  8004. // we added, nothing, must have been an empty string.
  8005. parts.push('');
  8006. length = 1;
  8007. }
  8008. // Concatenating expressions makes it hard to reason about whether some combination of
  8009. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  8010. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  8011. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  8012. // make it obvious that you bound the value to some user controlled value. This helps reduce
  8013. // the load when auditing for XSS issues.
  8014. if (trustedContext && parts.length > 1) {
  8015. throw $interpolateMinErr('noconcat',
  8016. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  8017. "interpolations that concatenate multiple expressions when a trusted value is " +
  8018. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  8019. }
  8020. if (!mustHaveExpression || hasInterpolation) {
  8021. concat.length = length;
  8022. fn = function(context) {
  8023. try {
  8024. for(var i = 0, ii = length, part; i<ii; i++) {
  8025. if (typeof (part = parts[i]) == 'function') {
  8026. part = part(context);
  8027. if (trustedContext) {
  8028. part = $sce.getTrusted(trustedContext, part);
  8029. } else {
  8030. part = $sce.valueOf(part);
  8031. }
  8032. if (part == null) { // null || undefined
  8033. part = '';
  8034. } else {
  8035. switch (typeof part) {
  8036. case 'string':
  8037. {
  8038. break;
  8039. }
  8040. case 'number':
  8041. {
  8042. part = '' + part;
  8043. break;
  8044. }
  8045. default:
  8046. {
  8047. part = toJson(part);
  8048. }
  8049. }
  8050. }
  8051. }
  8052. concat[i] = part;
  8053. }
  8054. return concat.join('');
  8055. }
  8056. catch(err) {
  8057. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  8058. err.toString());
  8059. $exceptionHandler(newErr);
  8060. }
  8061. };
  8062. fn.exp = text;
  8063. fn.parts = parts;
  8064. return fn;
  8065. }
  8066. }
  8067. /**
  8068. * @ngdoc method
  8069. * @name $interpolate#startSymbol
  8070. * @description
  8071. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  8072. *
  8073. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  8074. * the symbol.
  8075. *
  8076. * @returns {string} start symbol.
  8077. */
  8078. $interpolate.startSymbol = function() {
  8079. return startSymbol;
  8080. };
  8081. /**
  8082. * @ngdoc method
  8083. * @name $interpolate#endSymbol
  8084. * @description
  8085. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8086. *
  8087. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  8088. * the symbol.
  8089. *
  8090. * @returns {string} end symbol.
  8091. */
  8092. $interpolate.endSymbol = function() {
  8093. return endSymbol;
  8094. };
  8095. return $interpolate;
  8096. }];
  8097. }
  8098. function $IntervalProvider() {
  8099. this.$get = ['$rootScope', '$window', '$q',
  8100. function($rootScope, $window, $q) {
  8101. var intervals = {};
  8102. /**
  8103. * @ngdoc service
  8104. * @name $interval
  8105. *
  8106. * @description
  8107. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  8108. * milliseconds.
  8109. *
  8110. * The return value of registering an interval function is a promise. This promise will be
  8111. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  8112. * run indefinitely if `count` is not defined. The value of the notification will be the
  8113. * number of iterations that have run.
  8114. * To cancel an interval, call `$interval.cancel(promise)`.
  8115. *
  8116. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  8117. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  8118. * time.
  8119. *
  8120. * <div class="alert alert-warning">
  8121. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  8122. * with them. In particular they are not automatically destroyed when a controller's scope or a
  8123. * directive's element are destroyed.
  8124. * You should take this into consideration and make sure to always cancel the interval at the
  8125. * appropriate moment. See the example below for more details on how and when to do this.
  8126. * </div>
  8127. *
  8128. * @param {function()} fn A function that should be called repeatedly.
  8129. * @param {number} delay Number of milliseconds between each function call.
  8130. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  8131. * indefinitely.
  8132. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  8133. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  8134. * @returns {promise} A promise which will be notified on each iteration.
  8135. *
  8136. * @example
  8137. * <example module="intervalExample">
  8138. * <file name="index.html">
  8139. * <script>
  8140. * angular.module('intervalExample', [])
  8141. * .controller('ExampleController', ['$scope', '$interval',
  8142. * function($scope, $interval) {
  8143. * $scope.format = 'M/d/yy h:mm:ss a';
  8144. * $scope.blood_1 = 100;
  8145. * $scope.blood_2 = 120;
  8146. *
  8147. * var stop;
  8148. * $scope.fight = function() {
  8149. * // Don't start a new fight if we are already fighting
  8150. * if ( angular.isDefined(stop) ) return;
  8151. *
  8152. * stop = $interval(function() {
  8153. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  8154. * $scope.blood_1 = $scope.blood_1 - 3;
  8155. * $scope.blood_2 = $scope.blood_2 - 4;
  8156. * } else {
  8157. * $scope.stopFight();
  8158. * }
  8159. * }, 100);
  8160. * };
  8161. *
  8162. * $scope.stopFight = function() {
  8163. * if (angular.isDefined(stop)) {
  8164. * $interval.cancel(stop);
  8165. * stop = undefined;
  8166. * }
  8167. * };
  8168. *
  8169. * $scope.resetFight = function() {
  8170. * $scope.blood_1 = 100;
  8171. * $scope.blood_2 = 120;
  8172. * };
  8173. *
  8174. * $scope.$on('$destroy', function() {
  8175. * // Make sure that the interval is destroyed too
  8176. * $scope.stopFight();
  8177. * });
  8178. * }])
  8179. * // Register the 'myCurrentTime' directive factory method.
  8180. * // We inject $interval and dateFilter service since the factory method is DI.
  8181. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  8182. * function($interval, dateFilter) {
  8183. * // return the directive link function. (compile function not needed)
  8184. * return function(scope, element, attrs) {
  8185. * var format, // date format
  8186. * stopTime; // so that we can cancel the time updates
  8187. *
  8188. * // used to update the UI
  8189. * function updateTime() {
  8190. * element.text(dateFilter(new Date(), format));
  8191. * }
  8192. *
  8193. * // watch the expression, and update the UI on change.
  8194. * scope.$watch(attrs.myCurrentTime, function(value) {
  8195. * format = value;
  8196. * updateTime();
  8197. * });
  8198. *
  8199. * stopTime = $interval(updateTime, 1000);
  8200. *
  8201. * // listen on DOM destroy (removal) event, and cancel the next UI update
  8202. * // to prevent updating time after the DOM element was removed.
  8203. * element.bind('$destroy', function() {
  8204. * $interval.cancel(stopTime);
  8205. * });
  8206. * }
  8207. * }]);
  8208. * </script>
  8209. *
  8210. * <div>
  8211. * <div ng-controller="ExampleController">
  8212. * Date format: <input ng-model="format"> <hr/>
  8213. * Current time is: <span my-current-time="format"></span>
  8214. * <hr/>
  8215. * Blood 1 : <font color='red'>{{blood_1}}</font>
  8216. * Blood 2 : <font color='red'>{{blood_2}}</font>
  8217. * <button type="button" data-ng-click="fight()">Fight</button>
  8218. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  8219. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  8220. * </div>
  8221. * </div>
  8222. *
  8223. * </file>
  8224. * </example>
  8225. */
  8226. function interval(fn, delay, count, invokeApply) {
  8227. var setInterval = $window.setInterval,
  8228. clearInterval = $window.clearInterval,
  8229. deferred = $q.defer(),
  8230. promise = deferred.promise,
  8231. iteration = 0,
  8232. skipApply = (isDefined(invokeApply) && !invokeApply);
  8233. count = isDefined(count) ? count : 0;
  8234. promise.then(null, null, fn);
  8235. promise.$$intervalId = setInterval(function tick() {
  8236. deferred.notify(iteration++);
  8237. if (count > 0 && iteration >= count) {
  8238. deferred.resolve(iteration);
  8239. clearInterval(promise.$$intervalId);
  8240. delete intervals[promise.$$intervalId];
  8241. }
  8242. if (!skipApply) $rootScope.$apply();
  8243. }, delay);
  8244. intervals[promise.$$intervalId] = deferred;
  8245. return promise;
  8246. }
  8247. /**
  8248. * @ngdoc method
  8249. * @name $interval#cancel
  8250. *
  8251. * @description
  8252. * Cancels a task associated with the `promise`.
  8253. *
  8254. * @param {promise} promise returned by the `$interval` function.
  8255. * @returns {boolean} Returns `true` if the task was successfully canceled.
  8256. */
  8257. interval.cancel = function(promise) {
  8258. if (promise && promise.$$intervalId in intervals) {
  8259. intervals[promise.$$intervalId].reject('canceled');
  8260. $window.clearInterval(promise.$$intervalId);
  8261. delete intervals[promise.$$intervalId];
  8262. return true;
  8263. }
  8264. return false;
  8265. };
  8266. return interval;
  8267. }];
  8268. }
  8269. /**
  8270. * @ngdoc service
  8271. * @name $locale
  8272. *
  8273. * @description
  8274. * $locale service provides localization rules for various Angular components. As of right now the
  8275. * only public api is:
  8276. *
  8277. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8278. */
  8279. function $LocaleProvider(){
  8280. this.$get = function() {
  8281. return {
  8282. id: 'en-us',
  8283. NUMBER_FORMATS: {
  8284. DECIMAL_SEP: '.',
  8285. GROUP_SEP: ',',
  8286. PATTERNS: [
  8287. { // Decimal Pattern
  8288. minInt: 1,
  8289. minFrac: 0,
  8290. maxFrac: 3,
  8291. posPre: '',
  8292. posSuf: '',
  8293. negPre: '-',
  8294. negSuf: '',
  8295. gSize: 3,
  8296. lgSize: 3
  8297. },{ //Currency Pattern
  8298. minInt: 1,
  8299. minFrac: 2,
  8300. maxFrac: 2,
  8301. posPre: '\u00A4',
  8302. posSuf: '',
  8303. negPre: '(\u00A4',
  8304. negSuf: ')',
  8305. gSize: 3,
  8306. lgSize: 3
  8307. }
  8308. ],
  8309. CURRENCY_SYM: '$'
  8310. },
  8311. DATETIME_FORMATS: {
  8312. MONTH:
  8313. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8314. .split(','),
  8315. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8316. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8317. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8318. AMPMS: ['AM','PM'],
  8319. medium: 'MMM d, y h:mm:ss a',
  8320. short: 'M/d/yy h:mm a',
  8321. fullDate: 'EEEE, MMMM d, y',
  8322. longDate: 'MMMM d, y',
  8323. mediumDate: 'MMM d, y',
  8324. shortDate: 'M/d/yy',
  8325. mediumTime: 'h:mm:ss a',
  8326. shortTime: 'h:mm a'
  8327. },
  8328. pluralCat: function(num) {
  8329. if (num === 1) {
  8330. return 'one';
  8331. }
  8332. return 'other';
  8333. }
  8334. };
  8335. };
  8336. }
  8337. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8338. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8339. var $locationMinErr = minErr('$location');
  8340. /**
  8341. * Encode path using encodeUriSegment, ignoring forward slashes
  8342. *
  8343. * @param {string} path Path to encode
  8344. * @returns {string}
  8345. */
  8346. function encodePath(path) {
  8347. var segments = path.split('/'),
  8348. i = segments.length;
  8349. while (i--) {
  8350. segments[i] = encodeUriSegment(segments[i]);
  8351. }
  8352. return segments.join('/');
  8353. }
  8354. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8355. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8356. locationObj.$$protocol = parsedUrl.protocol;
  8357. locationObj.$$host = parsedUrl.hostname;
  8358. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8359. }
  8360. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8361. var prefixed = (relativeUrl.charAt(0) !== '/');
  8362. if (prefixed) {
  8363. relativeUrl = '/' + relativeUrl;
  8364. }
  8365. var match = urlResolve(relativeUrl, appBase);
  8366. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8367. match.pathname.substring(1) : match.pathname);
  8368. locationObj.$$search = parseKeyValue(match.search);
  8369. locationObj.$$hash = decodeURIComponent(match.hash);
  8370. // make sure path starts with '/';
  8371. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8372. locationObj.$$path = '/' + locationObj.$$path;
  8373. }
  8374. }
  8375. /**
  8376. *
  8377. * @param {string} begin
  8378. * @param {string} whole
  8379. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8380. * expected string.
  8381. */
  8382. function beginsWith(begin, whole) {
  8383. if (whole.indexOf(begin) === 0) {
  8384. return whole.substr(begin.length);
  8385. }
  8386. }
  8387. function stripHash(url) {
  8388. var index = url.indexOf('#');
  8389. return index == -1 ? url : url.substr(0, index);
  8390. }
  8391. function stripFile(url) {
  8392. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8393. }
  8394. /* return the server only (scheme://host:port) */
  8395. function serverBase(url) {
  8396. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8397. }
  8398. /**
  8399. * LocationHtml5Url represents an url
  8400. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8401. *
  8402. * @constructor
  8403. * @param {string} appBase application base URL
  8404. * @param {string} basePrefix url path prefix
  8405. */
  8406. function LocationHtml5Url(appBase, basePrefix) {
  8407. this.$$html5 = true;
  8408. basePrefix = basePrefix || '';
  8409. var appBaseNoFile = stripFile(appBase);
  8410. parseAbsoluteUrl(appBase, this, appBase);
  8411. /**
  8412. * Parse given html5 (regular) url string into properties
  8413. * @param {string} newAbsoluteUrl HTML5 url
  8414. * @private
  8415. */
  8416. this.$$parse = function(url) {
  8417. var pathUrl = beginsWith(appBaseNoFile, url);
  8418. if (!isString(pathUrl)) {
  8419. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8420. appBaseNoFile);
  8421. }
  8422. parseAppUrl(pathUrl, this, appBase);
  8423. if (!this.$$path) {
  8424. this.$$path = '/';
  8425. }
  8426. this.$$compose();
  8427. };
  8428. /**
  8429. * Compose url and update `absUrl` property
  8430. * @private
  8431. */
  8432. this.$$compose = function() {
  8433. var search = toKeyValue(this.$$search),
  8434. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8435. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8436. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8437. };
  8438. this.$$parseLinkUrl = function(url, relHref) {
  8439. var appUrl, prevAppUrl;
  8440. var rewrittenUrl;
  8441. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8442. prevAppUrl = appUrl;
  8443. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8444. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8445. } else {
  8446. rewrittenUrl = appBase + prevAppUrl;
  8447. }
  8448. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8449. rewrittenUrl = appBaseNoFile + appUrl;
  8450. } else if (appBaseNoFile == url + '/') {
  8451. rewrittenUrl = appBaseNoFile;
  8452. }
  8453. if (rewrittenUrl) {
  8454. this.$$parse(rewrittenUrl);
  8455. }
  8456. return !!rewrittenUrl;
  8457. };
  8458. }
  8459. /**
  8460. * LocationHashbangUrl represents url
  8461. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8462. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8463. *
  8464. * @constructor
  8465. * @param {string} appBase application base URL
  8466. * @param {string} hashPrefix hashbang prefix
  8467. */
  8468. function LocationHashbangUrl(appBase, hashPrefix) {
  8469. var appBaseNoFile = stripFile(appBase);
  8470. parseAbsoluteUrl(appBase, this, appBase);
  8471. /**
  8472. * Parse given hashbang url into properties
  8473. * @param {string} url Hashbang url
  8474. * @private
  8475. */
  8476. this.$$parse = function(url) {
  8477. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8478. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8479. ? beginsWith(hashPrefix, withoutBaseUrl)
  8480. : (this.$$html5)
  8481. ? withoutBaseUrl
  8482. : '';
  8483. if (!isString(withoutHashUrl)) {
  8484. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8485. hashPrefix);
  8486. }
  8487. parseAppUrl(withoutHashUrl, this, appBase);
  8488. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8489. this.$$compose();
  8490. /*
  8491. * In Windows, on an anchor node on documents loaded from
  8492. * the filesystem, the browser will return a pathname
  8493. * prefixed with the drive name ('/C:/path') when a
  8494. * pathname without a drive is set:
  8495. * * a.setAttribute('href', '/foo')
  8496. * * a.pathname === '/C:/foo' //true
  8497. *
  8498. * Inside of Angular, we're always using pathnames that
  8499. * do not include drive names for routing.
  8500. */
  8501. function removeWindowsDriveName (path, url, base) {
  8502. /*
  8503. Matches paths for file protocol on windows,
  8504. such as /C:/foo/bar, and captures only /foo/bar.
  8505. */
  8506. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  8507. var firstPathSegmentMatch;
  8508. //Get the relative path from the input URL.
  8509. if (url.indexOf(base) === 0) {
  8510. url = url.replace(base, '');
  8511. }
  8512. // The input URL intentionally contains a first path segment that ends with a colon.
  8513. if (windowsFilePathExp.exec(url)) {
  8514. return path;
  8515. }
  8516. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8517. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8518. }
  8519. };
  8520. /**
  8521. * Compose hashbang url and update `absUrl` property
  8522. * @private
  8523. */
  8524. this.$$compose = function() {
  8525. var search = toKeyValue(this.$$search),
  8526. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8527. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8528. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8529. };
  8530. this.$$parseLinkUrl = function(url, relHref) {
  8531. if(stripHash(appBase) == stripHash(url)) {
  8532. this.$$parse(url);
  8533. return true;
  8534. }
  8535. return false;
  8536. };
  8537. }
  8538. /**
  8539. * LocationHashbangUrl represents url
  8540. * This object is exposed as $location service when html5 history api is enabled but the browser
  8541. * does not support it.
  8542. *
  8543. * @constructor
  8544. * @param {string} appBase application base URL
  8545. * @param {string} hashPrefix hashbang prefix
  8546. */
  8547. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8548. this.$$html5 = true;
  8549. LocationHashbangUrl.apply(this, arguments);
  8550. var appBaseNoFile = stripFile(appBase);
  8551. this.$$parseLinkUrl = function(url, relHref) {
  8552. var rewrittenUrl;
  8553. var appUrl;
  8554. if ( appBase == stripHash(url) ) {
  8555. rewrittenUrl = url;
  8556. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8557. rewrittenUrl = appBase + hashPrefix + appUrl;
  8558. } else if ( appBaseNoFile === url + '/') {
  8559. rewrittenUrl = appBaseNoFile;
  8560. }
  8561. if (rewrittenUrl) {
  8562. this.$$parse(rewrittenUrl);
  8563. }
  8564. return !!rewrittenUrl;
  8565. };
  8566. this.$$compose = function() {
  8567. var search = toKeyValue(this.$$search),
  8568. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8569. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8570. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  8571. this.$$absUrl = appBase + hashPrefix + this.$$url;
  8572. };
  8573. }
  8574. LocationHashbangInHtml5Url.prototype =
  8575. LocationHashbangUrl.prototype =
  8576. LocationHtml5Url.prototype = {
  8577. /**
  8578. * Are we in html5 mode?
  8579. * @private
  8580. */
  8581. $$html5: false,
  8582. /**
  8583. * Has any change been replacing ?
  8584. * @private
  8585. */
  8586. $$replace: false,
  8587. /**
  8588. * @ngdoc method
  8589. * @name $location#absUrl
  8590. *
  8591. * @description
  8592. * This method is getter only.
  8593. *
  8594. * Return full url representation with all segments encoded according to rules specified in
  8595. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8596. *
  8597. * @return {string} full url
  8598. */
  8599. absUrl: locationGetter('$$absUrl'),
  8600. /**
  8601. * @ngdoc method
  8602. * @name $location#url
  8603. *
  8604. * @description
  8605. * This method is getter / setter.
  8606. *
  8607. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8608. *
  8609. * Change path, search and hash, when called with parameter and return `$location`.
  8610. *
  8611. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8612. * @return {string} url
  8613. */
  8614. url: function(url) {
  8615. if (isUndefined(url))
  8616. return this.$$url;
  8617. var match = PATH_MATCH.exec(url);
  8618. if (match[1]) this.path(decodeURIComponent(match[1]));
  8619. if (match[2] || match[1]) this.search(match[3] || '');
  8620. this.hash(match[5] || '');
  8621. return this;
  8622. },
  8623. /**
  8624. * @ngdoc method
  8625. * @name $location#protocol
  8626. *
  8627. * @description
  8628. * This method is getter only.
  8629. *
  8630. * Return protocol of current url.
  8631. *
  8632. * @return {string} protocol of current url
  8633. */
  8634. protocol: locationGetter('$$protocol'),
  8635. /**
  8636. * @ngdoc method
  8637. * @name $location#host
  8638. *
  8639. * @description
  8640. * This method is getter only.
  8641. *
  8642. * Return host of current url.
  8643. *
  8644. * @return {string} host of current url.
  8645. */
  8646. host: locationGetter('$$host'),
  8647. /**
  8648. * @ngdoc method
  8649. * @name $location#port
  8650. *
  8651. * @description
  8652. * This method is getter only.
  8653. *
  8654. * Return port of current url.
  8655. *
  8656. * @return {Number} port
  8657. */
  8658. port: locationGetter('$$port'),
  8659. /**
  8660. * @ngdoc method
  8661. * @name $location#path
  8662. *
  8663. * @description
  8664. * This method is getter / setter.
  8665. *
  8666. * Return path of current url when called without any parameter.
  8667. *
  8668. * Change path when called with parameter and return `$location`.
  8669. *
  8670. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8671. * if it is missing.
  8672. *
  8673. * @param {(string|number)=} path New path
  8674. * @return {string} path
  8675. */
  8676. path: locationGetterSetter('$$path', function(path) {
  8677. path = path !== null ? path.toString() : '';
  8678. return path.charAt(0) == '/' ? path : '/' + path;
  8679. }),
  8680. /**
  8681. * @ngdoc method
  8682. * @name $location#search
  8683. *
  8684. * @description
  8685. * This method is getter / setter.
  8686. *
  8687. * Return search part (as object) of current url when called without any parameter.
  8688. *
  8689. * Change search part when called with parameter and return `$location`.
  8690. *
  8691. *
  8692. * ```js
  8693. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  8694. * var searchObject = $location.search();
  8695. * // => {foo: 'bar', baz: 'xoxo'}
  8696. *
  8697. *
  8698. * // set foo to 'yipee'
  8699. * $location.search('foo', 'yipee');
  8700. * // => $location
  8701. * ```
  8702. *
  8703. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8704. * hash object.
  8705. *
  8706. * When called with a single argument the method acts as a setter, setting the `search` component
  8707. * of `$location` to the specified value.
  8708. *
  8709. * If the argument is a hash object containing an array of values, these values will be encoded
  8710. * as duplicate search parameters in the url.
  8711. *
  8712. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  8713. * will override only a single search property.
  8714. *
  8715. * If `paramValue` is an array, it will override the property of the `search` component of
  8716. * `$location` specified via the first argument.
  8717. *
  8718. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  8719. *
  8720. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  8721. * value nor trailing equal sign.
  8722. *
  8723. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  8724. * one or more arguments returns `$location` object itself.
  8725. */
  8726. search: function(search, paramValue) {
  8727. switch (arguments.length) {
  8728. case 0:
  8729. return this.$$search;
  8730. case 1:
  8731. if (isString(search) || isNumber(search)) {
  8732. search = search.toString();
  8733. this.$$search = parseKeyValue(search);
  8734. } else if (isObject(search)) {
  8735. // remove object undefined or null properties
  8736. forEach(search, function(value, key) {
  8737. if (value == null) delete search[key];
  8738. });
  8739. this.$$search = search;
  8740. } else {
  8741. throw $locationMinErr('isrcharg',
  8742. 'The first argument of the `$location#search()` call must be a string or an object.');
  8743. }
  8744. break;
  8745. default:
  8746. if (isUndefined(paramValue) || paramValue === null) {
  8747. delete this.$$search[search];
  8748. } else {
  8749. this.$$search[search] = paramValue;
  8750. }
  8751. }
  8752. this.$$compose();
  8753. return this;
  8754. },
  8755. /**
  8756. * @ngdoc method
  8757. * @name $location#hash
  8758. *
  8759. * @description
  8760. * This method is getter / setter.
  8761. *
  8762. * Return hash fragment when called without any parameter.
  8763. *
  8764. * Change hash fragment when called with parameter and return `$location`.
  8765. *
  8766. * @param {(string|number)=} hash New hash fragment
  8767. * @return {string} hash
  8768. */
  8769. hash: locationGetterSetter('$$hash', function(hash) {
  8770. return hash !== null ? hash.toString() : '';
  8771. }),
  8772. /**
  8773. * @ngdoc method
  8774. * @name $location#replace
  8775. *
  8776. * @description
  8777. * If called, all changes to $location during current `$digest` will be replacing current history
  8778. * record, instead of adding new one.
  8779. */
  8780. replace: function() {
  8781. this.$$replace = true;
  8782. return this;
  8783. }
  8784. };
  8785. function locationGetter(property) {
  8786. return function() {
  8787. return this[property];
  8788. };
  8789. }
  8790. function locationGetterSetter(property, preprocess) {
  8791. return function(value) {
  8792. if (isUndefined(value))
  8793. return this[property];
  8794. this[property] = preprocess(value);
  8795. this.$$compose();
  8796. return this;
  8797. };
  8798. }
  8799. /**
  8800. * @ngdoc service
  8801. * @name $location
  8802. *
  8803. * @requires $rootElement
  8804. *
  8805. * @description
  8806. * The $location service parses the URL in the browser address bar (based on the
  8807. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8808. * available to your application. Changes to the URL in the address bar are reflected into
  8809. * $location service and changes to $location are reflected into the browser address bar.
  8810. *
  8811. * **The $location service:**
  8812. *
  8813. * - Exposes the current URL in the browser address bar, so you can
  8814. * - Watch and observe the URL.
  8815. * - Change the URL.
  8816. * - Synchronizes the URL with the browser when the user
  8817. * - Changes the address bar.
  8818. * - Clicks the back or forward button (or clicks a History link).
  8819. * - Clicks on a link.
  8820. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8821. *
  8822. * For more information see {@link guide/$location Developer Guide: Using $location}
  8823. */
  8824. /**
  8825. * @ngdoc provider
  8826. * @name $locationProvider
  8827. * @description
  8828. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8829. */
  8830. function $LocationProvider(){
  8831. var hashPrefix = '',
  8832. html5Mode = false;
  8833. /**
  8834. * @ngdoc method
  8835. * @name $locationProvider#hashPrefix
  8836. * @description
  8837. * @param {string=} prefix Prefix for hash part (containing path and search)
  8838. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8839. */
  8840. this.hashPrefix = function(prefix) {
  8841. if (isDefined(prefix)) {
  8842. hashPrefix = prefix;
  8843. return this;
  8844. } else {
  8845. return hashPrefix;
  8846. }
  8847. };
  8848. /**
  8849. * @ngdoc method
  8850. * @name $locationProvider#html5Mode
  8851. * @description
  8852. * @param {boolean=} mode Use HTML5 strategy if available.
  8853. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8854. */
  8855. this.html5Mode = function(mode) {
  8856. if (isDefined(mode)) {
  8857. html5Mode = mode;
  8858. return this;
  8859. } else {
  8860. return html5Mode;
  8861. }
  8862. };
  8863. /**
  8864. * @ngdoc event
  8865. * @name $location#$locationChangeStart
  8866. * @eventType broadcast on root scope
  8867. * @description
  8868. * Broadcasted before a URL will change. This change can be prevented by calling
  8869. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8870. * details about event object. Upon successful change
  8871. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8872. *
  8873. * @param {Object} angularEvent Synthetic event object.
  8874. * @param {string} newUrl New URL
  8875. * @param {string=} oldUrl URL that was before it was changed.
  8876. */
  8877. /**
  8878. * @ngdoc event
  8879. * @name $location#$locationChangeSuccess
  8880. * @eventType broadcast on root scope
  8881. * @description
  8882. * Broadcasted after a URL was changed.
  8883. *
  8884. * @param {Object} angularEvent Synthetic event object.
  8885. * @param {string} newUrl New URL
  8886. * @param {string=} oldUrl URL that was before it was changed.
  8887. */
  8888. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8889. function( $rootScope, $browser, $sniffer, $rootElement) {
  8890. var $location,
  8891. LocationMode,
  8892. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8893. initialUrl = $browser.url(),
  8894. appBase;
  8895. if (html5Mode) {
  8896. appBase = serverBase(initialUrl) + (baseHref || '/');
  8897. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8898. } else {
  8899. appBase = stripHash(initialUrl);
  8900. LocationMode = LocationHashbangUrl;
  8901. }
  8902. $location = new LocationMode(appBase, '#' + hashPrefix);
  8903. $location.$$parseLinkUrl(initialUrl, initialUrl);
  8904. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  8905. $rootElement.on('click', function(event) {
  8906. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8907. // currently we open nice url link and redirect then
  8908. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8909. var elm = jqLite(event.target);
  8910. // traverse the DOM up to find first A tag
  8911. while (lowercase(elm[0].nodeName) !== 'a') {
  8912. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8913. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8914. }
  8915. var absHref = elm.prop('href');
  8916. // get the actual href attribute - see
  8917. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  8918. var relHref = elm.attr('href') || elm.attr('xlink:href');
  8919. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8920. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8921. // an animation.
  8922. absHref = urlResolve(absHref.animVal).href;
  8923. }
  8924. // Ignore when url is started with javascript: or mailto:
  8925. if (IGNORE_URI_REGEXP.test(absHref)) return;
  8926. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  8927. if ($location.$$parseLinkUrl(absHref, relHref)) {
  8928. // We do a preventDefault for all urls that are part of the angular application,
  8929. // in html5mode and also without, so that we are able to abort navigation without
  8930. // getting double entries in the location history.
  8931. event.preventDefault();
  8932. // update location manually
  8933. if ($location.absUrl() != $browser.url()) {
  8934. $rootScope.$apply();
  8935. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8936. window.angular['ff-684208-preventDefault'] = true;
  8937. }
  8938. }
  8939. }
  8940. });
  8941. // rewrite hashbang url <> html5 url
  8942. if ($location.absUrl() != initialUrl) {
  8943. $browser.url($location.absUrl(), true);
  8944. }
  8945. // update $location when $browser url changes
  8946. $browser.onUrlChange(function(newUrl) {
  8947. if ($location.absUrl() != newUrl) {
  8948. $rootScope.$evalAsync(function() {
  8949. var oldUrl = $location.absUrl();
  8950. $location.$$parse(newUrl);
  8951. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8952. oldUrl).defaultPrevented) {
  8953. $location.$$parse(oldUrl);
  8954. $browser.url(oldUrl);
  8955. } else {
  8956. afterLocationChange(oldUrl);
  8957. }
  8958. });
  8959. if (!$rootScope.$$phase) $rootScope.$digest();
  8960. }
  8961. });
  8962. // update browser
  8963. var changeCounter = 0;
  8964. $rootScope.$watch(function $locationWatch() {
  8965. var oldUrl = $browser.url();
  8966. var currentReplace = $location.$$replace;
  8967. if (!changeCounter || oldUrl != $location.absUrl()) {
  8968. changeCounter++;
  8969. $rootScope.$evalAsync(function() {
  8970. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8971. defaultPrevented) {
  8972. $location.$$parse(oldUrl);
  8973. } else {
  8974. $browser.url($location.absUrl(), currentReplace);
  8975. afterLocationChange(oldUrl);
  8976. }
  8977. });
  8978. }
  8979. $location.$$replace = false;
  8980. return changeCounter;
  8981. });
  8982. return $location;
  8983. function afterLocationChange(oldUrl) {
  8984. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8985. }
  8986. }];
  8987. }
  8988. /**
  8989. * @ngdoc service
  8990. * @name $log
  8991. * @requires $window
  8992. *
  8993. * @description
  8994. * Simple service for logging. Default implementation safely writes the message
  8995. * into the browser's console (if present).
  8996. *
  8997. * The main purpose of this service is to simplify debugging and troubleshooting.
  8998. *
  8999. * The default is to log `debug` messages. You can use
  9000. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  9001. *
  9002. * @example
  9003. <example module="logExample">
  9004. <file name="script.js">
  9005. angular.module('logExample', [])
  9006. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  9007. $scope.$log = $log;
  9008. $scope.message = 'Hello World!';
  9009. }]);
  9010. </file>
  9011. <file name="index.html">
  9012. <div ng-controller="LogController">
  9013. <p>Reload this page with open console, enter text and hit the log button...</p>
  9014. Message:
  9015. <input type="text" ng-model="message"/>
  9016. <button ng-click="$log.log(message)">log</button>
  9017. <button ng-click="$log.warn(message)">warn</button>
  9018. <button ng-click="$log.info(message)">info</button>
  9019. <button ng-click="$log.error(message)">error</button>
  9020. </div>
  9021. </file>
  9022. </example>
  9023. */
  9024. /**
  9025. * @ngdoc provider
  9026. * @name $logProvider
  9027. * @description
  9028. * Use the `$logProvider` to configure how the application logs messages
  9029. */
  9030. function $LogProvider(){
  9031. var debug = true,
  9032. self = this;
  9033. /**
  9034. * @ngdoc method
  9035. * @name $logProvider#debugEnabled
  9036. * @description
  9037. * @param {boolean=} flag enable or disable debug level messages
  9038. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9039. */
  9040. this.debugEnabled = function(flag) {
  9041. if (isDefined(flag)) {
  9042. debug = flag;
  9043. return this;
  9044. } else {
  9045. return debug;
  9046. }
  9047. };
  9048. this.$get = ['$window', function($window){
  9049. return {
  9050. /**
  9051. * @ngdoc method
  9052. * @name $log#log
  9053. *
  9054. * @description
  9055. * Write a log message
  9056. */
  9057. log: consoleLog('log'),
  9058. /**
  9059. * @ngdoc method
  9060. * @name $log#info
  9061. *
  9062. * @description
  9063. * Write an information message
  9064. */
  9065. info: consoleLog('info'),
  9066. /**
  9067. * @ngdoc method
  9068. * @name $log#warn
  9069. *
  9070. * @description
  9071. * Write a warning message
  9072. */
  9073. warn: consoleLog('warn'),
  9074. /**
  9075. * @ngdoc method
  9076. * @name $log#error
  9077. *
  9078. * @description
  9079. * Write an error message
  9080. */
  9081. error: consoleLog('error'),
  9082. /**
  9083. * @ngdoc method
  9084. * @name $log#debug
  9085. *
  9086. * @description
  9087. * Write a debug message
  9088. */
  9089. debug: (function () {
  9090. var fn = consoleLog('debug');
  9091. return function() {
  9092. if (debug) {
  9093. fn.apply(self, arguments);
  9094. }
  9095. };
  9096. }())
  9097. };
  9098. function formatError(arg) {
  9099. if (arg instanceof Error) {
  9100. if (arg.stack) {
  9101. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  9102. ? 'Error: ' + arg.message + '\n' + arg.stack
  9103. : arg.stack;
  9104. } else if (arg.sourceURL) {
  9105. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  9106. }
  9107. }
  9108. return arg;
  9109. }
  9110. function consoleLog(type) {
  9111. var console = $window.console || {},
  9112. logFn = console[type] || console.log || noop,
  9113. hasApply = false;
  9114. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  9115. // The reason behind this is that console.log has type "object" in IE8...
  9116. try {
  9117. hasApply = !!logFn.apply;
  9118. } catch (e) {}
  9119. if (hasApply) {
  9120. return function() {
  9121. var args = [];
  9122. forEach(arguments, function(arg) {
  9123. args.push(formatError(arg));
  9124. });
  9125. return logFn.apply(console, args);
  9126. };
  9127. }
  9128. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  9129. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  9130. return function(arg1, arg2) {
  9131. logFn(arg1, arg2 == null ? '' : arg2);
  9132. };
  9133. }
  9134. }];
  9135. }
  9136. var $parseMinErr = minErr('$parse');
  9137. var promiseWarningCache = {};
  9138. var promiseWarning;
  9139. // Sandboxing Angular Expressions
  9140. // ------------------------------
  9141. // Angular expressions are generally considered safe because these expressions only have direct
  9142. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  9143. // obtaining a reference to native JS functions such as the Function constructor.
  9144. //
  9145. // As an example, consider the following Angular expression:
  9146. //
  9147. // {}.toString.constructor('alert("evil JS code")')
  9148. //
  9149. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  9150. // against the expression language, but not to prevent exploits that were enabled by exposing
  9151. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  9152. // practice and therefore we are not even trying to protect against interaction with an object
  9153. // explicitly exposed in this way.
  9154. //
  9155. // In general, it is not possible to access a Window object from an angular expression unless a
  9156. // window or some DOM object that has a reference to window is published onto a Scope.
  9157. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  9158. // native objects.
  9159. //
  9160. // See https://docs.angularjs.org/guide/security
  9161. function ensureSafeMemberName(name, fullExpression) {
  9162. if (name === "__defineGetter__" || name === "__defineSetter__"
  9163. || name === "__lookupGetter__" || name === "__lookupSetter__"
  9164. || name === "__proto__") {
  9165. throw $parseMinErr('isecfld',
  9166. 'Attempting to access a disallowed field in Angular expressions! '
  9167. +'Expression: {0}', fullExpression);
  9168. }
  9169. return name;
  9170. }
  9171. function ensureSafeObject(obj, fullExpression) {
  9172. // nifty check if obj is Function that is fast and works across iframes and other contexts
  9173. if (obj) {
  9174. if (obj.constructor === obj) {
  9175. throw $parseMinErr('isecfn',
  9176. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9177. fullExpression);
  9178. } else if (// isWindow(obj)
  9179. obj.document && obj.location && obj.alert && obj.setInterval) {
  9180. throw $parseMinErr('isecwindow',
  9181. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  9182. fullExpression);
  9183. } else if (// isElement(obj)
  9184. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  9185. throw $parseMinErr('isecdom',
  9186. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  9187. fullExpression);
  9188. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  9189. obj === Object) {
  9190. throw $parseMinErr('isecobj',
  9191. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  9192. fullExpression);
  9193. }
  9194. }
  9195. return obj;
  9196. }
  9197. var CALL = Function.prototype.call;
  9198. var APPLY = Function.prototype.apply;
  9199. var BIND = Function.prototype.bind;
  9200. function ensureSafeFunction(obj, fullExpression) {
  9201. if (obj) {
  9202. if (obj.constructor === obj) {
  9203. throw $parseMinErr('isecfn',
  9204. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9205. fullExpression);
  9206. } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
  9207. throw $parseMinErr('isecff',
  9208. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  9209. fullExpression);
  9210. }
  9211. }
  9212. }
  9213. var OPERATORS = {
  9214. /* jshint bitwise : false */
  9215. 'null':function(){return null;},
  9216. 'true':function(){return true;},
  9217. 'false':function(){return false;},
  9218. undefined:noop,
  9219. '+':function(self, locals, a,b){
  9220. a=a(self, locals); b=b(self, locals);
  9221. if (isDefined(a)) {
  9222. if (isDefined(b)) {
  9223. return a + b;
  9224. }
  9225. return a;
  9226. }
  9227. return isDefined(b)?b:undefined;},
  9228. '-':function(self, locals, a,b){
  9229. a=a(self, locals); b=b(self, locals);
  9230. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  9231. },
  9232. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  9233. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  9234. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  9235. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  9236. '=':noop,
  9237. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  9238. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  9239. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  9240. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  9241. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  9242. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  9243. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  9244. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  9245. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  9246. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  9247. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  9248. // '|':function(self, locals, a,b){return a|b;},
  9249. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  9250. '!':function(self, locals, a){return !a(self, locals);}
  9251. };
  9252. /* jshint bitwise: true */
  9253. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  9254. /////////////////////////////////////////
  9255. /**
  9256. * @constructor
  9257. */
  9258. var Lexer = function (options) {
  9259. this.options = options;
  9260. };
  9261. Lexer.prototype = {
  9262. constructor: Lexer,
  9263. lex: function (text) {
  9264. this.text = text;
  9265. this.index = 0;
  9266. this.ch = undefined;
  9267. this.lastCh = ':'; // can start regexp
  9268. this.tokens = [];
  9269. while (this.index < this.text.length) {
  9270. this.ch = this.text.charAt(this.index);
  9271. if (this.is('"\'')) {
  9272. this.readString(this.ch);
  9273. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  9274. this.readNumber();
  9275. } else if (this.isIdent(this.ch)) {
  9276. this.readIdent();
  9277. } else if (this.is('(){}[].,;:?')) {
  9278. this.tokens.push({
  9279. index: this.index,
  9280. text: this.ch
  9281. });
  9282. this.index++;
  9283. } else if (this.isWhitespace(this.ch)) {
  9284. this.index++;
  9285. continue;
  9286. } else {
  9287. var ch2 = this.ch + this.peek();
  9288. var ch3 = ch2 + this.peek(2);
  9289. var fn = OPERATORS[this.ch];
  9290. var fn2 = OPERATORS[ch2];
  9291. var fn3 = OPERATORS[ch3];
  9292. if (fn3) {
  9293. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  9294. this.index += 3;
  9295. } else if (fn2) {
  9296. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  9297. this.index += 2;
  9298. } else if (fn) {
  9299. this.tokens.push({
  9300. index: this.index,
  9301. text: this.ch,
  9302. fn: fn
  9303. });
  9304. this.index += 1;
  9305. } else {
  9306. this.throwError('Unexpected next character ', this.index, this.index + 1);
  9307. }
  9308. }
  9309. this.lastCh = this.ch;
  9310. }
  9311. return this.tokens;
  9312. },
  9313. is: function(chars) {
  9314. return chars.indexOf(this.ch) !== -1;
  9315. },
  9316. was: function(chars) {
  9317. return chars.indexOf(this.lastCh) !== -1;
  9318. },
  9319. peek: function(i) {
  9320. var num = i || 1;
  9321. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  9322. },
  9323. isNumber: function(ch) {
  9324. return ('0' <= ch && ch <= '9');
  9325. },
  9326. isWhitespace: function(ch) {
  9327. // IE treats non-breaking space as \u00A0
  9328. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9329. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9330. },
  9331. isIdent: function(ch) {
  9332. return ('a' <= ch && ch <= 'z' ||
  9333. 'A' <= ch && ch <= 'Z' ||
  9334. '_' === ch || ch === '$');
  9335. },
  9336. isExpOperator: function(ch) {
  9337. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9338. },
  9339. throwError: function(error, start, end) {
  9340. end = end || this.index;
  9341. var colStr = (isDefined(start)
  9342. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9343. : ' ' + end);
  9344. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9345. error, colStr, this.text);
  9346. },
  9347. readNumber: function() {
  9348. var number = '';
  9349. var start = this.index;
  9350. while (this.index < this.text.length) {
  9351. var ch = lowercase(this.text.charAt(this.index));
  9352. if (ch == '.' || this.isNumber(ch)) {
  9353. number += ch;
  9354. } else {
  9355. var peekCh = this.peek();
  9356. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9357. number += ch;
  9358. } else if (this.isExpOperator(ch) &&
  9359. peekCh && this.isNumber(peekCh) &&
  9360. number.charAt(number.length - 1) == 'e') {
  9361. number += ch;
  9362. } else if (this.isExpOperator(ch) &&
  9363. (!peekCh || !this.isNumber(peekCh)) &&
  9364. number.charAt(number.length - 1) == 'e') {
  9365. this.throwError('Invalid exponent');
  9366. } else {
  9367. break;
  9368. }
  9369. }
  9370. this.index++;
  9371. }
  9372. number = 1 * number;
  9373. this.tokens.push({
  9374. index: start,
  9375. text: number,
  9376. literal: true,
  9377. constant: true,
  9378. fn: function() { return number; }
  9379. });
  9380. },
  9381. readIdent: function() {
  9382. var parser = this;
  9383. var ident = '';
  9384. var start = this.index;
  9385. var lastDot, peekIndex, methodName, ch;
  9386. while (this.index < this.text.length) {
  9387. ch = this.text.charAt(this.index);
  9388. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9389. if (ch === '.') lastDot = this.index;
  9390. ident += ch;
  9391. } else {
  9392. break;
  9393. }
  9394. this.index++;
  9395. }
  9396. //check if this is not a method invocation and if it is back out to last dot
  9397. if (lastDot) {
  9398. peekIndex = this.index;
  9399. while (peekIndex < this.text.length) {
  9400. ch = this.text.charAt(peekIndex);
  9401. if (ch === '(') {
  9402. methodName = ident.substr(lastDot - start + 1);
  9403. ident = ident.substr(0, lastDot - start);
  9404. this.index = peekIndex;
  9405. break;
  9406. }
  9407. if (this.isWhitespace(ch)) {
  9408. peekIndex++;
  9409. } else {
  9410. break;
  9411. }
  9412. }
  9413. }
  9414. var token = {
  9415. index: start,
  9416. text: ident
  9417. };
  9418. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9419. if (OPERATORS.hasOwnProperty(ident)) {
  9420. token.fn = OPERATORS[ident];
  9421. token.literal = true;
  9422. token.constant = true;
  9423. } else {
  9424. var getter = getterFn(ident, this.options, this.text);
  9425. token.fn = extend(function(self, locals) {
  9426. return (getter(self, locals));
  9427. }, {
  9428. assign: function(self, value) {
  9429. return setter(self, ident, value, parser.text, parser.options);
  9430. }
  9431. });
  9432. }
  9433. this.tokens.push(token);
  9434. if (methodName) {
  9435. this.tokens.push({
  9436. index:lastDot,
  9437. text: '.'
  9438. });
  9439. this.tokens.push({
  9440. index: lastDot + 1,
  9441. text: methodName
  9442. });
  9443. }
  9444. },
  9445. readString: function(quote) {
  9446. var start = this.index;
  9447. this.index++;
  9448. var string = '';
  9449. var rawString = quote;
  9450. var escape = false;
  9451. while (this.index < this.text.length) {
  9452. var ch = this.text.charAt(this.index);
  9453. rawString += ch;
  9454. if (escape) {
  9455. if (ch === 'u') {
  9456. var hex = this.text.substring(this.index + 1, this.index + 5);
  9457. if (!hex.match(/[\da-f]{4}/i))
  9458. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9459. this.index += 4;
  9460. string += String.fromCharCode(parseInt(hex, 16));
  9461. } else {
  9462. var rep = ESCAPE[ch];
  9463. string = string + (rep || ch);
  9464. }
  9465. escape = false;
  9466. } else if (ch === '\\') {
  9467. escape = true;
  9468. } else if (ch === quote) {
  9469. this.index++;
  9470. this.tokens.push({
  9471. index: start,
  9472. text: rawString,
  9473. string: string,
  9474. literal: true,
  9475. constant: true,
  9476. fn: function() { return string; }
  9477. });
  9478. return;
  9479. } else {
  9480. string += ch;
  9481. }
  9482. this.index++;
  9483. }
  9484. this.throwError('Unterminated quote', start);
  9485. }
  9486. };
  9487. /**
  9488. * @constructor
  9489. */
  9490. var Parser = function (lexer, $filter, options) {
  9491. this.lexer = lexer;
  9492. this.$filter = $filter;
  9493. this.options = options;
  9494. };
  9495. Parser.ZERO = extend(function () {
  9496. return 0;
  9497. }, {
  9498. constant: true
  9499. });
  9500. Parser.prototype = {
  9501. constructor: Parser,
  9502. parse: function (text) {
  9503. this.text = text;
  9504. this.tokens = this.lexer.lex(text);
  9505. var value = this.statements();
  9506. if (this.tokens.length !== 0) {
  9507. this.throwError('is an unexpected token', this.tokens[0]);
  9508. }
  9509. value.literal = !!value.literal;
  9510. value.constant = !!value.constant;
  9511. return value;
  9512. },
  9513. primary: function () {
  9514. var primary;
  9515. if (this.expect('(')) {
  9516. primary = this.filterChain();
  9517. this.consume(')');
  9518. } else if (this.expect('[')) {
  9519. primary = this.arrayDeclaration();
  9520. } else if (this.expect('{')) {
  9521. primary = this.object();
  9522. } else {
  9523. var token = this.expect();
  9524. primary = token.fn;
  9525. if (!primary) {
  9526. this.throwError('not a primary expression', token);
  9527. }
  9528. primary.literal = !!token.literal;
  9529. primary.constant = !!token.constant;
  9530. }
  9531. var next, context;
  9532. while ((next = this.expect('(', '[', '.'))) {
  9533. if (next.text === '(') {
  9534. primary = this.functionCall(primary, context);
  9535. context = null;
  9536. } else if (next.text === '[') {
  9537. context = primary;
  9538. primary = this.objectIndex(primary);
  9539. } else if (next.text === '.') {
  9540. context = primary;
  9541. primary = this.fieldAccess(primary);
  9542. } else {
  9543. this.throwError('IMPOSSIBLE');
  9544. }
  9545. }
  9546. return primary;
  9547. },
  9548. throwError: function(msg, token) {
  9549. throw $parseMinErr('syntax',
  9550. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9551. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9552. },
  9553. peekToken: function() {
  9554. if (this.tokens.length === 0)
  9555. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9556. return this.tokens[0];
  9557. },
  9558. peek: function(e1, e2, e3, e4) {
  9559. if (this.tokens.length > 0) {
  9560. var token = this.tokens[0];
  9561. var t = token.text;
  9562. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9563. (!e1 && !e2 && !e3 && !e4)) {
  9564. return token;
  9565. }
  9566. }
  9567. return false;
  9568. },
  9569. expect: function(e1, e2, e3, e4){
  9570. var token = this.peek(e1, e2, e3, e4);
  9571. if (token) {
  9572. this.tokens.shift();
  9573. return token;
  9574. }
  9575. return false;
  9576. },
  9577. consume: function(e1){
  9578. if (!this.expect(e1)) {
  9579. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9580. }
  9581. },
  9582. unaryFn: function(fn, right) {
  9583. return extend(function(self, locals) {
  9584. return fn(self, locals, right);
  9585. }, {
  9586. constant:right.constant
  9587. });
  9588. },
  9589. ternaryFn: function(left, middle, right){
  9590. return extend(function(self, locals){
  9591. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9592. }, {
  9593. constant: left.constant && middle.constant && right.constant
  9594. });
  9595. },
  9596. binaryFn: function(left, fn, right) {
  9597. return extend(function(self, locals) {
  9598. return fn(self, locals, left, right);
  9599. }, {
  9600. constant:left.constant && right.constant
  9601. });
  9602. },
  9603. statements: function() {
  9604. var statements = [];
  9605. while (true) {
  9606. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9607. statements.push(this.filterChain());
  9608. if (!this.expect(';')) {
  9609. // optimize for the common case where there is only one statement.
  9610. // TODO(size): maybe we should not support multiple statements?
  9611. return (statements.length === 1)
  9612. ? statements[0]
  9613. : function(self, locals) {
  9614. var value;
  9615. for (var i = 0; i < statements.length; i++) {
  9616. var statement = statements[i];
  9617. if (statement) {
  9618. value = statement(self, locals);
  9619. }
  9620. }
  9621. return value;
  9622. };
  9623. }
  9624. }
  9625. },
  9626. filterChain: function() {
  9627. var left = this.expression();
  9628. var token;
  9629. while (true) {
  9630. if ((token = this.expect('|'))) {
  9631. left = this.binaryFn(left, token.fn, this.filter());
  9632. } else {
  9633. return left;
  9634. }
  9635. }
  9636. },
  9637. filter: function() {
  9638. var token = this.expect();
  9639. var fn = this.$filter(token.text);
  9640. var argsFn = [];
  9641. while (true) {
  9642. if ((token = this.expect(':'))) {
  9643. argsFn.push(this.expression());
  9644. } else {
  9645. var fnInvoke = function(self, locals, input) {
  9646. var args = [input];
  9647. for (var i = 0; i < argsFn.length; i++) {
  9648. args.push(argsFn[i](self, locals));
  9649. }
  9650. return fn.apply(self, args);
  9651. };
  9652. return function() {
  9653. return fnInvoke;
  9654. };
  9655. }
  9656. }
  9657. },
  9658. expression: function() {
  9659. return this.assignment();
  9660. },
  9661. assignment: function() {
  9662. var left = this.ternary();
  9663. var right;
  9664. var token;
  9665. if ((token = this.expect('='))) {
  9666. if (!left.assign) {
  9667. this.throwError('implies assignment but [' +
  9668. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9669. }
  9670. right = this.ternary();
  9671. return function(scope, locals) {
  9672. return left.assign(scope, right(scope, locals), locals);
  9673. };
  9674. }
  9675. return left;
  9676. },
  9677. ternary: function() {
  9678. var left = this.logicalOR();
  9679. var middle;
  9680. var token;
  9681. if ((token = this.expect('?'))) {
  9682. middle = this.assignment();
  9683. if ((token = this.expect(':'))) {
  9684. return this.ternaryFn(left, middle, this.assignment());
  9685. } else {
  9686. this.throwError('expected :', token);
  9687. }
  9688. } else {
  9689. return left;
  9690. }
  9691. },
  9692. logicalOR: function() {
  9693. var left = this.logicalAND();
  9694. var token;
  9695. while (true) {
  9696. if ((token = this.expect('||'))) {
  9697. left = this.binaryFn(left, token.fn, this.logicalAND());
  9698. } else {
  9699. return left;
  9700. }
  9701. }
  9702. },
  9703. logicalAND: function() {
  9704. var left = this.equality();
  9705. var token;
  9706. if ((token = this.expect('&&'))) {
  9707. left = this.binaryFn(left, token.fn, this.logicalAND());
  9708. }
  9709. return left;
  9710. },
  9711. equality: function() {
  9712. var left = this.relational();
  9713. var token;
  9714. if ((token = this.expect('==','!=','===','!=='))) {
  9715. left = this.binaryFn(left, token.fn, this.equality());
  9716. }
  9717. return left;
  9718. },
  9719. relational: function() {
  9720. var left = this.additive();
  9721. var token;
  9722. if ((token = this.expect('<', '>', '<=', '>='))) {
  9723. left = this.binaryFn(left, token.fn, this.relational());
  9724. }
  9725. return left;
  9726. },
  9727. additive: function() {
  9728. var left = this.multiplicative();
  9729. var token;
  9730. while ((token = this.expect('+','-'))) {
  9731. left = this.binaryFn(left, token.fn, this.multiplicative());
  9732. }
  9733. return left;
  9734. },
  9735. multiplicative: function() {
  9736. var left = this.unary();
  9737. var token;
  9738. while ((token = this.expect('*','/','%'))) {
  9739. left = this.binaryFn(left, token.fn, this.unary());
  9740. }
  9741. return left;
  9742. },
  9743. unary: function() {
  9744. var token;
  9745. if (this.expect('+')) {
  9746. return this.primary();
  9747. } else if ((token = this.expect('-'))) {
  9748. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9749. } else if ((token = this.expect('!'))) {
  9750. return this.unaryFn(token.fn, this.unary());
  9751. } else {
  9752. return this.primary();
  9753. }
  9754. },
  9755. fieldAccess: function(object) {
  9756. var parser = this;
  9757. var field = this.expect().text;
  9758. var getter = getterFn(field, this.options, this.text);
  9759. return extend(function(scope, locals, self) {
  9760. return getter(self || object(scope, locals));
  9761. }, {
  9762. assign: function(scope, value, locals) {
  9763. var o = object(scope, locals);
  9764. if (!o) object.assign(scope, o = {});
  9765. return setter(o, field, value, parser.text, parser.options);
  9766. }
  9767. });
  9768. },
  9769. objectIndex: function(obj) {
  9770. var parser = this;
  9771. var indexFn = this.expression();
  9772. this.consume(']');
  9773. return extend(function(self, locals) {
  9774. var o = obj(self, locals),
  9775. i = indexFn(self, locals),
  9776. v, p;
  9777. ensureSafeMemberName(i, parser.text);
  9778. if (!o) return undefined;
  9779. v = ensureSafeObject(o[i], parser.text);
  9780. if (v && v.then && parser.options.unwrapPromises) {
  9781. p = v;
  9782. if (!('$$v' in v)) {
  9783. p.$$v = undefined;
  9784. p.then(function(val) { p.$$v = val; });
  9785. }
  9786. v = v.$$v;
  9787. }
  9788. return v;
  9789. }, {
  9790. assign: function(self, value, locals) {
  9791. var key = ensureSafeMemberName(indexFn(self, locals), parser.text);
  9792. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9793. var o = ensureSafeObject(obj(self, locals), parser.text);
  9794. if (!o) obj.assign(self, o = {});
  9795. return o[key] = value;
  9796. }
  9797. });
  9798. },
  9799. functionCall: function(fn, contextGetter) {
  9800. var argsFn = [];
  9801. if (this.peekToken().text !== ')') {
  9802. do {
  9803. argsFn.push(this.expression());
  9804. } while (this.expect(','));
  9805. }
  9806. this.consume(')');
  9807. var parser = this;
  9808. return function(scope, locals) {
  9809. var args = [];
  9810. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9811. for (var i = 0; i < argsFn.length; i++) {
  9812. args.push(ensureSafeObject(argsFn[i](scope, locals), parser.text));
  9813. }
  9814. var fnPtr = fn(scope, locals, context) || noop;
  9815. ensureSafeObject(context, parser.text);
  9816. ensureSafeFunction(fnPtr, parser.text);
  9817. // IE doesn't have apply for some native functions
  9818. var v = fnPtr.apply
  9819. ? fnPtr.apply(context, args)
  9820. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9821. return ensureSafeObject(v, parser.text);
  9822. };
  9823. },
  9824. // This is used with json array declaration
  9825. arrayDeclaration: function () {
  9826. var elementFns = [];
  9827. var allConstant = true;
  9828. if (this.peekToken().text !== ']') {
  9829. do {
  9830. if (this.peek(']')) {
  9831. // Support trailing commas per ES5.1.
  9832. break;
  9833. }
  9834. var elementFn = this.expression();
  9835. elementFns.push(elementFn);
  9836. if (!elementFn.constant) {
  9837. allConstant = false;
  9838. }
  9839. } while (this.expect(','));
  9840. }
  9841. this.consume(']');
  9842. return extend(function(self, locals) {
  9843. var array = [];
  9844. for (var i = 0; i < elementFns.length; i++) {
  9845. array.push(elementFns[i](self, locals));
  9846. }
  9847. return array;
  9848. }, {
  9849. literal: true,
  9850. constant: allConstant
  9851. });
  9852. },
  9853. object: function () {
  9854. var keyValues = [];
  9855. var allConstant = true;
  9856. if (this.peekToken().text !== '}') {
  9857. do {
  9858. if (this.peek('}')) {
  9859. // Support trailing commas per ES5.1.
  9860. break;
  9861. }
  9862. var token = this.expect(),
  9863. key = token.string || token.text;
  9864. this.consume(':');
  9865. var value = this.expression();
  9866. keyValues.push({key: key, value: value});
  9867. if (!value.constant) {
  9868. allConstant = false;
  9869. }
  9870. } while (this.expect(','));
  9871. }
  9872. this.consume('}');
  9873. return extend(function(self, locals) {
  9874. var object = {};
  9875. for (var i = 0; i < keyValues.length; i++) {
  9876. var keyValue = keyValues[i];
  9877. object[keyValue.key] = keyValue.value(self, locals);
  9878. }
  9879. return object;
  9880. }, {
  9881. literal: true,
  9882. constant: allConstant
  9883. });
  9884. }
  9885. };
  9886. //////////////////////////////////////////////////
  9887. // Parser helper functions
  9888. //////////////////////////////////////////////////
  9889. function setter(obj, path, setValue, fullExp, options) {
  9890. ensureSafeObject(obj, fullExp);
  9891. //needed?
  9892. options = options || {};
  9893. var element = path.split('.'), key;
  9894. for (var i = 0; element.length > 1; i++) {
  9895. key = ensureSafeMemberName(element.shift(), fullExp);
  9896. var propertyObj = ensureSafeObject(obj[key], fullExp);
  9897. if (!propertyObj) {
  9898. propertyObj = {};
  9899. obj[key] = propertyObj;
  9900. }
  9901. obj = propertyObj;
  9902. if (obj.then && options.unwrapPromises) {
  9903. promiseWarning(fullExp);
  9904. if (!("$$v" in obj)) {
  9905. (function(promise) {
  9906. promise.then(function(val) { promise.$$v = val; }); }
  9907. )(obj);
  9908. }
  9909. if (obj.$$v === undefined) {
  9910. obj.$$v = {};
  9911. }
  9912. obj = obj.$$v;
  9913. }
  9914. }
  9915. key = ensureSafeMemberName(element.shift(), fullExp);
  9916. ensureSafeObject(obj[key], fullExp);
  9917. obj[key] = setValue;
  9918. return setValue;
  9919. }
  9920. var getterFnCacheDefault = {};
  9921. var getterFnCacheExpensive = {};
  9922. function isPossiblyDangerousMemberName(name) {
  9923. return name == 'constructor';
  9924. }
  9925. /**
  9926. * Implementation of the "Black Hole" variant from:
  9927. * - http://jsperf.com/angularjs-parse-getter/4
  9928. * - http://jsperf.com/path-evaluation-simplified/7
  9929. */
  9930. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9931. ensureSafeMemberName(key0, fullExp);
  9932. ensureSafeMemberName(key1, fullExp);
  9933. ensureSafeMemberName(key2, fullExp);
  9934. ensureSafeMemberName(key3, fullExp);
  9935. ensureSafeMemberName(key4, fullExp);
  9936. var eso = function(o) {
  9937. return ensureSafeObject(o, fullExp);
  9938. };
  9939. var expensiveChecks = options.expensiveChecks;
  9940. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  9941. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  9942. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  9943. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  9944. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  9945. return !options.unwrapPromises
  9946. ? function cspSafeGetter(scope, locals) {
  9947. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9948. if (pathVal == null) return pathVal;
  9949. pathVal = eso0(pathVal[key0]);
  9950. if (!key1) return pathVal;
  9951. if (pathVal == null) return undefined;
  9952. pathVal = eso1(pathVal[key1]);
  9953. if (!key2) return pathVal;
  9954. if (pathVal == null) return undefined;
  9955. pathVal = eso2(pathVal[key2]);
  9956. if (!key3) return pathVal;
  9957. if (pathVal == null) return undefined;
  9958. pathVal = eso3(pathVal[key3]);
  9959. if (!key4) return pathVal;
  9960. if (pathVal == null) return undefined;
  9961. pathVal = eso4(pathVal[key4]);
  9962. return pathVal;
  9963. }
  9964. : function cspSafePromiseEnabledGetter(scope, locals) {
  9965. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9966. promise;
  9967. if (pathVal == null) return pathVal;
  9968. pathVal = eso0(pathVal[key0]);
  9969. if (pathVal && pathVal.then) {
  9970. promiseWarning(fullExp);
  9971. if (!("$$v" in pathVal)) {
  9972. promise = pathVal;
  9973. promise.$$v = undefined;
  9974. promise.then(function(val) { promise.$$v = eso0(val); });
  9975. }
  9976. pathVal = eso0(pathVal.$$v);
  9977. }
  9978. if (!key1) return pathVal;
  9979. if (pathVal == null) return undefined;
  9980. pathVal = eso1(pathVal[key1]);
  9981. if (pathVal && pathVal.then) {
  9982. promiseWarning(fullExp);
  9983. if (!("$$v" in pathVal)) {
  9984. promise = pathVal;
  9985. promise.$$v = undefined;
  9986. promise.then(function(val) { promise.$$v = eso1(val); });
  9987. }
  9988. pathVal = eso1(pathVal.$$v);
  9989. }
  9990. if (!key2) return pathVal;
  9991. if (pathVal == null) return undefined;
  9992. pathVal = eso2(pathVal[key2]);
  9993. if (pathVal && pathVal.then) {
  9994. promiseWarning(fullExp);
  9995. if (!("$$v" in pathVal)) {
  9996. promise = pathVal;
  9997. promise.$$v = undefined;
  9998. promise.then(function(val) { promise.$$v = eso2(val); });
  9999. }
  10000. pathVal = eso2(pathVal.$$v);
  10001. }
  10002. if (!key3) return pathVal;
  10003. if (pathVal == null) return undefined;
  10004. pathVal = eso3(pathVal[key3]);
  10005. if (pathVal && pathVal.then) {
  10006. promiseWarning(fullExp);
  10007. if (!("$$v" in pathVal)) {
  10008. promise = pathVal;
  10009. promise.$$v = undefined;
  10010. promise.then(function(val) { promise.$$v = eso3(val); });
  10011. }
  10012. pathVal = eso3(pathVal.$$v);
  10013. }
  10014. if (!key4) return pathVal;
  10015. if (pathVal == null) return undefined;
  10016. pathVal = eso4(pathVal[key4]);
  10017. if (pathVal && pathVal.then) {
  10018. promiseWarning(fullExp);
  10019. if (!("$$v" in pathVal)) {
  10020. promise = pathVal;
  10021. promise.$$v = undefined;
  10022. promise.then(function(val) { promise.$$v = eso4(val); });
  10023. }
  10024. pathVal = eso4(pathVal.$$v);
  10025. }
  10026. return pathVal;
  10027. };
  10028. }
  10029. function getterFnWithExtraArgs(fn, fullExpression) {
  10030. return function(s, l) {
  10031. return fn(s, l, promiseWarning, ensureSafeObject, fullExpression);
  10032. };
  10033. }
  10034. function getterFn(path, options, fullExp) {
  10035. var expensiveChecks = options.expensiveChecks;
  10036. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  10037. // Check whether the cache has this getter already.
  10038. // We can use hasOwnProperty directly on the cache because we ensure,
  10039. // see below, that the cache never stores a path called 'hasOwnProperty'
  10040. if (getterFnCache.hasOwnProperty(path)) {
  10041. return getterFnCache[path];
  10042. }
  10043. var pathKeys = path.split('.'),
  10044. pathKeysLength = pathKeys.length,
  10045. fn;
  10046. // http://jsperf.com/angularjs-parse-getter/6
  10047. if (options.csp) {
  10048. if (pathKeysLength < 6) {
  10049. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  10050. options);
  10051. } else {
  10052. fn = function(scope, locals) {
  10053. var i = 0, val;
  10054. do {
  10055. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  10056. pathKeys[i++], fullExp, options)(scope, locals);
  10057. locals = undefined; // clear after first iteration
  10058. scope = val;
  10059. } while (i < pathKeysLength);
  10060. return val;
  10061. };
  10062. }
  10063. } else {
  10064. var code = 'var p;\n';
  10065. if (expensiveChecks) {
  10066. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  10067. }
  10068. var needsEnsureSafeObject = expensiveChecks;
  10069. forEach(pathKeys, function(key, index) {
  10070. ensureSafeMemberName(key, fullExp);
  10071. var lookupJs = (index
  10072. // we simply dereference 's' on any .dot notation
  10073. ? 's'
  10074. // but if we are first then we check locals first, and if so read it first
  10075. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '["' + key + '"]';
  10076. var wrapWithEso = expensiveChecks || isPossiblyDangerousMemberName(key);
  10077. if (wrapWithEso) {
  10078. lookupJs = 'eso(' + lookupJs + ', fe)';
  10079. needsEnsureSafeObject = true;
  10080. }
  10081. code += 'if(s == null) return undefined;\n' +
  10082. 's=' + lookupJs + ';\n';
  10083. if (options.unwrapPromises) {
  10084. code += 'if (s && s.then) {\n' +
  10085. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  10086. ' if (!("$$v" in s)) {\n' +
  10087. ' p=s;\n' +
  10088. ' p.$$v = undefined;\n' +
  10089. ' p.then(function(v) {p.$$v=' + (wrapWithEso ? 'eso(v)' : 'v') + ';});\n' +
  10090. '}\n' +
  10091. ' s=' + (wrapWithEso ? 'eso(s.$$v)' : 's.$$v') + '\n' +
  10092. '}\n';
  10093. }
  10094. });
  10095. code += 'return s;';
  10096. /* jshint -W054 */
  10097. // s=scope, l=locals, pw=promiseWarning, eso=ensureSafeObject, fe=fullExpression
  10098. var evaledFnGetter = new Function('s', 'l', 'pw', 'eso', 'fe', code);
  10099. /* jshint +W054 */
  10100. evaledFnGetter.toString = valueFn(code);
  10101. if (needsEnsureSafeObject || options.unwrapPromises) {
  10102. evaledFnGetter = getterFnWithExtraArgs(evaledFnGetter, fullExp);
  10103. }
  10104. fn = evaledFnGetter;
  10105. }
  10106. // Only cache the value if it's not going to mess up the cache object
  10107. // This is more performant that using Object.prototype.hasOwnProperty.call
  10108. if (path !== 'hasOwnProperty') {
  10109. getterFnCache[path] = fn;
  10110. }
  10111. return fn;
  10112. }
  10113. ///////////////////////////////////
  10114. /**
  10115. * @ngdoc service
  10116. * @name $parse
  10117. * @kind function
  10118. *
  10119. * @description
  10120. *
  10121. * Converts Angular {@link guide/expression expression} into a function.
  10122. *
  10123. * ```js
  10124. * var getter = $parse('user.name');
  10125. * var setter = getter.assign;
  10126. * var context = {user:{name:'angular'}};
  10127. * var locals = {user:{name:'local'}};
  10128. *
  10129. * expect(getter(context)).toEqual('angular');
  10130. * setter(context, 'newValue');
  10131. * expect(context.user.name).toEqual('newValue');
  10132. * expect(getter(context, locals)).toEqual('local');
  10133. * ```
  10134. *
  10135. *
  10136. * @param {string} expression String expression to compile.
  10137. * @returns {function(context, locals)} a function which represents the compiled expression:
  10138. *
  10139. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  10140. * are evaluated against (typically a scope object).
  10141. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  10142. * `context`.
  10143. *
  10144. * The returned function also has the following properties:
  10145. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  10146. * literal.
  10147. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  10148. * constant literals.
  10149. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  10150. * set to a function to change its value on the given context.
  10151. *
  10152. */
  10153. /**
  10154. * @ngdoc provider
  10155. * @name $parseProvider
  10156. * @kind function
  10157. *
  10158. * @description
  10159. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  10160. * service.
  10161. */
  10162. function $ParseProvider() {
  10163. var cacheDefault = {};
  10164. var cacheExpensive = {};
  10165. var $parseOptions = {
  10166. csp: false,
  10167. unwrapPromises: false,
  10168. logPromiseWarnings: true,
  10169. expensiveChecks: false
  10170. };
  10171. /**
  10172. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10173. *
  10174. * @ngdoc method
  10175. * @name $parseProvider#unwrapPromises
  10176. * @description
  10177. *
  10178. * **This feature is deprecated, see deprecation notes below for more info**
  10179. *
  10180. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  10181. * found at any part of the expression. In other words, if set to true, the expression will always
  10182. * result in a non-promise value.
  10183. *
  10184. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  10185. * the fulfillment value is used in place of the promise while evaluating the expression.
  10186. *
  10187. * **Deprecation notice**
  10188. *
  10189. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  10190. * dichotomy between data access in templates (accessed as raw values) and controller code
  10191. * (accessed as promises).
  10192. *
  10193. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  10194. * the model access there.
  10195. *
  10196. * Other downsides of automatic promise unwrapping:
  10197. *
  10198. * - when building components it's often desirable to receive the raw promises
  10199. * - adds complexity and slows down expression evaluation
  10200. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  10201. * generated
  10202. * - makes IDE auto-completion and tool support hard
  10203. *
  10204. * **Warning Logs**
  10205. *
  10206. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  10207. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  10208. * `$parseProvider.logPromiseWarnings(false)` api.
  10209. *
  10210. *
  10211. * @param {boolean=} value New value.
  10212. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10213. * setter.
  10214. */
  10215. this.unwrapPromises = function(value) {
  10216. if (isDefined(value)) {
  10217. $parseOptions.unwrapPromises = !!value;
  10218. return this;
  10219. } else {
  10220. return $parseOptions.unwrapPromises;
  10221. }
  10222. };
  10223. /**
  10224. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10225. *
  10226. * @ngdoc method
  10227. * @name $parseProvider#logPromiseWarnings
  10228. * @description
  10229. *
  10230. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  10231. *
  10232. * The default is set to `true`.
  10233. *
  10234. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  10235. *
  10236. * @param {boolean=} value New value.
  10237. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10238. * setter.
  10239. */
  10240. this.logPromiseWarnings = function(value) {
  10241. if (isDefined(value)) {
  10242. $parseOptions.logPromiseWarnings = value;
  10243. return this;
  10244. } else {
  10245. return $parseOptions.logPromiseWarnings;
  10246. }
  10247. };
  10248. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  10249. $parseOptions.csp = $sniffer.csp;
  10250. var $parseOptionsExpensive = {
  10251. csp: $parseOptions.csp,
  10252. unwrapPromises: $parseOptions.unwrapPromises,
  10253. logPromiseWarnings: $parseOptions.logPromiseWarnings,
  10254. expensiveChecks: true
  10255. };
  10256. promiseWarning = function promiseWarningFn(fullExp) {
  10257. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  10258. promiseWarningCache[fullExp] = true;
  10259. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  10260. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  10261. };
  10262. return function(exp, expensiveChecks) {
  10263. var parsedExpression;
  10264. switch (typeof exp) {
  10265. case 'string':
  10266. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  10267. if (cache.hasOwnProperty(exp)) {
  10268. return cache[exp];
  10269. }
  10270. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  10271. var lexer = new Lexer(parseOptions);
  10272. var parser = new Parser(lexer, $filter, parseOptions);
  10273. parsedExpression = parser.parse(exp);
  10274. if (exp !== 'hasOwnProperty') {
  10275. // Only cache the value if it's not going to mess up the cache object
  10276. // This is more performant that using Object.prototype.hasOwnProperty.call
  10277. cache[exp] = parsedExpression;
  10278. }
  10279. return parsedExpression;
  10280. case 'function':
  10281. return exp;
  10282. default:
  10283. return noop;
  10284. }
  10285. };
  10286. }];
  10287. }
  10288. /**
  10289. * @ngdoc service
  10290. * @name $q
  10291. * @requires $rootScope
  10292. *
  10293. * @description
  10294. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  10295. * when they are done processing.
  10296. *
  10297. * This is an implementation of promises/deferred objects inspired by
  10298. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  10299. *
  10300. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  10301. * interface for interacting with an object that represents the result of an action that is
  10302. * performed asynchronously, and may or may not be finished at any given point in time.
  10303. *
  10304. * From the perspective of dealing with error handling, deferred and promise APIs are to
  10305. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  10306. *
  10307. * ```js
  10308. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  10309. * // are available in the current lexical scope (they could have been injected or passed in).
  10310. *
  10311. * function asyncGreet(name) {
  10312. * var deferred = $q.defer();
  10313. *
  10314. * setTimeout(function() {
  10315. * deferred.notify('About to greet ' + name + '.');
  10316. *
  10317. * if (okToGreet(name)) {
  10318. * deferred.resolve('Hello, ' + name + '!');
  10319. * } else {
  10320. * deferred.reject('Greeting ' + name + ' is not allowed.');
  10321. * }
  10322. * }, 1000);
  10323. *
  10324. * return deferred.promise;
  10325. * }
  10326. *
  10327. * var promise = asyncGreet('Robin Hood');
  10328. * promise.then(function(greeting) {
  10329. * alert('Success: ' + greeting);
  10330. * }, function(reason) {
  10331. * alert('Failed: ' + reason);
  10332. * }, function(update) {
  10333. * alert('Got notification: ' + update);
  10334. * });
  10335. * ```
  10336. *
  10337. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10338. * comes in the way of guarantees that promise and deferred APIs make, see
  10339. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10340. *
  10341. * Additionally the promise api allows for composition that is very hard to do with the
  10342. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10343. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10344. * section on serial or parallel joining of promises.
  10345. *
  10346. *
  10347. * # The Deferred API
  10348. *
  10349. * A new instance of deferred is constructed by calling `$q.defer()`.
  10350. *
  10351. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10352. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10353. * of the task.
  10354. *
  10355. * **Methods**
  10356. *
  10357. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10358. * constructed via `$q.reject`, the promise will be rejected instead.
  10359. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10360. * resolving it with a rejection constructed via `$q.reject`.
  10361. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10362. * multiple times before the promise is either resolved or rejected.
  10363. *
  10364. * **Properties**
  10365. *
  10366. * - promise – `{Promise}` – promise object associated with this deferred.
  10367. *
  10368. *
  10369. * # The Promise API
  10370. *
  10371. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10372. * calling `deferred.promise`.
  10373. *
  10374. * The purpose of the promise object is to allow for interested parties to get access to the result
  10375. * of the deferred task when it completes.
  10376. *
  10377. * **Methods**
  10378. *
  10379. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10380. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10381. * as soon as the result is available. The callbacks are called with a single argument: the result
  10382. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10383. * provide a progress indication, before the promise is resolved or rejected.
  10384. *
  10385. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10386. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10387. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10388. * method.
  10389. *
  10390. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10391. *
  10392. * Because `catch` is a reserved word in JavaScript and reserved keywords are not supported as
  10393. * property names by ES3, you'll need to invoke the method like `promise['catch'](callback)` or
  10394. * `promise.then(null, errorCallback)` to make your code IE8 and Android 2.x compatible.
  10395. *
  10396. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10397. * but to do so without modifying the final value. This is useful to release resources or do some
  10398. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10399. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10400. * more information.
  10401. *
  10402. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10403. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10404. * make your code IE8 and Android 2.x compatible.
  10405. *
  10406. * # Chaining promises
  10407. *
  10408. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10409. * possible to create a chain of promises:
  10410. *
  10411. * ```js
  10412. * promiseB = promiseA.then(function(result) {
  10413. * return result + 1;
  10414. * });
  10415. *
  10416. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10417. * // will be the result of promiseA incremented by 1
  10418. * ```
  10419. *
  10420. * It is possible to create chains of any length and since a promise can be resolved with another
  10421. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10422. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10423. * $http's response interceptors.
  10424. *
  10425. *
  10426. * # Differences between Kris Kowal's Q and $q
  10427. *
  10428. * There are two main differences:
  10429. *
  10430. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10431. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10432. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10433. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10434. * all the important functionality needed for common async tasks.
  10435. *
  10436. * # Testing
  10437. *
  10438. * ```js
  10439. * it('should simulate promise', inject(function($q, $rootScope) {
  10440. * var deferred = $q.defer();
  10441. * var promise = deferred.promise;
  10442. * var resolvedValue;
  10443. *
  10444. * promise.then(function(value) { resolvedValue = value; });
  10445. * expect(resolvedValue).toBeUndefined();
  10446. *
  10447. * // Simulate resolving of promise
  10448. * deferred.resolve(123);
  10449. * // Note that the 'then' function does not get called synchronously.
  10450. * // This is because we want the promise API to always be async, whether or not
  10451. * // it got called synchronously or asynchronously.
  10452. * expect(resolvedValue).toBeUndefined();
  10453. *
  10454. * // Propagate promise resolution to 'then' functions using $apply().
  10455. * $rootScope.$apply();
  10456. * expect(resolvedValue).toEqual(123);
  10457. * }));
  10458. * ```
  10459. */
  10460. function $QProvider() {
  10461. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10462. return qFactory(function(callback) {
  10463. $rootScope.$evalAsync(callback);
  10464. }, $exceptionHandler);
  10465. }];
  10466. }
  10467. /**
  10468. * Constructs a promise manager.
  10469. *
  10470. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10471. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10472. * debugging purposes.
  10473. * @returns {object} Promise manager.
  10474. */
  10475. function qFactory(nextTick, exceptionHandler) {
  10476. /**
  10477. * @ngdoc method
  10478. * @name $q#defer
  10479. * @kind function
  10480. *
  10481. * @description
  10482. * Creates a `Deferred` object which represents a task which will finish in the future.
  10483. *
  10484. * @returns {Deferred} Returns a new instance of deferred.
  10485. */
  10486. var defer = function() {
  10487. var pending = [],
  10488. value, deferred;
  10489. deferred = {
  10490. resolve: function(val) {
  10491. if (pending) {
  10492. var callbacks = pending;
  10493. pending = undefined;
  10494. value = ref(val);
  10495. if (callbacks.length) {
  10496. nextTick(function() {
  10497. var callback;
  10498. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10499. callback = callbacks[i];
  10500. value.then(callback[0], callback[1], callback[2]);
  10501. }
  10502. });
  10503. }
  10504. }
  10505. },
  10506. reject: function(reason) {
  10507. deferred.resolve(createInternalRejectedPromise(reason));
  10508. },
  10509. notify: function(progress) {
  10510. if (pending) {
  10511. var callbacks = pending;
  10512. if (pending.length) {
  10513. nextTick(function() {
  10514. var callback;
  10515. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10516. callback = callbacks[i];
  10517. callback[2](progress);
  10518. }
  10519. });
  10520. }
  10521. }
  10522. },
  10523. promise: {
  10524. then: function(callback, errback, progressback) {
  10525. var result = defer();
  10526. var wrappedCallback = function(value) {
  10527. try {
  10528. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10529. } catch(e) {
  10530. result.reject(e);
  10531. exceptionHandler(e);
  10532. }
  10533. };
  10534. var wrappedErrback = function(reason) {
  10535. try {
  10536. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10537. } catch(e) {
  10538. result.reject(e);
  10539. exceptionHandler(e);
  10540. }
  10541. };
  10542. var wrappedProgressback = function(progress) {
  10543. try {
  10544. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10545. } catch(e) {
  10546. exceptionHandler(e);
  10547. }
  10548. };
  10549. if (pending) {
  10550. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10551. } else {
  10552. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10553. }
  10554. return result.promise;
  10555. },
  10556. "catch": function(callback) {
  10557. return this.then(null, callback);
  10558. },
  10559. "finally": function(callback) {
  10560. function makePromise(value, resolved) {
  10561. var result = defer();
  10562. if (resolved) {
  10563. result.resolve(value);
  10564. } else {
  10565. result.reject(value);
  10566. }
  10567. return result.promise;
  10568. }
  10569. function handleCallback(value, isResolved) {
  10570. var callbackOutput = null;
  10571. try {
  10572. callbackOutput = (callback ||defaultCallback)();
  10573. } catch(e) {
  10574. return makePromise(e, false);
  10575. }
  10576. if (isPromiseLike(callbackOutput)) {
  10577. return callbackOutput.then(function() {
  10578. return makePromise(value, isResolved);
  10579. }, function(error) {
  10580. return makePromise(error, false);
  10581. });
  10582. } else {
  10583. return makePromise(value, isResolved);
  10584. }
  10585. }
  10586. return this.then(function(value) {
  10587. return handleCallback(value, true);
  10588. }, function(error) {
  10589. return handleCallback(error, false);
  10590. });
  10591. }
  10592. }
  10593. };
  10594. return deferred;
  10595. };
  10596. var ref = function(value) {
  10597. if (isPromiseLike(value)) return value;
  10598. return {
  10599. then: function(callback) {
  10600. var result = defer();
  10601. nextTick(function() {
  10602. result.resolve(callback(value));
  10603. });
  10604. return result.promise;
  10605. }
  10606. };
  10607. };
  10608. /**
  10609. * @ngdoc method
  10610. * @name $q#reject
  10611. * @kind function
  10612. *
  10613. * @description
  10614. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10615. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10616. * a promise chain, you don't need to worry about it.
  10617. *
  10618. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10619. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10620. * a promise error callback and you want to forward the error to the promise derived from the
  10621. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10622. * `reject`.
  10623. *
  10624. * ```js
  10625. * promiseB = promiseA.then(function(result) {
  10626. * // success: do something and resolve promiseB
  10627. * // with the old or a new result
  10628. * return result;
  10629. * }, function(reason) {
  10630. * // error: handle the error if possible and
  10631. * // resolve promiseB with newPromiseOrValue,
  10632. * // otherwise forward the rejection to promiseB
  10633. * if (canHandle(reason)) {
  10634. * // handle the error and recover
  10635. * return newPromiseOrValue;
  10636. * }
  10637. * return $q.reject(reason);
  10638. * });
  10639. * ```
  10640. *
  10641. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10642. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10643. */
  10644. var reject = function(reason) {
  10645. var result = defer();
  10646. result.reject(reason);
  10647. return result.promise;
  10648. };
  10649. var createInternalRejectedPromise = function(reason) {
  10650. return {
  10651. then: function(callback, errback) {
  10652. var result = defer();
  10653. nextTick(function() {
  10654. try {
  10655. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10656. } catch(e) {
  10657. result.reject(e);
  10658. exceptionHandler(e);
  10659. }
  10660. });
  10661. return result.promise;
  10662. }
  10663. };
  10664. };
  10665. /**
  10666. * @ngdoc method
  10667. * @name $q#when
  10668. * @kind function
  10669. *
  10670. * @description
  10671. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10672. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10673. * the promise comes from a source that can't be trusted.
  10674. *
  10675. * @param {*} value Value or a promise
  10676. * @returns {Promise} Returns a promise of the passed value or promise
  10677. */
  10678. var when = function(value, callback, errback, progressback) {
  10679. var result = defer(),
  10680. done;
  10681. var wrappedCallback = function(value) {
  10682. try {
  10683. return (isFunction(callback) ? callback : defaultCallback)(value);
  10684. } catch (e) {
  10685. exceptionHandler(e);
  10686. return reject(e);
  10687. }
  10688. };
  10689. var wrappedErrback = function(reason) {
  10690. try {
  10691. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10692. } catch (e) {
  10693. exceptionHandler(e);
  10694. return reject(e);
  10695. }
  10696. };
  10697. var wrappedProgressback = function(progress) {
  10698. try {
  10699. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10700. } catch (e) {
  10701. exceptionHandler(e);
  10702. }
  10703. };
  10704. nextTick(function() {
  10705. ref(value).then(function(value) {
  10706. if (done) return;
  10707. done = true;
  10708. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10709. }, function(reason) {
  10710. if (done) return;
  10711. done = true;
  10712. result.resolve(wrappedErrback(reason));
  10713. }, function(progress) {
  10714. if (done) return;
  10715. result.notify(wrappedProgressback(progress));
  10716. });
  10717. });
  10718. return result.promise;
  10719. };
  10720. function defaultCallback(value) {
  10721. return value;
  10722. }
  10723. function defaultErrback(reason) {
  10724. return reject(reason);
  10725. }
  10726. /**
  10727. * @ngdoc method
  10728. * @name $q#all
  10729. * @kind function
  10730. *
  10731. * @description
  10732. * Combines multiple promises into a single promise that is resolved when all of the input
  10733. * promises are resolved.
  10734. *
  10735. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10736. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10737. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10738. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10739. * with the same rejection value.
  10740. */
  10741. function all(promises) {
  10742. var deferred = defer(),
  10743. counter = 0,
  10744. results = isArray(promises) ? [] : {};
  10745. forEach(promises, function(promise, key) {
  10746. counter++;
  10747. ref(promise).then(function(value) {
  10748. if (results.hasOwnProperty(key)) return;
  10749. results[key] = value;
  10750. if (!(--counter)) deferred.resolve(results);
  10751. }, function(reason) {
  10752. if (results.hasOwnProperty(key)) return;
  10753. deferred.reject(reason);
  10754. });
  10755. });
  10756. if (counter === 0) {
  10757. deferred.resolve(results);
  10758. }
  10759. return deferred.promise;
  10760. }
  10761. return {
  10762. defer: defer,
  10763. reject: reject,
  10764. when: when,
  10765. all: all
  10766. };
  10767. }
  10768. function $$RAFProvider(){ //rAF
  10769. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10770. var requestAnimationFrame = $window.requestAnimationFrame ||
  10771. $window.webkitRequestAnimationFrame ||
  10772. $window.mozRequestAnimationFrame;
  10773. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10774. $window.webkitCancelAnimationFrame ||
  10775. $window.mozCancelAnimationFrame ||
  10776. $window.webkitCancelRequestAnimationFrame;
  10777. var rafSupported = !!requestAnimationFrame;
  10778. var raf = rafSupported
  10779. ? function(fn) {
  10780. var id = requestAnimationFrame(fn);
  10781. return function() {
  10782. cancelAnimationFrame(id);
  10783. };
  10784. }
  10785. : function(fn) {
  10786. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10787. return function() {
  10788. $timeout.cancel(timer);
  10789. };
  10790. };
  10791. raf.supported = rafSupported;
  10792. return raf;
  10793. }];
  10794. }
  10795. /**
  10796. * DESIGN NOTES
  10797. *
  10798. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10799. *
  10800. * The typical use of scope is to watch the expressions, which most of the time return the same
  10801. * value as last time so we optimize the operation.
  10802. *
  10803. * Closures construction is expensive in terms of speed as well as memory:
  10804. * - No closures, instead use prototypical inheritance for API
  10805. * - Internal state needs to be stored on scope directly, which means that private state is
  10806. * exposed as $$____ properties
  10807. *
  10808. * Loop operations are optimized by using while(count--) { ... }
  10809. * - this means that in order to keep the same order of execution as addition we have to add
  10810. * items to the array at the beginning (unshift) instead of at the end (push)
  10811. *
  10812. * Child scopes are created and removed often
  10813. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10814. *
  10815. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10816. * implemented in the same way as watch. Watch requires return of initialization function which
  10817. * are expensive to construct.
  10818. */
  10819. /**
  10820. * @ngdoc provider
  10821. * @name $rootScopeProvider
  10822. * @description
  10823. *
  10824. * Provider for the $rootScope service.
  10825. */
  10826. /**
  10827. * @ngdoc method
  10828. * @name $rootScopeProvider#digestTtl
  10829. * @description
  10830. *
  10831. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10832. * assuming that the model is unstable.
  10833. *
  10834. * The current default is 10 iterations.
  10835. *
  10836. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10837. * several digest iterations. However if an application needs more than the default 10 digest
  10838. * iterations for its model to stabilize then you should investigate what is causing the model to
  10839. * continuously change during the digest.
  10840. *
  10841. * Increasing the TTL could have performance implications, so you should not change it without
  10842. * proper justification.
  10843. *
  10844. * @param {number} limit The number of digest iterations.
  10845. */
  10846. /**
  10847. * @ngdoc service
  10848. * @name $rootScope
  10849. * @description
  10850. *
  10851. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10852. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10853. * between the model and the view, via a mechanism for watching the model for changes.
  10854. * They also provide an event emission/broadcast and subscription facility. See the
  10855. * {@link guide/scope developer guide on scopes}.
  10856. */
  10857. function $RootScopeProvider(){
  10858. var TTL = 10;
  10859. var $rootScopeMinErr = minErr('$rootScope');
  10860. var lastDirtyWatch = null;
  10861. this.digestTtl = function(value) {
  10862. if (arguments.length) {
  10863. TTL = value;
  10864. }
  10865. return TTL;
  10866. };
  10867. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10868. function( $injector, $exceptionHandler, $parse, $browser) {
  10869. /**
  10870. * @ngdoc type
  10871. * @name $rootScope.Scope
  10872. *
  10873. * @description
  10874. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10875. * {@link auto.$injector $injector}. Child scopes are created using the
  10876. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10877. * compiled HTML template is executed.)
  10878. *
  10879. * Here is a simple scope snippet to show how you can interact with the scope.
  10880. * ```html
  10881. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10882. * ```
  10883. *
  10884. * # Inheritance
  10885. * A scope can inherit from a parent scope, as in this example:
  10886. * ```js
  10887. var parent = $rootScope;
  10888. var child = parent.$new();
  10889. parent.salutation = "Hello";
  10890. child.name = "World";
  10891. expect(child.salutation).toEqual('Hello');
  10892. child.salutation = "Welcome";
  10893. expect(child.salutation).toEqual('Welcome');
  10894. expect(parent.salutation).toEqual('Hello');
  10895. * ```
  10896. *
  10897. *
  10898. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10899. * provided for the current scope. Defaults to {@link ng}.
  10900. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10901. * append/override services provided by `providers`. This is handy
  10902. * when unit-testing and having the need to override a default
  10903. * service.
  10904. * @returns {Object} Newly created scope.
  10905. *
  10906. */
  10907. function Scope() {
  10908. this.$id = nextUid();
  10909. this.$$phase = this.$parent = this.$$watchers =
  10910. this.$$nextSibling = this.$$prevSibling =
  10911. this.$$childHead = this.$$childTail = null;
  10912. this['this'] = this.$root = this;
  10913. this.$$destroyed = false;
  10914. this.$$asyncQueue = [];
  10915. this.$$postDigestQueue = [];
  10916. this.$$listeners = {};
  10917. this.$$listenerCount = {};
  10918. this.$$isolateBindings = {};
  10919. }
  10920. /**
  10921. * @ngdoc property
  10922. * @name $rootScope.Scope#$id
  10923. *
  10924. * @description
  10925. * Unique scope ID (monotonically increasing) useful for debugging.
  10926. */
  10927. /**
  10928. * @ngdoc property
  10929. * @name $rootScope.Scope#$parent
  10930. *
  10931. * @description
  10932. * Reference to the parent scope.
  10933. */
  10934. /**
  10935. * @ngdoc property
  10936. * @name $rootScope.Scope#$root
  10937. *
  10938. * @description
  10939. * Reference to the root scope.
  10940. */
  10941. Scope.prototype = {
  10942. constructor: Scope,
  10943. /**
  10944. * @ngdoc method
  10945. * @name $rootScope.Scope#$new
  10946. * @kind function
  10947. *
  10948. * @description
  10949. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10950. *
  10951. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  10952. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10953. *
  10954. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10955. * desired for the scope and its child scopes to be permanently detached from the parent and
  10956. * thus stop participating in model change detection and listener notification by invoking.
  10957. *
  10958. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10959. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10960. * When creating widgets, it is useful for the widget to not accidentally read parent
  10961. * state.
  10962. *
  10963. * @returns {Object} The newly created child scope.
  10964. *
  10965. */
  10966. $new: function(isolate) {
  10967. var ChildScope,
  10968. child;
  10969. if (isolate) {
  10970. child = new Scope();
  10971. child.$root = this.$root;
  10972. // ensure that there is just one async queue per $rootScope and its children
  10973. child.$$asyncQueue = this.$$asyncQueue;
  10974. child.$$postDigestQueue = this.$$postDigestQueue;
  10975. } else {
  10976. // Only create a child scope class if somebody asks for one,
  10977. // but cache it to allow the VM to optimize lookups.
  10978. if (!this.$$childScopeClass) {
  10979. this.$$childScopeClass = function() {
  10980. this.$$watchers = this.$$nextSibling =
  10981. this.$$childHead = this.$$childTail = null;
  10982. this.$$listeners = {};
  10983. this.$$listenerCount = {};
  10984. this.$id = nextUid();
  10985. this.$$childScopeClass = null;
  10986. };
  10987. this.$$childScopeClass.prototype = this;
  10988. }
  10989. child = new this.$$childScopeClass();
  10990. }
  10991. child['this'] = child;
  10992. child.$parent = this;
  10993. child.$$prevSibling = this.$$childTail;
  10994. if (this.$$childHead) {
  10995. this.$$childTail.$$nextSibling = child;
  10996. this.$$childTail = child;
  10997. } else {
  10998. this.$$childHead = this.$$childTail = child;
  10999. }
  11000. return child;
  11001. },
  11002. /**
  11003. * @ngdoc method
  11004. * @name $rootScope.Scope#$watch
  11005. * @kind function
  11006. *
  11007. * @description
  11008. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  11009. *
  11010. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  11011. * $digest()} and should return the value that will be watched. (Since
  11012. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  11013. * `watchExpression` can execute multiple times per
  11014. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  11015. * - The `listener` is called only when the value from the current `watchExpression` and the
  11016. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  11017. * see below). Inequality is determined according to reference inequality,
  11018. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  11019. * via the `!==` Javascript operator, unless `objectEquality == true`
  11020. * (see next point)
  11021. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  11022. * according to the {@link angular.equals} function. To save the value of the object for
  11023. * later comparison, the {@link angular.copy} function is used. This therefore means that
  11024. * watching complex objects will have adverse memory and performance implications.
  11025. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  11026. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  11027. * iteration limit is 10 to prevent an infinite loop deadlock.
  11028. *
  11029. *
  11030. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  11031. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  11032. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  11033. * change is detected, be prepared for multiple calls to your listener.)
  11034. *
  11035. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  11036. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  11037. * watcher. In rare cases, this is undesirable because the listener is called when the result
  11038. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  11039. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  11040. * listener was called due to initialization.
  11041. *
  11042. * The example below contains an illustration of using a function as your $watch listener
  11043. *
  11044. *
  11045. * # Example
  11046. * ```js
  11047. // let's assume that scope was dependency injected as the $rootScope
  11048. var scope = $rootScope;
  11049. scope.name = 'misko';
  11050. scope.counter = 0;
  11051. expect(scope.counter).toEqual(0);
  11052. scope.$watch('name', function(newValue, oldValue) {
  11053. scope.counter = scope.counter + 1;
  11054. });
  11055. expect(scope.counter).toEqual(0);
  11056. scope.$digest();
  11057. // the listener is always called during the first $digest loop after it was registered
  11058. expect(scope.counter).toEqual(1);
  11059. scope.$digest();
  11060. // but now it will not be called unless the value changes
  11061. expect(scope.counter).toEqual(1);
  11062. scope.name = 'adam';
  11063. scope.$digest();
  11064. expect(scope.counter).toEqual(2);
  11065. // Using a listener function
  11066. var food;
  11067. scope.foodCounter = 0;
  11068. expect(scope.foodCounter).toEqual(0);
  11069. scope.$watch(
  11070. // This is the listener function
  11071. function() { return food; },
  11072. // This is the change handler
  11073. function(newValue, oldValue) {
  11074. if ( newValue !== oldValue ) {
  11075. // Only increment the counter if the value changed
  11076. scope.foodCounter = scope.foodCounter + 1;
  11077. }
  11078. }
  11079. );
  11080. // No digest has been run so the counter will be zero
  11081. expect(scope.foodCounter).toEqual(0);
  11082. // Run the digest but since food has not changed count will still be zero
  11083. scope.$digest();
  11084. expect(scope.foodCounter).toEqual(0);
  11085. // Update food and run digest. Now the counter will increment
  11086. food = 'cheeseburger';
  11087. scope.$digest();
  11088. expect(scope.foodCounter).toEqual(1);
  11089. * ```
  11090. *
  11091. *
  11092. *
  11093. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  11094. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  11095. * a call to the `listener`.
  11096. *
  11097. * - `string`: Evaluated as {@link guide/expression expression}
  11098. * - `function(scope)`: called with current `scope` as a parameter.
  11099. * @param {(function()|string)=} listener Callback called whenever the return value of
  11100. * the `watchExpression` changes.
  11101. *
  11102. * - `string`: Evaluated as {@link guide/expression expression}
  11103. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  11104. * parameters.
  11105. *
  11106. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  11107. * comparing for reference equality.
  11108. * @returns {function()} Returns a deregistration function for this listener.
  11109. */
  11110. $watch: function(watchExp, listener, objectEquality) {
  11111. var scope = this,
  11112. get = compileToFn(watchExp, 'watch'),
  11113. array = scope.$$watchers,
  11114. watcher = {
  11115. fn: listener,
  11116. last: initWatchVal,
  11117. get: get,
  11118. exp: watchExp,
  11119. eq: !!objectEquality
  11120. };
  11121. lastDirtyWatch = null;
  11122. // in the case user pass string, we need to compile it, do we really need this ?
  11123. if (!isFunction(listener)) {
  11124. var listenFn = compileToFn(listener || noop, 'listener');
  11125. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  11126. }
  11127. if (typeof watchExp == 'string' && get.constant) {
  11128. var originalFn = watcher.fn;
  11129. watcher.fn = function(newVal, oldVal, scope) {
  11130. originalFn.call(this, newVal, oldVal, scope);
  11131. arrayRemove(array, watcher);
  11132. };
  11133. }
  11134. if (!array) {
  11135. array = scope.$$watchers = [];
  11136. }
  11137. // we use unshift since we use a while loop in $digest for speed.
  11138. // the while loop reads in reverse order.
  11139. array.unshift(watcher);
  11140. return function deregisterWatch() {
  11141. arrayRemove(array, watcher);
  11142. lastDirtyWatch = null;
  11143. };
  11144. },
  11145. /**
  11146. * @ngdoc method
  11147. * @name $rootScope.Scope#$watchCollection
  11148. * @kind function
  11149. *
  11150. * @description
  11151. * Shallow watches the properties of an object and fires whenever any of the properties change
  11152. * (for arrays, this implies watching the array items; for object maps, this implies watching
  11153. * the properties). If a change is detected, the `listener` callback is fired.
  11154. *
  11155. * - The `obj` collection is observed via standard $watch operation and is examined on every
  11156. * call to $digest() to see if any items have been added, removed, or moved.
  11157. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  11158. * adding, removing, and moving items belonging to an object or array.
  11159. *
  11160. *
  11161. * # Example
  11162. * ```js
  11163. $scope.names = ['igor', 'matias', 'misko', 'james'];
  11164. $scope.dataCount = 4;
  11165. $scope.$watchCollection('names', function(newNames, oldNames) {
  11166. $scope.dataCount = newNames.length;
  11167. });
  11168. expect($scope.dataCount).toEqual(4);
  11169. $scope.$digest();
  11170. //still at 4 ... no changes
  11171. expect($scope.dataCount).toEqual(4);
  11172. $scope.names.pop();
  11173. $scope.$digest();
  11174. //now there's been a change
  11175. expect($scope.dataCount).toEqual(3);
  11176. * ```
  11177. *
  11178. *
  11179. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  11180. * expression value should evaluate to an object or an array which is observed on each
  11181. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  11182. * collection will trigger a call to the `listener`.
  11183. *
  11184. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  11185. * when a change is detected.
  11186. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  11187. * - The `oldCollection` object is a copy of the former collection data.
  11188. * Due to performance considerations, the`oldCollection` value is computed only if the
  11189. * `listener` function declares two or more arguments.
  11190. * - The `scope` argument refers to the current scope.
  11191. *
  11192. * @returns {function()} Returns a de-registration function for this listener. When the
  11193. * de-registration function is executed, the internal watch operation is terminated.
  11194. */
  11195. $watchCollection: function(obj, listener) {
  11196. var self = this;
  11197. // the current value, updated on each dirty-check run
  11198. var newValue;
  11199. // a shallow copy of the newValue from the last dirty-check run,
  11200. // updated to match newValue during dirty-check run
  11201. var oldValue;
  11202. // a shallow copy of the newValue from when the last change happened
  11203. var veryOldValue;
  11204. // only track veryOldValue if the listener is asking for it
  11205. var trackVeryOldValue = (listener.length > 1);
  11206. var changeDetected = 0;
  11207. var objGetter = $parse(obj);
  11208. var internalArray = [];
  11209. var internalObject = {};
  11210. var initRun = true;
  11211. var oldLength = 0;
  11212. function $watchCollectionWatch() {
  11213. newValue = objGetter(self);
  11214. var newLength, key, bothNaN;
  11215. if (!isObject(newValue)) { // if primitive
  11216. if (oldValue !== newValue) {
  11217. oldValue = newValue;
  11218. changeDetected++;
  11219. }
  11220. } else if (isArrayLike(newValue)) {
  11221. if (oldValue !== internalArray) {
  11222. // we are transitioning from something which was not an array into array.
  11223. oldValue = internalArray;
  11224. oldLength = oldValue.length = 0;
  11225. changeDetected++;
  11226. }
  11227. newLength = newValue.length;
  11228. if (oldLength !== newLength) {
  11229. // if lengths do not match we need to trigger change notification
  11230. changeDetected++;
  11231. oldValue.length = oldLength = newLength;
  11232. }
  11233. // copy the items to oldValue and look for changes.
  11234. for (var i = 0; i < newLength; i++) {
  11235. bothNaN = (oldValue[i] !== oldValue[i]) &&
  11236. (newValue[i] !== newValue[i]);
  11237. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  11238. changeDetected++;
  11239. oldValue[i] = newValue[i];
  11240. }
  11241. }
  11242. } else {
  11243. if (oldValue !== internalObject) {
  11244. // we are transitioning from something which was not an object into object.
  11245. oldValue = internalObject = {};
  11246. oldLength = 0;
  11247. changeDetected++;
  11248. }
  11249. // copy the items to oldValue and look for changes.
  11250. newLength = 0;
  11251. for (key in newValue) {
  11252. if (newValue.hasOwnProperty(key)) {
  11253. newLength++;
  11254. if (oldValue.hasOwnProperty(key)) {
  11255. bothNaN = (oldValue[key] !== oldValue[key]) &&
  11256. (newValue[key] !== newValue[key]);
  11257. if (!bothNaN && (oldValue[key] !== newValue[key])) {
  11258. changeDetected++;
  11259. oldValue[key] = newValue[key];
  11260. }
  11261. } else {
  11262. oldLength++;
  11263. oldValue[key] = newValue[key];
  11264. changeDetected++;
  11265. }
  11266. }
  11267. }
  11268. if (oldLength > newLength) {
  11269. // we used to have more keys, need to find them and destroy them.
  11270. changeDetected++;
  11271. for(key in oldValue) {
  11272. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  11273. oldLength--;
  11274. delete oldValue[key];
  11275. }
  11276. }
  11277. }
  11278. }
  11279. return changeDetected;
  11280. }
  11281. function $watchCollectionAction() {
  11282. if (initRun) {
  11283. initRun = false;
  11284. listener(newValue, newValue, self);
  11285. } else {
  11286. listener(newValue, veryOldValue, self);
  11287. }
  11288. // make a copy for the next time a collection is changed
  11289. if (trackVeryOldValue) {
  11290. if (!isObject(newValue)) {
  11291. //primitive
  11292. veryOldValue = newValue;
  11293. } else if (isArrayLike(newValue)) {
  11294. veryOldValue = new Array(newValue.length);
  11295. for (var i = 0; i < newValue.length; i++) {
  11296. veryOldValue[i] = newValue[i];
  11297. }
  11298. } else { // if object
  11299. veryOldValue = {};
  11300. for (var key in newValue) {
  11301. if (hasOwnProperty.call(newValue, key)) {
  11302. veryOldValue[key] = newValue[key];
  11303. }
  11304. }
  11305. }
  11306. }
  11307. }
  11308. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  11309. },
  11310. /**
  11311. * @ngdoc method
  11312. * @name $rootScope.Scope#$digest
  11313. * @kind function
  11314. *
  11315. * @description
  11316. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  11317. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  11318. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  11319. * until no more listeners are firing. This means that it is possible to get into an infinite
  11320. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  11321. * iterations exceeds 10.
  11322. *
  11323. * Usually, you don't call `$digest()` directly in
  11324. * {@link ng.directive:ngController controllers} or in
  11325. * {@link ng.$compileProvider#directive directives}.
  11326. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  11327. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  11328. *
  11329. * If you want to be notified whenever `$digest()` is called,
  11330. * you can register a `watchExpression` function with
  11331. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  11332. *
  11333. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  11334. *
  11335. * # Example
  11336. * ```js
  11337. var scope = ...;
  11338. scope.name = 'misko';
  11339. scope.counter = 0;
  11340. expect(scope.counter).toEqual(0);
  11341. scope.$watch('name', function(newValue, oldValue) {
  11342. scope.counter = scope.counter + 1;
  11343. });
  11344. expect(scope.counter).toEqual(0);
  11345. scope.$digest();
  11346. // the listener is always called during the first $digest loop after it was registered
  11347. expect(scope.counter).toEqual(1);
  11348. scope.$digest();
  11349. // but now it will not be called unless the value changes
  11350. expect(scope.counter).toEqual(1);
  11351. scope.name = 'adam';
  11352. scope.$digest();
  11353. expect(scope.counter).toEqual(2);
  11354. * ```
  11355. *
  11356. */
  11357. $digest: function() {
  11358. var watch, value, last,
  11359. watchers,
  11360. asyncQueue = this.$$asyncQueue,
  11361. postDigestQueue = this.$$postDigestQueue,
  11362. length,
  11363. dirty, ttl = TTL,
  11364. next, current, target = this,
  11365. watchLog = [],
  11366. logIdx, logMsg, asyncTask;
  11367. beginPhase('$digest');
  11368. // Check for changes to browser url that happened in sync before the call to $digest
  11369. $browser.$$checkUrlChange();
  11370. lastDirtyWatch = null;
  11371. do { // "while dirty" loop
  11372. dirty = false;
  11373. current = target;
  11374. while(asyncQueue.length) {
  11375. try {
  11376. asyncTask = asyncQueue.shift();
  11377. asyncTask.scope.$eval(asyncTask.expression);
  11378. } catch (e) {
  11379. clearPhase();
  11380. $exceptionHandler(e);
  11381. }
  11382. lastDirtyWatch = null;
  11383. }
  11384. traverseScopesLoop:
  11385. do { // "traverse the scopes" loop
  11386. if ((watchers = current.$$watchers)) {
  11387. // process our watches
  11388. length = watchers.length;
  11389. while (length--) {
  11390. try {
  11391. watch = watchers[length];
  11392. // Most common watches are on primitives, in which case we can short
  11393. // circuit it with === operator, only when === fails do we use .equals
  11394. if (watch) {
  11395. if ((value = watch.get(current)) !== (last = watch.last) &&
  11396. !(watch.eq
  11397. ? equals(value, last)
  11398. : (typeof value === 'number' && typeof last === 'number'
  11399. && isNaN(value) && isNaN(last)))) {
  11400. dirty = true;
  11401. lastDirtyWatch = watch;
  11402. watch.last = watch.eq ? copy(value, null) : value;
  11403. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11404. if (ttl < 5) {
  11405. logIdx = 4 - ttl;
  11406. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11407. logMsg = (isFunction(watch.exp))
  11408. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11409. : watch.exp;
  11410. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11411. watchLog[logIdx].push(logMsg);
  11412. }
  11413. } else if (watch === lastDirtyWatch) {
  11414. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11415. // have already been tested.
  11416. dirty = false;
  11417. break traverseScopesLoop;
  11418. }
  11419. }
  11420. } catch (e) {
  11421. clearPhase();
  11422. $exceptionHandler(e);
  11423. }
  11424. }
  11425. }
  11426. // Insanity Warning: scope depth-first traversal
  11427. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11428. // this piece should be kept in sync with the traversal in $broadcast
  11429. if (!(next = (current.$$childHead ||
  11430. (current !== target && current.$$nextSibling)))) {
  11431. while(current !== target && !(next = current.$$nextSibling)) {
  11432. current = current.$parent;
  11433. }
  11434. }
  11435. } while ((current = next));
  11436. // `break traverseScopesLoop;` takes us to here
  11437. if((dirty || asyncQueue.length) && !(ttl--)) {
  11438. clearPhase();
  11439. throw $rootScopeMinErr('infdig',
  11440. '{0} $digest() iterations reached. Aborting!\n' +
  11441. 'Watchers fired in the last 5 iterations: {1}',
  11442. TTL, toJson(watchLog));
  11443. }
  11444. } while (dirty || asyncQueue.length);
  11445. clearPhase();
  11446. while(postDigestQueue.length) {
  11447. try {
  11448. postDigestQueue.shift()();
  11449. } catch (e) {
  11450. $exceptionHandler(e);
  11451. }
  11452. }
  11453. },
  11454. /**
  11455. * @ngdoc event
  11456. * @name $rootScope.Scope#$destroy
  11457. * @eventType broadcast on scope being destroyed
  11458. *
  11459. * @description
  11460. * Broadcasted when a scope and its children are being destroyed.
  11461. *
  11462. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11463. * clean up DOM bindings before an element is removed from the DOM.
  11464. */
  11465. /**
  11466. * @ngdoc method
  11467. * @name $rootScope.Scope#$destroy
  11468. * @kind function
  11469. *
  11470. * @description
  11471. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11472. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11473. * propagate to the current scope and its children. Removal also implies that the current
  11474. * scope is eligible for garbage collection.
  11475. *
  11476. * The `$destroy()` is usually used by directives such as
  11477. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11478. * unrolling of the loop.
  11479. *
  11480. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11481. * Application code can register a `$destroy` event handler that will give it a chance to
  11482. * perform any necessary cleanup.
  11483. *
  11484. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11485. * clean up DOM bindings before an element is removed from the DOM.
  11486. */
  11487. $destroy: function() {
  11488. // we can't destroy the root scope or a scope that has been already destroyed
  11489. if (this.$$destroyed) return;
  11490. var parent = this.$parent;
  11491. this.$broadcast('$destroy');
  11492. this.$$destroyed = true;
  11493. if (this === $rootScope) return;
  11494. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11495. // sever all the references to parent scopes (after this cleanup, the current scope should
  11496. // not be retained by any of our references and should be eligible for garbage collection)
  11497. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11498. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11499. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11500. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11501. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11502. // and inline caches.
  11503. //
  11504. // see:
  11505. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11506. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11507. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11508. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11509. this.$$childTail = this.$root = null;
  11510. // don't reset these to null in case some async task tries to register a listener/watch/task
  11511. this.$$listeners = {};
  11512. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11513. // prevent NPEs since these methods have references to properties we nulled out
  11514. this.$destroy = this.$digest = this.$apply = noop;
  11515. this.$on = this.$watch = function() { return noop; };
  11516. },
  11517. /**
  11518. * @ngdoc method
  11519. * @name $rootScope.Scope#$eval
  11520. * @kind function
  11521. *
  11522. * @description
  11523. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11524. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11525. * expressions.
  11526. *
  11527. * # Example
  11528. * ```js
  11529. var scope = ng.$rootScope.Scope();
  11530. scope.a = 1;
  11531. scope.b = 2;
  11532. expect(scope.$eval('a+b')).toEqual(3);
  11533. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11534. * ```
  11535. *
  11536. * @param {(string|function())=} expression An angular expression to be executed.
  11537. *
  11538. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11539. * - `function(scope)`: execute the function with the current `scope` parameter.
  11540. *
  11541. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11542. * @returns {*} The result of evaluating the expression.
  11543. */
  11544. $eval: function(expr, locals) {
  11545. return $parse(expr)(this, locals);
  11546. },
  11547. /**
  11548. * @ngdoc method
  11549. * @name $rootScope.Scope#$evalAsync
  11550. * @kind function
  11551. *
  11552. * @description
  11553. * Executes the expression on the current scope at a later point in time.
  11554. *
  11555. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11556. * that:
  11557. *
  11558. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11559. * rendering).
  11560. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11561. * `expression` execution.
  11562. *
  11563. * Any exceptions from the execution of the expression are forwarded to the
  11564. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11565. *
  11566. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11567. * will be scheduled. However, it is encouraged to always call code that changes the model
  11568. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11569. *
  11570. * @param {(string|function())=} expression An angular expression to be executed.
  11571. *
  11572. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11573. * - `function(scope)`: execute the function with the current `scope` parameter.
  11574. *
  11575. */
  11576. $evalAsync: function(expr) {
  11577. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11578. // task also schedule async auto-flush
  11579. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11580. $browser.defer(function() {
  11581. if ($rootScope.$$asyncQueue.length) {
  11582. $rootScope.$digest();
  11583. }
  11584. });
  11585. }
  11586. this.$$asyncQueue.push({scope: this, expression: expr});
  11587. },
  11588. $$postDigest : function(fn) {
  11589. this.$$postDigestQueue.push(fn);
  11590. },
  11591. /**
  11592. * @ngdoc method
  11593. * @name $rootScope.Scope#$apply
  11594. * @kind function
  11595. *
  11596. * @description
  11597. * `$apply()` is used to execute an expression in angular from outside of the angular
  11598. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11599. * Because we are calling into the angular framework we need to perform proper scope life
  11600. * cycle of {@link ng.$exceptionHandler exception handling},
  11601. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11602. *
  11603. * ## Life cycle
  11604. *
  11605. * # Pseudo-Code of `$apply()`
  11606. * ```js
  11607. function $apply(expr) {
  11608. try {
  11609. return $eval(expr);
  11610. } catch (e) {
  11611. $exceptionHandler(e);
  11612. } finally {
  11613. $root.$digest();
  11614. }
  11615. }
  11616. * ```
  11617. *
  11618. *
  11619. * Scope's `$apply()` method transitions through the following stages:
  11620. *
  11621. * 1. The {@link guide/expression expression} is executed using the
  11622. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11623. * 2. Any exceptions from the execution of the expression are forwarded to the
  11624. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11625. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11626. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11627. *
  11628. *
  11629. * @param {(string|function())=} exp An angular expression to be executed.
  11630. *
  11631. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11632. * - `function(scope)`: execute the function with current `scope` parameter.
  11633. *
  11634. * @returns {*} The result of evaluating the expression.
  11635. */
  11636. $apply: function(expr) {
  11637. try {
  11638. beginPhase('$apply');
  11639. return this.$eval(expr);
  11640. } catch (e) {
  11641. $exceptionHandler(e);
  11642. } finally {
  11643. clearPhase();
  11644. try {
  11645. $rootScope.$digest();
  11646. } catch (e) {
  11647. $exceptionHandler(e);
  11648. throw e;
  11649. }
  11650. }
  11651. },
  11652. /**
  11653. * @ngdoc method
  11654. * @name $rootScope.Scope#$on
  11655. * @kind function
  11656. *
  11657. * @description
  11658. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11659. * discussion of event life cycle.
  11660. *
  11661. * The event listener function format is: `function(event, args...)`. The `event` object
  11662. * passed into the listener has the following attributes:
  11663. *
  11664. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11665. * `$broadcast`-ed.
  11666. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11667. * - `name` - `{string}`: name of the event.
  11668. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11669. * further event propagation (available only for events that were `$emit`-ed).
  11670. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11671. * to true.
  11672. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11673. *
  11674. * @param {string} name Event name to listen on.
  11675. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11676. * @returns {function()} Returns a deregistration function for this listener.
  11677. */
  11678. $on: function(name, listener) {
  11679. var namedListeners = this.$$listeners[name];
  11680. if (!namedListeners) {
  11681. this.$$listeners[name] = namedListeners = [];
  11682. }
  11683. namedListeners.push(listener);
  11684. var current = this;
  11685. do {
  11686. if (!current.$$listenerCount[name]) {
  11687. current.$$listenerCount[name] = 0;
  11688. }
  11689. current.$$listenerCount[name]++;
  11690. } while ((current = current.$parent));
  11691. var self = this;
  11692. return function() {
  11693. var indexOfListener = indexOf(namedListeners, listener);
  11694. if (indexOfListener !== -1) {
  11695. namedListeners[indexOfListener] = null;
  11696. decrementListenerCount(self, 1, name);
  11697. }
  11698. };
  11699. },
  11700. /**
  11701. * @ngdoc method
  11702. * @name $rootScope.Scope#$emit
  11703. * @kind function
  11704. *
  11705. * @description
  11706. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11707. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11708. *
  11709. * The event life cycle starts at the scope on which `$emit` was called. All
  11710. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11711. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11712. * registered listeners along the way. The event will stop propagating if one of the listeners
  11713. * cancels it.
  11714. *
  11715. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11716. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11717. *
  11718. * @param {string} name Event name to emit.
  11719. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11720. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11721. */
  11722. $emit: function(name, args) {
  11723. var empty = [],
  11724. namedListeners,
  11725. scope = this,
  11726. stopPropagation = false,
  11727. event = {
  11728. name: name,
  11729. targetScope: scope,
  11730. stopPropagation: function() {stopPropagation = true;},
  11731. preventDefault: function() {
  11732. event.defaultPrevented = true;
  11733. },
  11734. defaultPrevented: false
  11735. },
  11736. listenerArgs = concat([event], arguments, 1),
  11737. i, length;
  11738. do {
  11739. namedListeners = scope.$$listeners[name] || empty;
  11740. event.currentScope = scope;
  11741. for (i=0, length=namedListeners.length; i<length; i++) {
  11742. // if listeners were deregistered, defragment the array
  11743. if (!namedListeners[i]) {
  11744. namedListeners.splice(i, 1);
  11745. i--;
  11746. length--;
  11747. continue;
  11748. }
  11749. try {
  11750. //allow all listeners attached to the current scope to run
  11751. namedListeners[i].apply(null, listenerArgs);
  11752. } catch (e) {
  11753. $exceptionHandler(e);
  11754. }
  11755. }
  11756. //if any listener on the current scope stops propagation, prevent bubbling
  11757. if (stopPropagation) return event;
  11758. //traverse upwards
  11759. scope = scope.$parent;
  11760. } while (scope);
  11761. return event;
  11762. },
  11763. /**
  11764. * @ngdoc method
  11765. * @name $rootScope.Scope#$broadcast
  11766. * @kind function
  11767. *
  11768. * @description
  11769. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11770. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11771. *
  11772. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11773. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11774. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11775. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11776. *
  11777. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11778. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11779. *
  11780. * @param {string} name Event name to broadcast.
  11781. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11782. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11783. */
  11784. $broadcast: function(name, args) {
  11785. var target = this,
  11786. current = target,
  11787. next = target,
  11788. event = {
  11789. name: name,
  11790. targetScope: target,
  11791. preventDefault: function() {
  11792. event.defaultPrevented = true;
  11793. },
  11794. defaultPrevented: false
  11795. },
  11796. listenerArgs = concat([event], arguments, 1),
  11797. listeners, i, length;
  11798. //down while you can, then up and next sibling or up and next sibling until back at root
  11799. while ((current = next)) {
  11800. event.currentScope = current;
  11801. listeners = current.$$listeners[name] || [];
  11802. for (i=0, length = listeners.length; i<length; i++) {
  11803. // if listeners were deregistered, defragment the array
  11804. if (!listeners[i]) {
  11805. listeners.splice(i, 1);
  11806. i--;
  11807. length--;
  11808. continue;
  11809. }
  11810. try {
  11811. listeners[i].apply(null, listenerArgs);
  11812. } catch(e) {
  11813. $exceptionHandler(e);
  11814. }
  11815. }
  11816. // Insanity Warning: scope depth-first traversal
  11817. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11818. // this piece should be kept in sync with the traversal in $digest
  11819. // (though it differs due to having the extra check for $$listenerCount)
  11820. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11821. (current !== target && current.$$nextSibling)))) {
  11822. while(current !== target && !(next = current.$$nextSibling)) {
  11823. current = current.$parent;
  11824. }
  11825. }
  11826. }
  11827. return event;
  11828. }
  11829. };
  11830. var $rootScope = new Scope();
  11831. return $rootScope;
  11832. function beginPhase(phase) {
  11833. if ($rootScope.$$phase) {
  11834. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11835. }
  11836. $rootScope.$$phase = phase;
  11837. }
  11838. function clearPhase() {
  11839. $rootScope.$$phase = null;
  11840. }
  11841. function compileToFn(exp, name) {
  11842. var fn = $parse(exp);
  11843. assertArgFn(fn, name);
  11844. return fn;
  11845. }
  11846. function decrementListenerCount(current, count, name) {
  11847. do {
  11848. current.$$listenerCount[name] -= count;
  11849. if (current.$$listenerCount[name] === 0) {
  11850. delete current.$$listenerCount[name];
  11851. }
  11852. } while ((current = current.$parent));
  11853. }
  11854. /**
  11855. * function used as an initial value for watchers.
  11856. * because it's unique we can easily tell it apart from other values
  11857. */
  11858. function initWatchVal() {}
  11859. }];
  11860. }
  11861. /**
  11862. * @description
  11863. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11864. */
  11865. function $$SanitizeUriProvider() {
  11866. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11867. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file):|data:image\/)/;
  11868. /**
  11869. * @description
  11870. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11871. * urls during a[href] sanitization.
  11872. *
  11873. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11874. *
  11875. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11876. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11877. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11878. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11879. *
  11880. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11881. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11882. * chaining otherwise.
  11883. */
  11884. this.aHrefSanitizationWhitelist = function(regexp) {
  11885. if (isDefined(regexp)) {
  11886. aHrefSanitizationWhitelist = regexp;
  11887. return this;
  11888. }
  11889. return aHrefSanitizationWhitelist;
  11890. };
  11891. /**
  11892. * @description
  11893. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11894. * urls during img[src] sanitization.
  11895. *
  11896. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11897. *
  11898. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11899. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11900. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11901. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11902. *
  11903. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11904. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11905. * chaining otherwise.
  11906. */
  11907. this.imgSrcSanitizationWhitelist = function(regexp) {
  11908. if (isDefined(regexp)) {
  11909. imgSrcSanitizationWhitelist = regexp;
  11910. return this;
  11911. }
  11912. return imgSrcSanitizationWhitelist;
  11913. };
  11914. this.$get = function() {
  11915. return function sanitizeUri(uri, isImage) {
  11916. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11917. var normalizedVal;
  11918. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11919. if (!msie || msie >= 8 ) {
  11920. normalizedVal = urlResolve(uri).href;
  11921. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11922. return 'unsafe:'+normalizedVal;
  11923. }
  11924. }
  11925. return uri;
  11926. };
  11927. };
  11928. }
  11929. var $sceMinErr = minErr('$sce');
  11930. var SCE_CONTEXTS = {
  11931. HTML: 'html',
  11932. CSS: 'css',
  11933. URL: 'url',
  11934. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11935. // url. (e.g. ng-include, script src, templateUrl)
  11936. RESOURCE_URL: 'resourceUrl',
  11937. JS: 'js'
  11938. };
  11939. // Helper functions follow.
  11940. // Copied from:
  11941. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11942. // Prereq: s is a string.
  11943. function escapeForRegexp(s) {
  11944. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11945. replace(/\x08/g, '\\x08');
  11946. }
  11947. function adjustMatcher(matcher) {
  11948. if (matcher === 'self') {
  11949. return matcher;
  11950. } else if (isString(matcher)) {
  11951. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11952. // '*' matches any character except those from the set ':/.?&'.
  11953. // '**' matches any character (like .* in a RegExp).
  11954. // More than 2 *'s raises an error as it's ill defined.
  11955. if (matcher.indexOf('***') > -1) {
  11956. throw $sceMinErr('iwcard',
  11957. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11958. }
  11959. matcher = escapeForRegexp(matcher).
  11960. replace('\\*\\*', '.*').
  11961. replace('\\*', '[^:/.?&;]*');
  11962. return new RegExp('^' + matcher + '$');
  11963. } else if (isRegExp(matcher)) {
  11964. // The only other type of matcher allowed is a Regexp.
  11965. // Match entire URL / disallow partial matches.
  11966. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11967. return new RegExp('^' + matcher.source + '$');
  11968. } else {
  11969. throw $sceMinErr('imatcher',
  11970. 'Matchers may only be "self", string patterns or RegExp objects');
  11971. }
  11972. }
  11973. function adjustMatchers(matchers) {
  11974. var adjustedMatchers = [];
  11975. if (isDefined(matchers)) {
  11976. forEach(matchers, function(matcher) {
  11977. adjustedMatchers.push(adjustMatcher(matcher));
  11978. });
  11979. }
  11980. return adjustedMatchers;
  11981. }
  11982. /**
  11983. * @ngdoc service
  11984. * @name $sceDelegate
  11985. * @kind function
  11986. *
  11987. * @description
  11988. *
  11989. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11990. * Contextual Escaping (SCE)} services to AngularJS.
  11991. *
  11992. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11993. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11994. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11995. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11996. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11997. *
  11998. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11999. *
  12000. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  12001. * can override it completely to change the behavior of `$sce`, the common case would
  12002. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  12003. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  12004. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  12005. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  12006. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  12007. */
  12008. /**
  12009. * @ngdoc provider
  12010. * @name $sceDelegateProvider
  12011. * @description
  12012. *
  12013. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  12014. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  12015. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  12016. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  12017. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  12018. *
  12019. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  12020. * Strict Contextual Escaping (SCE)}.
  12021. *
  12022. * **Example**: Consider the following case. <a name="example"></a>
  12023. *
  12024. * - your app is hosted at url `http://myapp.example.com/`
  12025. * - but some of your templates are hosted on other domains you control such as
  12026. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  12027. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  12028. *
  12029. * Here is what a secure configuration for this scenario might look like:
  12030. *
  12031. * ```
  12032. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  12033. * $sceDelegateProvider.resourceUrlWhitelist([
  12034. * // Allow same origin resource loads.
  12035. * 'self',
  12036. * // Allow loading from our assets domain. Notice the difference between * and **.
  12037. * 'http://srv*.assets.example.com/**'
  12038. * ]);
  12039. *
  12040. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  12041. * $sceDelegateProvider.resourceUrlBlacklist([
  12042. * 'http://myapp.example.com/clickThru**'
  12043. * ]);
  12044. * });
  12045. * ```
  12046. */
  12047. function $SceDelegateProvider() {
  12048. this.SCE_CONTEXTS = SCE_CONTEXTS;
  12049. // Resource URLs can also be trusted by policy.
  12050. var resourceUrlWhitelist = ['self'],
  12051. resourceUrlBlacklist = [];
  12052. /**
  12053. * @ngdoc method
  12054. * @name $sceDelegateProvider#resourceUrlWhitelist
  12055. * @kind function
  12056. *
  12057. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  12058. * provided. This must be an array or null. A snapshot of this array is used so further
  12059. * changes to the array are ignored.
  12060. *
  12061. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12062. * allowed in this array.
  12063. *
  12064. * Note: **an empty whitelist array will block all URLs**!
  12065. *
  12066. * @return {Array} the currently set whitelist array.
  12067. *
  12068. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  12069. * same origin resource requests.
  12070. *
  12071. * @description
  12072. * Sets/Gets the whitelist of trusted resource URLs.
  12073. */
  12074. this.resourceUrlWhitelist = function (value) {
  12075. if (arguments.length) {
  12076. resourceUrlWhitelist = adjustMatchers(value);
  12077. }
  12078. return resourceUrlWhitelist;
  12079. };
  12080. /**
  12081. * @ngdoc method
  12082. * @name $sceDelegateProvider#resourceUrlBlacklist
  12083. * @kind function
  12084. *
  12085. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  12086. * provided. This must be an array or null. A snapshot of this array is used so further
  12087. * changes to the array are ignored.
  12088. *
  12089. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12090. * allowed in this array.
  12091. *
  12092. * The typical usage for the blacklist is to **block
  12093. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  12094. * these would otherwise be trusted but actually return content from the redirected domain.
  12095. *
  12096. * Finally, **the blacklist overrides the whitelist** and has the final say.
  12097. *
  12098. * @return {Array} the currently set blacklist array.
  12099. *
  12100. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  12101. * is no blacklist.)
  12102. *
  12103. * @description
  12104. * Sets/Gets the blacklist of trusted resource URLs.
  12105. */
  12106. this.resourceUrlBlacklist = function (value) {
  12107. if (arguments.length) {
  12108. resourceUrlBlacklist = adjustMatchers(value);
  12109. }
  12110. return resourceUrlBlacklist;
  12111. };
  12112. this.$get = ['$injector', function($injector) {
  12113. var htmlSanitizer = function htmlSanitizer(html) {
  12114. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12115. };
  12116. if ($injector.has('$sanitize')) {
  12117. htmlSanitizer = $injector.get('$sanitize');
  12118. }
  12119. function matchUrl(matcher, parsedUrl) {
  12120. if (matcher === 'self') {
  12121. return urlIsSameOrigin(parsedUrl);
  12122. } else {
  12123. // definitely a regex. See adjustMatchers()
  12124. return !!matcher.exec(parsedUrl.href);
  12125. }
  12126. }
  12127. function isResourceUrlAllowedByPolicy(url) {
  12128. var parsedUrl = urlResolve(url.toString());
  12129. var i, n, allowed = false;
  12130. // Ensure that at least one item from the whitelist allows this url.
  12131. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  12132. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  12133. allowed = true;
  12134. break;
  12135. }
  12136. }
  12137. if (allowed) {
  12138. // Ensure that no item from the blacklist blocked this url.
  12139. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  12140. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  12141. allowed = false;
  12142. break;
  12143. }
  12144. }
  12145. }
  12146. return allowed;
  12147. }
  12148. function generateHolderType(Base) {
  12149. var holderType = function TrustedValueHolderType(trustedValue) {
  12150. this.$$unwrapTrustedValue = function() {
  12151. return trustedValue;
  12152. };
  12153. };
  12154. if (Base) {
  12155. holderType.prototype = new Base();
  12156. }
  12157. holderType.prototype.valueOf = function sceValueOf() {
  12158. return this.$$unwrapTrustedValue();
  12159. };
  12160. holderType.prototype.toString = function sceToString() {
  12161. return this.$$unwrapTrustedValue().toString();
  12162. };
  12163. return holderType;
  12164. }
  12165. var trustedValueHolderBase = generateHolderType(),
  12166. byType = {};
  12167. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  12168. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  12169. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  12170. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  12171. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  12172. /**
  12173. * @ngdoc method
  12174. * @name $sceDelegate#trustAs
  12175. *
  12176. * @description
  12177. * Returns an object that is trusted by angular for use in specified strict
  12178. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  12179. * attribute interpolation, any dom event binding attribute interpolation
  12180. * such as for onclick, etc.) that uses the provided value.
  12181. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  12182. *
  12183. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12184. * resourceUrl, html, js and css.
  12185. * @param {*} value The value that that should be considered trusted/safe.
  12186. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12187. * where Angular expects a $sce.trustAs() return value.
  12188. */
  12189. function trustAs(type, trustedValue) {
  12190. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12191. if (!Constructor) {
  12192. throw $sceMinErr('icontext',
  12193. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  12194. type, trustedValue);
  12195. }
  12196. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  12197. return trustedValue;
  12198. }
  12199. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  12200. // mutable objects, we ensure here that the value passed in is actually a string.
  12201. if (typeof trustedValue !== 'string') {
  12202. throw $sceMinErr('itype',
  12203. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  12204. type);
  12205. }
  12206. return new Constructor(trustedValue);
  12207. }
  12208. /**
  12209. * @ngdoc method
  12210. * @name $sceDelegate#valueOf
  12211. *
  12212. * @description
  12213. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  12214. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  12215. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  12216. *
  12217. * If the passed parameter is not a value that had been returned by {@link
  12218. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  12219. *
  12220. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  12221. * call or anything else.
  12222. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  12223. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  12224. * `value` unchanged.
  12225. */
  12226. function valueOf(maybeTrusted) {
  12227. if (maybeTrusted instanceof trustedValueHolderBase) {
  12228. return maybeTrusted.$$unwrapTrustedValue();
  12229. } else {
  12230. return maybeTrusted;
  12231. }
  12232. }
  12233. /**
  12234. * @ngdoc method
  12235. * @name $sceDelegate#getTrusted
  12236. *
  12237. * @description
  12238. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  12239. * returns the originally supplied value if the queried context type is a supertype of the
  12240. * created type. If this condition isn't satisfied, throws an exception.
  12241. *
  12242. * @param {string} type The kind of context in which this value is to be used.
  12243. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  12244. * `$sceDelegate.trustAs`} call.
  12245. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  12246. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  12247. */
  12248. function getTrusted(type, maybeTrusted) {
  12249. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  12250. return maybeTrusted;
  12251. }
  12252. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12253. if (constructor && maybeTrusted instanceof constructor) {
  12254. return maybeTrusted.$$unwrapTrustedValue();
  12255. }
  12256. // If we get here, then we may only take one of two actions.
  12257. // 1. sanitize the value for the requested type, or
  12258. // 2. throw an exception.
  12259. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  12260. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  12261. return maybeTrusted;
  12262. } else {
  12263. throw $sceMinErr('insecurl',
  12264. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  12265. maybeTrusted.toString());
  12266. }
  12267. } else if (type === SCE_CONTEXTS.HTML) {
  12268. return htmlSanitizer(maybeTrusted);
  12269. }
  12270. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12271. }
  12272. return { trustAs: trustAs,
  12273. getTrusted: getTrusted,
  12274. valueOf: valueOf };
  12275. }];
  12276. }
  12277. /**
  12278. * @ngdoc provider
  12279. * @name $sceProvider
  12280. * @description
  12281. *
  12282. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  12283. * - enable/disable Strict Contextual Escaping (SCE) in a module
  12284. * - override the default implementation with a custom delegate
  12285. *
  12286. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  12287. */
  12288. /* jshint maxlen: false*/
  12289. /**
  12290. * @ngdoc service
  12291. * @name $sce
  12292. * @kind function
  12293. *
  12294. * @description
  12295. *
  12296. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  12297. *
  12298. * # Strict Contextual Escaping
  12299. *
  12300. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  12301. * contexts to result in a value that is marked as safe to use for that context. One example of
  12302. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  12303. * to these contexts as privileged or SCE contexts.
  12304. *
  12305. * As of version 1.2, Angular ships with SCE enabled by default.
  12306. *
  12307. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  12308. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  12309. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  12310. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  12311. * to the top of your HTML document.
  12312. *
  12313. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  12314. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  12315. *
  12316. * Here's an example of a binding in a privileged context:
  12317. *
  12318. * ```
  12319. * <input ng-model="userHtml">
  12320. * <div ng-bind-html="userHtml"></div>
  12321. * ```
  12322. *
  12323. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  12324. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  12325. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  12326. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  12327. * security vulnerabilities.)
  12328. *
  12329. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  12330. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  12331. *
  12332. * How would you ensure that every place that used these types of bindings was bound to a value that
  12333. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  12334. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  12335. * properties/fields and forgot to update the binding to the sanitized value?
  12336. *
  12337. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  12338. * determine that something explicitly says it's safe to use a value for binding in that
  12339. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  12340. * for those values that you can easily tell are safe - because they were received from your server,
  12341. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  12342. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  12343. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  12344. *
  12345. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  12346. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  12347. * obtain values that will be accepted by SCE / privileged contexts.
  12348. *
  12349. *
  12350. * ## How does it work?
  12351. *
  12352. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  12353. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  12354. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  12355. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  12356. *
  12357. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  12358. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  12359. * simplified):
  12360. *
  12361. * ```
  12362. * var ngBindHtmlDirective = ['$sce', function($sce) {
  12363. * return function(scope, element, attr) {
  12364. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  12365. * element.html(value || '');
  12366. * });
  12367. * };
  12368. * }];
  12369. * ```
  12370. *
  12371. * ## Impact on loading templates
  12372. *
  12373. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12374. * `templateUrl`'s specified by {@link guide/directive directives}.
  12375. *
  12376. * By default, Angular only loads templates from the same domain and protocol as the application
  12377. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12378. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12379. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12380. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12381. *
  12382. * *Please note*:
  12383. * The browser's
  12384. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12385. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12386. * policy apply in addition to this and may further restrict whether the template is successfully
  12387. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12388. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12389. * browsers.
  12390. *
  12391. * ## This feels like too much overhead for the developer?
  12392. *
  12393. * It's important to remember that SCE only applies to interpolation expressions.
  12394. *
  12395. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12396. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12397. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12398. *
  12399. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12400. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12401. *
  12402. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12403. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12404. * It blocks loading templates from other domains or loading templates over http from an https
  12405. * served document. You can change these by setting your own custom {@link
  12406. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12407. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12408. *
  12409. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12410. * application that's secure and can be audited to verify that with much more ease than bolting
  12411. * security onto an application later.
  12412. *
  12413. * <a name="contexts"></a>
  12414. * ## What trusted context types are supported?
  12415. *
  12416. * | Context | Notes |
  12417. * |---------------------|----------------|
  12418. * | `$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. |
  12419. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12420. * | `$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. |
  12421. * | `$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. |
  12422. * | `$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. |
  12423. *
  12424. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12425. *
  12426. * Each element in these arrays must be one of the following:
  12427. *
  12428. * - **'self'**
  12429. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12430. * domain** as the application document using the **same protocol**.
  12431. * - **String** (except the special value `'self'`)
  12432. * - The string is matched against the full *normalized / absolute URL* of the resource
  12433. * being tested (substring matches are not good enough.)
  12434. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12435. * match themselves.
  12436. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12437. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12438. * in a whitelist.
  12439. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12440. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12441. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12442. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  12443. * http://foo.example.com/templates/**).
  12444. * - **RegExp** (*see caveat below*)
  12445. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12446. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12447. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12448. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12449. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12450. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12451. * is highly recommended to use the string patterns and only fall back to regular expressions
  12452. * if they as a last resort.
  12453. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12454. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12455. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12456. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12457. * - If you are generating your JavaScript from some other templating engine (not
  12458. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12459. * remember to escape your regular expression (and be aware that you might need more than
  12460. * one level of escaping depending on your templating engine and the way you interpolated
  12461. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12462. * enough before coding your own. e.g. Ruby has
  12463. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12464. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12465. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12466. * Closure library's [goog.string.regExpEscape(s)](
  12467. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12468. *
  12469. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12470. *
  12471. * ## Show me an example using SCE.
  12472. *
  12473. * <example module="mySceApp" deps="angular-sanitize.js">
  12474. * <file name="index.html">
  12475. * <div ng-controller="myAppController as myCtrl">
  12476. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12477. * <b>User comments</b><br>
  12478. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12479. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12480. * exploit.
  12481. * <div class="well">
  12482. * <div ng-repeat="userComment in myCtrl.userComments">
  12483. * <b>{{userComment.name}}</b>:
  12484. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12485. * <br>
  12486. * </div>
  12487. * </div>
  12488. * </div>
  12489. * </file>
  12490. *
  12491. * <file name="script.js">
  12492. * var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12493. *
  12494. * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12495. * var self = this;
  12496. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12497. * self.userComments = userComments;
  12498. * });
  12499. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12500. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12501. * 'sanitization.&quot;">Hover over this text.</span>');
  12502. * });
  12503. * </file>
  12504. *
  12505. * <file name="test_data.json">
  12506. * [
  12507. * { "name": "Alice",
  12508. * "htmlComment":
  12509. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12510. * },
  12511. * { "name": "Bob",
  12512. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12513. * }
  12514. * ]
  12515. * </file>
  12516. *
  12517. * <file name="protractor.js" type="protractor">
  12518. * describe('SCE doc demo', function() {
  12519. * it('should sanitize untrusted values', function() {
  12520. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  12521. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12522. * });
  12523. *
  12524. * it('should NOT sanitize explicitly trusted values', function() {
  12525. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12526. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12527. * 'sanitization.&quot;">Hover over this text.</span>');
  12528. * });
  12529. * });
  12530. * </file>
  12531. * </example>
  12532. *
  12533. *
  12534. *
  12535. * ## Can I disable SCE completely?
  12536. *
  12537. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12538. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12539. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12540. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12541. * you're migrating them a module at a time.
  12542. *
  12543. * That said, here's how you can completely disable SCE:
  12544. *
  12545. * ```
  12546. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12547. * // Completely disable SCE. For demonstration purposes only!
  12548. * // Do not use in new projects.
  12549. * $sceProvider.enabled(false);
  12550. * });
  12551. * ```
  12552. *
  12553. */
  12554. /* jshint maxlen: 100 */
  12555. function $SceProvider() {
  12556. var enabled = true;
  12557. /**
  12558. * @ngdoc method
  12559. * @name $sceProvider#enabled
  12560. * @kind function
  12561. *
  12562. * @param {boolean=} value If provided, then enables/disables SCE.
  12563. * @return {boolean} true if SCE is enabled, false otherwise.
  12564. *
  12565. * @description
  12566. * Enables/disables SCE and returns the current value.
  12567. */
  12568. this.enabled = function (value) {
  12569. if (arguments.length) {
  12570. enabled = !!value;
  12571. }
  12572. return enabled;
  12573. };
  12574. /* Design notes on the default implementation for SCE.
  12575. *
  12576. * The API contract for the SCE delegate
  12577. * -------------------------------------
  12578. * The SCE delegate object must provide the following 3 methods:
  12579. *
  12580. * - trustAs(contextEnum, value)
  12581. * This method is used to tell the SCE service that the provided value is OK to use in the
  12582. * contexts specified by contextEnum. It must return an object that will be accepted by
  12583. * getTrusted() for a compatible contextEnum and return this value.
  12584. *
  12585. * - valueOf(value)
  12586. * For values that were not produced by trustAs(), return them as is. For values that were
  12587. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12588. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12589. * such a value.
  12590. *
  12591. * - getTrusted(contextEnum, value)
  12592. * This function should return the a value that is safe to use in the context specified by
  12593. * contextEnum or throw and exception otherwise.
  12594. *
  12595. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12596. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12597. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12598. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12599. * return the same object passed in if it was found in the registry under a compatible context or
  12600. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12601. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12602. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12603. *
  12604. *
  12605. * A note on the inheritance model for SCE contexts
  12606. * ------------------------------------------------
  12607. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12608. * is purely an implementation details.
  12609. *
  12610. * The contract is simply this:
  12611. *
  12612. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12613. * will also succeed.
  12614. *
  12615. * Inheritance happens to capture this in a natural way. In some future, we
  12616. * may not use inheritance anymore. That is OK because no code outside of
  12617. * sce.js and sceSpecs.js would need to be aware of this detail.
  12618. */
  12619. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12620. $parse, $sniffer, $sceDelegate) {
  12621. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12622. // the "expression(javascript expression)" syntax which is insecure.
  12623. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12624. throw $sceMinErr('iequirks',
  12625. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12626. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12627. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12628. }
  12629. var sce = shallowCopy(SCE_CONTEXTS);
  12630. /**
  12631. * @ngdoc method
  12632. * @name $sce#isEnabled
  12633. * @kind function
  12634. *
  12635. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12636. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12637. *
  12638. * @description
  12639. * Returns a boolean indicating if SCE is enabled.
  12640. */
  12641. sce.isEnabled = function () {
  12642. return enabled;
  12643. };
  12644. sce.trustAs = $sceDelegate.trustAs;
  12645. sce.getTrusted = $sceDelegate.getTrusted;
  12646. sce.valueOf = $sceDelegate.valueOf;
  12647. if (!enabled) {
  12648. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12649. sce.valueOf = identity;
  12650. }
  12651. /**
  12652. * @ngdoc method
  12653. * @name $sce#parseAs
  12654. *
  12655. * @description
  12656. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12657. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12658. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12659. * *result*)}
  12660. *
  12661. * @param {string} type The kind of SCE context in which this result will be used.
  12662. * @param {string} expression String expression to compile.
  12663. * @returns {function(context, locals)} a function which represents the compiled expression:
  12664. *
  12665. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12666. * are evaluated against (typically a scope object).
  12667. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12668. * `context`.
  12669. */
  12670. sce.parseAs = function sceParseAs(type, expr) {
  12671. var parsed = $parse(expr);
  12672. if (parsed.literal && parsed.constant) {
  12673. return parsed;
  12674. } else {
  12675. return function sceParseAsTrusted(self, locals) {
  12676. return sce.getTrusted(type, parsed(self, locals));
  12677. };
  12678. }
  12679. };
  12680. /**
  12681. * @ngdoc method
  12682. * @name $sce#trustAs
  12683. *
  12684. * @description
  12685. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12686. * returns an object that is trusted by angular for use in specified strict contextual
  12687. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12688. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12689. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12690. * escaping.
  12691. *
  12692. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12693. * resource_url, html, js and css.
  12694. * @param {*} value The value that that should be considered trusted/safe.
  12695. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12696. * where Angular expects a $sce.trustAs() return value.
  12697. */
  12698. /**
  12699. * @ngdoc method
  12700. * @name $sce#trustAsHtml
  12701. *
  12702. * @description
  12703. * Shorthand method. `$sce.trustAsHtml(value)` →
  12704. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12705. *
  12706. * @param {*} value The value to trustAs.
  12707. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12708. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12709. * only accept expressions that are either literal constants or are the
  12710. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12711. */
  12712. /**
  12713. * @ngdoc method
  12714. * @name $sce#trustAsUrl
  12715. *
  12716. * @description
  12717. * Shorthand method. `$sce.trustAsUrl(value)` →
  12718. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12719. *
  12720. * @param {*} value The value to trustAs.
  12721. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12722. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12723. * only accept expressions that are either literal constants or are the
  12724. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12725. */
  12726. /**
  12727. * @ngdoc method
  12728. * @name $sce#trustAsResourceUrl
  12729. *
  12730. * @description
  12731. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12732. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12733. *
  12734. * @param {*} value The value to trustAs.
  12735. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12736. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12737. * only accept expressions that are either literal constants or are the return
  12738. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12739. */
  12740. /**
  12741. * @ngdoc method
  12742. * @name $sce#trustAsJs
  12743. *
  12744. * @description
  12745. * Shorthand method. `$sce.trustAsJs(value)` →
  12746. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12747. *
  12748. * @param {*} value The value to trustAs.
  12749. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12750. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12751. * only accept expressions that are either literal constants or are the
  12752. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12753. */
  12754. /**
  12755. * @ngdoc method
  12756. * @name $sce#getTrusted
  12757. *
  12758. * @description
  12759. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12760. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12761. * originally supplied value if the queried context type is a supertype of the created type.
  12762. * If this condition isn't satisfied, throws an exception.
  12763. *
  12764. * @param {string} type The kind of context in which this value is to be used.
  12765. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12766. * call.
  12767. * @returns {*} The value the was originally provided to
  12768. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12769. * Otherwise, throws an exception.
  12770. */
  12771. /**
  12772. * @ngdoc method
  12773. * @name $sce#getTrustedHtml
  12774. *
  12775. * @description
  12776. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12777. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12778. *
  12779. * @param {*} value The value to pass to `$sce.getTrusted`.
  12780. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12781. */
  12782. /**
  12783. * @ngdoc method
  12784. * @name $sce#getTrustedCss
  12785. *
  12786. * @description
  12787. * Shorthand method. `$sce.getTrustedCss(value)` →
  12788. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12789. *
  12790. * @param {*} value The value to pass to `$sce.getTrusted`.
  12791. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12792. */
  12793. /**
  12794. * @ngdoc method
  12795. * @name $sce#getTrustedUrl
  12796. *
  12797. * @description
  12798. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12799. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12800. *
  12801. * @param {*} value The value to pass to `$sce.getTrusted`.
  12802. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12803. */
  12804. /**
  12805. * @ngdoc method
  12806. * @name $sce#getTrustedResourceUrl
  12807. *
  12808. * @description
  12809. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12810. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12811. *
  12812. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12813. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12814. */
  12815. /**
  12816. * @ngdoc method
  12817. * @name $sce#getTrustedJs
  12818. *
  12819. * @description
  12820. * Shorthand method. `$sce.getTrustedJs(value)` →
  12821. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12822. *
  12823. * @param {*} value The value to pass to `$sce.getTrusted`.
  12824. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12825. */
  12826. /**
  12827. * @ngdoc method
  12828. * @name $sce#parseAsHtml
  12829. *
  12830. * @description
  12831. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12832. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12833. *
  12834. * @param {string} expression String expression to compile.
  12835. * @returns {function(context, locals)} a function which represents the compiled expression:
  12836. *
  12837. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12838. * are evaluated against (typically a scope object).
  12839. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12840. * `context`.
  12841. */
  12842. /**
  12843. * @ngdoc method
  12844. * @name $sce#parseAsCss
  12845. *
  12846. * @description
  12847. * Shorthand method. `$sce.parseAsCss(value)` →
  12848. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12849. *
  12850. * @param {string} expression String expression to compile.
  12851. * @returns {function(context, locals)} a function which represents the compiled expression:
  12852. *
  12853. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12854. * are evaluated against (typically a scope object).
  12855. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12856. * `context`.
  12857. */
  12858. /**
  12859. * @ngdoc method
  12860. * @name $sce#parseAsUrl
  12861. *
  12862. * @description
  12863. * Shorthand method. `$sce.parseAsUrl(value)` →
  12864. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12865. *
  12866. * @param {string} expression String expression to compile.
  12867. * @returns {function(context, locals)} a function which represents the compiled expression:
  12868. *
  12869. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12870. * are evaluated against (typically a scope object).
  12871. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12872. * `context`.
  12873. */
  12874. /**
  12875. * @ngdoc method
  12876. * @name $sce#parseAsResourceUrl
  12877. *
  12878. * @description
  12879. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12880. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12881. *
  12882. * @param {string} expression String expression to compile.
  12883. * @returns {function(context, locals)} a function which represents the compiled expression:
  12884. *
  12885. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12886. * are evaluated against (typically a scope object).
  12887. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12888. * `context`.
  12889. */
  12890. /**
  12891. * @ngdoc method
  12892. * @name $sce#parseAsJs
  12893. *
  12894. * @description
  12895. * Shorthand method. `$sce.parseAsJs(value)` →
  12896. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12897. *
  12898. * @param {string} expression String expression to compile.
  12899. * @returns {function(context, locals)} a function which represents the compiled expression:
  12900. *
  12901. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12902. * are evaluated against (typically a scope object).
  12903. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12904. * `context`.
  12905. */
  12906. // Shorthand delegations.
  12907. var parse = sce.parseAs,
  12908. getTrusted = sce.getTrusted,
  12909. trustAs = sce.trustAs;
  12910. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12911. var lName = lowercase(name);
  12912. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12913. return parse(enumValue, expr);
  12914. };
  12915. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12916. return getTrusted(enumValue, value);
  12917. };
  12918. sce[camelCase("trust_as_" + lName)] = function (value) {
  12919. return trustAs(enumValue, value);
  12920. };
  12921. });
  12922. return sce;
  12923. }];
  12924. }
  12925. /**
  12926. * !!! This is an undocumented "private" service !!!
  12927. *
  12928. * @name $sniffer
  12929. * @requires $window
  12930. * @requires $document
  12931. *
  12932. * @property {boolean} history Does the browser support html5 history api ?
  12933. * @property {boolean} hashchange Does the browser support hashchange event ?
  12934. * @property {boolean} transitions Does the browser support CSS transition events ?
  12935. * @property {boolean} animations Does the browser support CSS animation events ?
  12936. *
  12937. * @description
  12938. * This is very simple implementation of testing browser's features.
  12939. */
  12940. function $SnifferProvider() {
  12941. this.$get = ['$window', '$document', function($window, $document) {
  12942. var eventSupport = {},
  12943. android =
  12944. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12945. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12946. document = $document[0] || {},
  12947. documentMode = document.documentMode,
  12948. vendorPrefix,
  12949. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12950. bodyStyle = document.body && document.body.style,
  12951. transitions = false,
  12952. animations = false,
  12953. match;
  12954. if (bodyStyle) {
  12955. for(var prop in bodyStyle) {
  12956. if(match = vendorRegex.exec(prop)) {
  12957. vendorPrefix = match[0];
  12958. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12959. break;
  12960. }
  12961. }
  12962. if(!vendorPrefix) {
  12963. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12964. }
  12965. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12966. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12967. if (android && (!transitions||!animations)) {
  12968. transitions = isString(document.body.style.webkitTransition);
  12969. animations = isString(document.body.style.webkitAnimation);
  12970. }
  12971. }
  12972. return {
  12973. // Android has history.pushState, but it does not update location correctly
  12974. // so let's not use the history API at all.
  12975. // http://code.google.com/p/android/issues/detail?id=17471
  12976. // https://github.com/angular/angular.js/issues/904
  12977. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12978. // so let's not use the history API also
  12979. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12980. // jshint -W018
  12981. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12982. // jshint +W018
  12983. hashchange: 'onhashchange' in $window &&
  12984. // IE8 compatible mode lies
  12985. (!documentMode || documentMode > 7),
  12986. hasEvent: function(event) {
  12987. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12988. // it. In particular the event is not fired when backspace or delete key are pressed or
  12989. // when cut operation is performed.
  12990. if (event == 'input' && msie == 9) return false;
  12991. if (isUndefined(eventSupport[event])) {
  12992. var divElm = document.createElement('div');
  12993. eventSupport[event] = 'on' + event in divElm;
  12994. }
  12995. return eventSupport[event];
  12996. },
  12997. csp: csp(),
  12998. vendorPrefix: vendorPrefix,
  12999. transitions : transitions,
  13000. animations : animations,
  13001. android: android,
  13002. msie : msie,
  13003. msieDocumentMode: documentMode
  13004. };
  13005. }];
  13006. }
  13007. function $TimeoutProvider() {
  13008. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  13009. function($rootScope, $browser, $q, $exceptionHandler) {
  13010. var deferreds = {};
  13011. /**
  13012. * @ngdoc service
  13013. * @name $timeout
  13014. *
  13015. * @description
  13016. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  13017. * block and delegates any exceptions to
  13018. * {@link ng.$exceptionHandler $exceptionHandler} service.
  13019. *
  13020. * The return value of registering a timeout function is a promise, which will be resolved when
  13021. * the timeout is reached and the timeout function is executed.
  13022. *
  13023. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  13024. *
  13025. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  13026. * synchronously flush the queue of deferred functions.
  13027. *
  13028. * @param {function()} fn A function, whose execution should be delayed.
  13029. * @param {number=} [delay=0] Delay in milliseconds.
  13030. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  13031. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  13032. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  13033. * promise will be resolved with is the return value of the `fn` function.
  13034. *
  13035. */
  13036. function timeout(fn, delay, invokeApply) {
  13037. var deferred = $q.defer(),
  13038. promise = deferred.promise,
  13039. skipApply = (isDefined(invokeApply) && !invokeApply),
  13040. timeoutId;
  13041. timeoutId = $browser.defer(function() {
  13042. try {
  13043. deferred.resolve(fn());
  13044. } catch(e) {
  13045. deferred.reject(e);
  13046. $exceptionHandler(e);
  13047. }
  13048. finally {
  13049. delete deferreds[promise.$$timeoutId];
  13050. }
  13051. if (!skipApply) $rootScope.$apply();
  13052. }, delay);
  13053. promise.$$timeoutId = timeoutId;
  13054. deferreds[timeoutId] = deferred;
  13055. return promise;
  13056. }
  13057. /**
  13058. * @ngdoc method
  13059. * @name $timeout#cancel
  13060. *
  13061. * @description
  13062. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  13063. * resolved with a rejection.
  13064. *
  13065. * @param {Promise=} promise Promise returned by the `$timeout` function.
  13066. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  13067. * canceled.
  13068. */
  13069. timeout.cancel = function(promise) {
  13070. if (promise && promise.$$timeoutId in deferreds) {
  13071. deferreds[promise.$$timeoutId].reject('canceled');
  13072. delete deferreds[promise.$$timeoutId];
  13073. return $browser.defer.cancel(promise.$$timeoutId);
  13074. }
  13075. return false;
  13076. };
  13077. return timeout;
  13078. }];
  13079. }
  13080. // NOTE: The usage of window and document instead of $window and $document here is
  13081. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  13082. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  13083. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  13084. // doesn't know about mocked locations and resolves URLs to the real document - which is
  13085. // exactly the behavior needed here. There is little value is mocking these out for this
  13086. // service.
  13087. var urlParsingNode = document.createElement("a");
  13088. var originUrl = urlResolve(window.location.href, true);
  13089. /**
  13090. *
  13091. * Implementation Notes for non-IE browsers
  13092. * ----------------------------------------
  13093. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  13094. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  13095. * URL will be resolved into an absolute URL in the context of the application document.
  13096. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  13097. * properties are all populated to reflect the normalized URL. This approach has wide
  13098. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  13099. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13100. *
  13101. * Implementation Notes for IE
  13102. * ---------------------------
  13103. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  13104. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  13105. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  13106. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  13107. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  13108. * properties such as protocol, hostname, port, etc.
  13109. *
  13110. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  13111. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  13112. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  13113. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  13114. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  13115. * method and IE < 8 is unsupported.
  13116. *
  13117. * References:
  13118. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  13119. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13120. * http://url.spec.whatwg.org/#urlutils
  13121. * https://github.com/angular/angular.js/pull/2902
  13122. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  13123. *
  13124. * @kind function
  13125. * @param {string} url The URL to be parsed.
  13126. * @description Normalizes and parses a URL.
  13127. * @returns {object} Returns the normalized URL as a dictionary.
  13128. *
  13129. * | member name | Description |
  13130. * |---------------|----------------|
  13131. * | href | A normalized version of the provided URL if it was not an absolute URL |
  13132. * | protocol | The protocol including the trailing colon |
  13133. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  13134. * | search | The search params, minus the question mark |
  13135. * | hash | The hash string, minus the hash symbol
  13136. * | hostname | The hostname
  13137. * | port | The port, without ":"
  13138. * | pathname | The pathname, beginning with "/"
  13139. *
  13140. */
  13141. function urlResolve(url, base) {
  13142. var href = url;
  13143. if (msie) {
  13144. // Normalize before parse. Refer Implementation Notes on why this is
  13145. // done in two steps on IE.
  13146. urlParsingNode.setAttribute("href", href);
  13147. href = urlParsingNode.href;
  13148. }
  13149. urlParsingNode.setAttribute('href', href);
  13150. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  13151. return {
  13152. href: urlParsingNode.href,
  13153. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  13154. host: urlParsingNode.host,
  13155. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  13156. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  13157. hostname: urlParsingNode.hostname,
  13158. port: urlParsingNode.port,
  13159. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  13160. ? urlParsingNode.pathname
  13161. : '/' + urlParsingNode.pathname
  13162. };
  13163. }
  13164. /**
  13165. * Parse a request URL and determine whether this is a same-origin request as the application document.
  13166. *
  13167. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  13168. * or a parsed URL object.
  13169. * @returns {boolean} Whether the request is for the same origin as the application document.
  13170. */
  13171. function urlIsSameOrigin(requestUrl) {
  13172. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  13173. return (parsed.protocol === originUrl.protocol &&
  13174. parsed.host === originUrl.host);
  13175. }
  13176. /**
  13177. * @ngdoc service
  13178. * @name $window
  13179. *
  13180. * @description
  13181. * A reference to the browser's `window` object. While `window`
  13182. * is globally available in JavaScript, it causes testability problems, because
  13183. * it is a global variable. In angular we always refer to it through the
  13184. * `$window` service, so it may be overridden, removed or mocked for testing.
  13185. *
  13186. * Expressions, like the one defined for the `ngClick` directive in the example
  13187. * below, are evaluated with respect to the current scope. Therefore, there is
  13188. * no risk of inadvertently coding in a dependency on a global value in such an
  13189. * expression.
  13190. *
  13191. * @example
  13192. <example module="windowExample">
  13193. <file name="index.html">
  13194. <script>
  13195. angular.module('windowExample', [])
  13196. .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
  13197. $scope.greeting = 'Hello, World!';
  13198. $scope.doGreeting = function(greeting) {
  13199. $window.alert(greeting);
  13200. };
  13201. }]);
  13202. </script>
  13203. <div ng-controller="ExampleController">
  13204. <input type="text" ng-model="greeting" />
  13205. <button ng-click="doGreeting(greeting)">ALERT</button>
  13206. </div>
  13207. </file>
  13208. <file name="protractor.js" type="protractor">
  13209. it('should display the greeting in the input box', function() {
  13210. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  13211. // If we click the button it will block the test runner
  13212. // element(':button').click();
  13213. });
  13214. </file>
  13215. </example>
  13216. */
  13217. function $WindowProvider(){
  13218. this.$get = valueFn(window);
  13219. }
  13220. /* global currencyFilter: true,
  13221. dateFilter: true,
  13222. filterFilter: true,
  13223. jsonFilter: true,
  13224. limitToFilter: true,
  13225. lowercaseFilter: true,
  13226. numberFilter: true,
  13227. orderByFilter: true,
  13228. uppercaseFilter: true,
  13229. */
  13230. /**
  13231. * @ngdoc provider
  13232. * @name $filterProvider
  13233. * @description
  13234. *
  13235. * Filters are just functions which transform input to an output. However filters need to be
  13236. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  13237. * annotated with dependencies and is responsible for creating a filter function.
  13238. *
  13239. * ```js
  13240. * // Filter registration
  13241. * function MyModule($provide, $filterProvider) {
  13242. * // create a service to demonstrate injection (not always needed)
  13243. * $provide.value('greet', function(name){
  13244. * return 'Hello ' + name + '!';
  13245. * });
  13246. *
  13247. * // register a filter factory which uses the
  13248. * // greet service to demonstrate DI.
  13249. * $filterProvider.register('greet', function(greet){
  13250. * // return the filter function which uses the greet service
  13251. * // to generate salutation
  13252. * return function(text) {
  13253. * // filters need to be forgiving so check input validity
  13254. * return text && greet(text) || text;
  13255. * };
  13256. * });
  13257. * }
  13258. * ```
  13259. *
  13260. * The filter function is registered with the `$injector` under the filter name suffix with
  13261. * `Filter`.
  13262. *
  13263. * ```js
  13264. * it('should be the same instance', inject(
  13265. * function($filterProvider) {
  13266. * $filterProvider.register('reverse', function(){
  13267. * return ...;
  13268. * });
  13269. * },
  13270. * function($filter, reverseFilter) {
  13271. * expect($filter('reverse')).toBe(reverseFilter);
  13272. * });
  13273. * ```
  13274. *
  13275. *
  13276. * For more information about how angular filters work, and how to create your own filters, see
  13277. * {@link guide/filter Filters} in the Angular Developer Guide.
  13278. */
  13279. /**
  13280. * @ngdoc service
  13281. * @name $filter
  13282. * @kind function
  13283. * @description
  13284. * Filters are used for formatting data displayed to the user.
  13285. *
  13286. * The general syntax in templates is as follows:
  13287. *
  13288. * {{ expression [| filter_name[:parameter_value] ... ] }}
  13289. *
  13290. * @param {String} name Name of the filter function to retrieve
  13291. * @return {Function} the filter function
  13292. * @example
  13293. <example name="$filter" module="filterExample">
  13294. <file name="index.html">
  13295. <div ng-controller="MainCtrl">
  13296. <h3>{{ originalText }}</h3>
  13297. <h3>{{ filteredText }}</h3>
  13298. </div>
  13299. </file>
  13300. <file name="script.js">
  13301. angular.module('filterExample', [])
  13302. .controller('MainCtrl', function($scope, $filter) {
  13303. $scope.originalText = 'hello';
  13304. $scope.filteredText = $filter('uppercase')($scope.originalText);
  13305. });
  13306. </file>
  13307. </example>
  13308. */
  13309. $FilterProvider.$inject = ['$provide'];
  13310. function $FilterProvider($provide) {
  13311. var suffix = 'Filter';
  13312. /**
  13313. * @ngdoc method
  13314. * @name $filterProvider#register
  13315. * @param {string|Object} name Name of the filter function, or an object map of filters where
  13316. * the keys are the filter names and the values are the filter factories.
  13317. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  13318. * of the registered filter instances.
  13319. */
  13320. function register(name, factory) {
  13321. if(isObject(name)) {
  13322. var filters = {};
  13323. forEach(name, function(filter, key) {
  13324. filters[key] = register(key, filter);
  13325. });
  13326. return filters;
  13327. } else {
  13328. return $provide.factory(name + suffix, factory);
  13329. }
  13330. }
  13331. this.register = register;
  13332. this.$get = ['$injector', function($injector) {
  13333. return function(name) {
  13334. return $injector.get(name + suffix);
  13335. };
  13336. }];
  13337. ////////////////////////////////////////
  13338. /* global
  13339. currencyFilter: false,
  13340. dateFilter: false,
  13341. filterFilter: false,
  13342. jsonFilter: false,
  13343. limitToFilter: false,
  13344. lowercaseFilter: false,
  13345. numberFilter: false,
  13346. orderByFilter: false,
  13347. uppercaseFilter: false,
  13348. */
  13349. register('currency', currencyFilter);
  13350. register('date', dateFilter);
  13351. register('filter', filterFilter);
  13352. register('json', jsonFilter);
  13353. register('limitTo', limitToFilter);
  13354. register('lowercase', lowercaseFilter);
  13355. register('number', numberFilter);
  13356. register('orderBy', orderByFilter);
  13357. register('uppercase', uppercaseFilter);
  13358. }
  13359. /**
  13360. * @ngdoc filter
  13361. * @name filter
  13362. * @kind function
  13363. *
  13364. * @description
  13365. * Selects a subset of items from `array` and returns it as a new array.
  13366. *
  13367. * @param {Array} array The source array.
  13368. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  13369. * `array`.
  13370. *
  13371. * Can be one of:
  13372. *
  13373. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  13374. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  13375. * will be returned. The predicate can be negated by prefixing the string with `!`.
  13376. *
  13377. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  13378. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  13379. * which have property `name` containing "M" and property `phone` containing "1". A special
  13380. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  13381. * property of the object. That's equivalent to the simple substring match with a `string`
  13382. * as described above. The predicate can be negated by prefixing the string with `!`.
  13383. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  13384. * not containing "M".
  13385. *
  13386. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  13387. * called for each element of `array`. The final result is an array of those elements that
  13388. * the predicate returned true for.
  13389. *
  13390. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  13391. * determining if the expected value (from the filter expression) and actual value (from
  13392. * the object in the array) should be considered a match.
  13393. *
  13394. * Can be one of:
  13395. *
  13396. * - `function(actual, expected)`:
  13397. * The function will be given the object value and the predicate value to compare and
  13398. * should return true if the item should be included in filtered result.
  13399. *
  13400. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13401. * this is essentially strict comparison of expected and actual.
  13402. *
  13403. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13404. * insensitive way.
  13405. *
  13406. * @example
  13407. <example>
  13408. <file name="index.html">
  13409. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13410. {name:'Mary', phone:'800-BIG-MARY'},
  13411. {name:'Mike', phone:'555-4321'},
  13412. {name:'Adam', phone:'555-5678'},
  13413. {name:'Julie', phone:'555-8765'},
  13414. {name:'Juliette', phone:'555-5678'}]"></div>
  13415. Search: <input ng-model="searchText">
  13416. <table id="searchTextResults">
  13417. <tr><th>Name</th><th>Phone</th></tr>
  13418. <tr ng-repeat="friend in friends | filter:searchText">
  13419. <td>{{friend.name}}</td>
  13420. <td>{{friend.phone}}</td>
  13421. </tr>
  13422. </table>
  13423. <hr>
  13424. Any: <input ng-model="search.$"> <br>
  13425. Name only <input ng-model="search.name"><br>
  13426. Phone only <input ng-model="search.phone"><br>
  13427. Equality <input type="checkbox" ng-model="strict"><br>
  13428. <table id="searchObjResults">
  13429. <tr><th>Name</th><th>Phone</th></tr>
  13430. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13431. <td>{{friendObj.name}}</td>
  13432. <td>{{friendObj.phone}}</td>
  13433. </tr>
  13434. </table>
  13435. </file>
  13436. <file name="protractor.js" type="protractor">
  13437. var expectFriendNames = function(expectedNames, key) {
  13438. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13439. arr.forEach(function(wd, i) {
  13440. expect(wd.getText()).toMatch(expectedNames[i]);
  13441. });
  13442. });
  13443. };
  13444. it('should search across all fields when filtering with a string', function() {
  13445. var searchText = element(by.model('searchText'));
  13446. searchText.clear();
  13447. searchText.sendKeys('m');
  13448. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13449. searchText.clear();
  13450. searchText.sendKeys('76');
  13451. expectFriendNames(['John', 'Julie'], 'friend');
  13452. });
  13453. it('should search in specific fields when filtering with a predicate object', function() {
  13454. var searchAny = element(by.model('search.$'));
  13455. searchAny.clear();
  13456. searchAny.sendKeys('i');
  13457. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13458. });
  13459. it('should use a equal comparison when comparator is true', function() {
  13460. var searchName = element(by.model('search.name'));
  13461. var strict = element(by.model('strict'));
  13462. searchName.clear();
  13463. searchName.sendKeys('Julie');
  13464. strict.click();
  13465. expectFriendNames(['Julie'], 'friendObj');
  13466. });
  13467. </file>
  13468. </example>
  13469. */
  13470. function filterFilter() {
  13471. return function(array, expression, comparator) {
  13472. if (!isArray(array)) return array;
  13473. var comparatorType = typeof(comparator),
  13474. predicates = [];
  13475. predicates.check = function(value) {
  13476. for (var j = 0; j < predicates.length; j++) {
  13477. if(!predicates[j](value)) {
  13478. return false;
  13479. }
  13480. }
  13481. return true;
  13482. };
  13483. if (comparatorType !== 'function') {
  13484. if (comparatorType === 'boolean' && comparator) {
  13485. comparator = function(obj, text) {
  13486. return angular.equals(obj, text);
  13487. };
  13488. } else {
  13489. comparator = function(obj, text) {
  13490. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13491. for (var objKey in obj) {
  13492. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13493. comparator(obj[objKey], text[objKey])) {
  13494. return true;
  13495. }
  13496. }
  13497. return false;
  13498. }
  13499. text = (''+text).toLowerCase();
  13500. return (''+obj).toLowerCase().indexOf(text) > -1;
  13501. };
  13502. }
  13503. }
  13504. var search = function(obj, text){
  13505. if (typeof text === 'string' && text.charAt(0) === '!') {
  13506. return !search(obj, text.substr(1));
  13507. }
  13508. switch (typeof obj) {
  13509. case 'boolean':
  13510. case 'number':
  13511. case 'string':
  13512. return comparator(obj, text);
  13513. case 'object':
  13514. switch (typeof text) {
  13515. case 'object':
  13516. return comparator(obj, text);
  13517. default:
  13518. for ( var objKey in obj) {
  13519. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13520. return true;
  13521. }
  13522. }
  13523. break;
  13524. }
  13525. return false;
  13526. case 'array':
  13527. for ( var i = 0; i < obj.length; i++) {
  13528. if (search(obj[i], text)) {
  13529. return true;
  13530. }
  13531. }
  13532. return false;
  13533. default:
  13534. return false;
  13535. }
  13536. };
  13537. switch (typeof expression) {
  13538. case 'boolean':
  13539. case 'number':
  13540. case 'string':
  13541. // Set up expression object and fall through
  13542. expression = {$:expression};
  13543. // jshint -W086
  13544. case 'object':
  13545. // jshint +W086
  13546. for (var key in expression) {
  13547. (function(path) {
  13548. if (typeof expression[path] === 'undefined') return;
  13549. predicates.push(function(value) {
  13550. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13551. });
  13552. })(key);
  13553. }
  13554. break;
  13555. case 'function':
  13556. predicates.push(expression);
  13557. break;
  13558. default:
  13559. return array;
  13560. }
  13561. var filtered = [];
  13562. for ( var j = 0; j < array.length; j++) {
  13563. var value = array[j];
  13564. if (predicates.check(value)) {
  13565. filtered.push(value);
  13566. }
  13567. }
  13568. return filtered;
  13569. };
  13570. }
  13571. /**
  13572. * @ngdoc filter
  13573. * @name currency
  13574. * @kind function
  13575. *
  13576. * @description
  13577. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13578. * symbol for current locale is used.
  13579. *
  13580. * @param {number} amount Input to filter.
  13581. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13582. * @returns {string} Formatted number.
  13583. *
  13584. *
  13585. * @example
  13586. <example module="currencyExample">
  13587. <file name="index.html">
  13588. <script>
  13589. angular.module('currencyExample', [])
  13590. .controller('ExampleController', ['$scope', function($scope) {
  13591. $scope.amount = 1234.56;
  13592. }]);
  13593. </script>
  13594. <div ng-controller="ExampleController">
  13595. <input type="number" ng-model="amount"> <br>
  13596. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13597. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13598. </div>
  13599. </file>
  13600. <file name="protractor.js" type="protractor">
  13601. it('should init with 1234.56', function() {
  13602. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13603. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13604. });
  13605. it('should update', function() {
  13606. if (browser.params.browser == 'safari') {
  13607. // Safari does not understand the minus key. See
  13608. // https://github.com/angular/protractor/issues/481
  13609. return;
  13610. }
  13611. element(by.model('amount')).clear();
  13612. element(by.model('amount')).sendKeys('-1234');
  13613. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13614. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13615. });
  13616. </file>
  13617. </example>
  13618. */
  13619. currencyFilter.$inject = ['$locale'];
  13620. function currencyFilter($locale) {
  13621. var formats = $locale.NUMBER_FORMATS;
  13622. return function(amount, currencySymbol){
  13623. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13624. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13625. replace(/\u00A4/g, currencySymbol);
  13626. };
  13627. }
  13628. /**
  13629. * @ngdoc filter
  13630. * @name number
  13631. * @kind function
  13632. *
  13633. * @description
  13634. * Formats a number as text.
  13635. *
  13636. * If the input is not a number an empty string is returned.
  13637. *
  13638. * @param {number|string} number Number to format.
  13639. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13640. * If this is not provided then the fraction size is computed from the current locale's number
  13641. * formatting pattern. In the case of the default locale, it will be 3.
  13642. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13643. *
  13644. * @example
  13645. <example module="numberFilterExample">
  13646. <file name="index.html">
  13647. <script>
  13648. angular.module('numberFilterExample', [])
  13649. .controller('ExampleController', ['$scope', function($scope) {
  13650. $scope.val = 1234.56789;
  13651. }]);
  13652. </script>
  13653. <div ng-controller="ExampleController">
  13654. Enter number: <input ng-model='val'><br>
  13655. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13656. No fractions: <span>{{val | number:0}}</span><br>
  13657. Negative number: <span>{{-val | number:4}}</span>
  13658. </div>
  13659. </file>
  13660. <file name="protractor.js" type="protractor">
  13661. it('should format numbers', function() {
  13662. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13663. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13664. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13665. });
  13666. it('should update', function() {
  13667. element(by.model('val')).clear();
  13668. element(by.model('val')).sendKeys('3374.333');
  13669. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13670. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13671. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13672. });
  13673. </file>
  13674. </example>
  13675. */
  13676. numberFilter.$inject = ['$locale'];
  13677. function numberFilter($locale) {
  13678. var formats = $locale.NUMBER_FORMATS;
  13679. return function(number, fractionSize) {
  13680. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13681. fractionSize);
  13682. };
  13683. }
  13684. var DECIMAL_SEP = '.';
  13685. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13686. if (number == null || !isFinite(number) || isObject(number)) return '';
  13687. var isNegative = number < 0;
  13688. number = Math.abs(number);
  13689. var numStr = number + '',
  13690. formatedText = '',
  13691. parts = [];
  13692. var hasExponent = false;
  13693. if (numStr.indexOf('e') !== -1) {
  13694. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13695. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13696. numStr = '0';
  13697. number = 0;
  13698. } else {
  13699. formatedText = numStr;
  13700. hasExponent = true;
  13701. }
  13702. }
  13703. if (!hasExponent) {
  13704. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13705. // determine fractionSize if it is not specified
  13706. if (isUndefined(fractionSize)) {
  13707. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13708. }
  13709. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  13710. // inspired by:
  13711. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  13712. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  13713. if (number === 0) {
  13714. isNegative = false;
  13715. }
  13716. var fraction = ('' + number).split(DECIMAL_SEP);
  13717. var whole = fraction[0];
  13718. fraction = fraction[1] || '';
  13719. var i, pos = 0,
  13720. lgroup = pattern.lgSize,
  13721. group = pattern.gSize;
  13722. if (whole.length >= (lgroup + group)) {
  13723. pos = whole.length - lgroup;
  13724. for (i = 0; i < pos; i++) {
  13725. if ((pos - i)%group === 0 && i !== 0) {
  13726. formatedText += groupSep;
  13727. }
  13728. formatedText += whole.charAt(i);
  13729. }
  13730. }
  13731. for (i = pos; i < whole.length; i++) {
  13732. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13733. formatedText += groupSep;
  13734. }
  13735. formatedText += whole.charAt(i);
  13736. }
  13737. // format fraction part.
  13738. while(fraction.length < fractionSize) {
  13739. fraction += '0';
  13740. }
  13741. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13742. } else {
  13743. if (fractionSize > 0 && number > -1 && number < 1) {
  13744. formatedText = number.toFixed(fractionSize);
  13745. }
  13746. }
  13747. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13748. parts.push(formatedText);
  13749. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13750. return parts.join('');
  13751. }
  13752. function padNumber(num, digits, trim) {
  13753. var neg = '';
  13754. if (num < 0) {
  13755. neg = '-';
  13756. num = -num;
  13757. }
  13758. num = '' + num;
  13759. while(num.length < digits) num = '0' + num;
  13760. if (trim)
  13761. num = num.substr(num.length - digits);
  13762. return neg + num;
  13763. }
  13764. function dateGetter(name, size, offset, trim) {
  13765. offset = offset || 0;
  13766. return function(date) {
  13767. var value = date['get' + name]();
  13768. if (offset > 0 || value > -offset)
  13769. value += offset;
  13770. if (value === 0 && offset == -12 ) value = 12;
  13771. return padNumber(value, size, trim);
  13772. };
  13773. }
  13774. function dateStrGetter(name, shortForm) {
  13775. return function(date, formats) {
  13776. var value = date['get' + name]();
  13777. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13778. return formats[get][value];
  13779. };
  13780. }
  13781. function timeZoneGetter(date) {
  13782. var zone = -1 * date.getTimezoneOffset();
  13783. var paddedZone = (zone >= 0) ? "+" : "";
  13784. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13785. padNumber(Math.abs(zone % 60), 2);
  13786. return paddedZone;
  13787. }
  13788. function ampmGetter(date, formats) {
  13789. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13790. }
  13791. var DATE_FORMATS = {
  13792. yyyy: dateGetter('FullYear', 4),
  13793. yy: dateGetter('FullYear', 2, 0, true),
  13794. y: dateGetter('FullYear', 1),
  13795. MMMM: dateStrGetter('Month'),
  13796. MMM: dateStrGetter('Month', true),
  13797. MM: dateGetter('Month', 2, 1),
  13798. M: dateGetter('Month', 1, 1),
  13799. dd: dateGetter('Date', 2),
  13800. d: dateGetter('Date', 1),
  13801. HH: dateGetter('Hours', 2),
  13802. H: dateGetter('Hours', 1),
  13803. hh: dateGetter('Hours', 2, -12),
  13804. h: dateGetter('Hours', 1, -12),
  13805. mm: dateGetter('Minutes', 2),
  13806. m: dateGetter('Minutes', 1),
  13807. ss: dateGetter('Seconds', 2),
  13808. s: dateGetter('Seconds', 1),
  13809. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13810. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13811. sss: dateGetter('Milliseconds', 3),
  13812. EEEE: dateStrGetter('Day'),
  13813. EEE: dateStrGetter('Day', true),
  13814. a: ampmGetter,
  13815. Z: timeZoneGetter
  13816. };
  13817. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13818. NUMBER_STRING = /^\-?\d+$/;
  13819. /**
  13820. * @ngdoc filter
  13821. * @name date
  13822. * @kind function
  13823. *
  13824. * @description
  13825. * Formats `date` to a string based on the requested `format`.
  13826. *
  13827. * `format` string can be composed of the following elements:
  13828. *
  13829. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13830. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13831. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13832. * * `'MMMM'`: Month in year (January-December)
  13833. * * `'MMM'`: Month in year (Jan-Dec)
  13834. * * `'MM'`: Month in year, padded (01-12)
  13835. * * `'M'`: Month in year (1-12)
  13836. * * `'dd'`: Day in month, padded (01-31)
  13837. * * `'d'`: Day in month (1-31)
  13838. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13839. * * `'EEE'`: Day in Week, (Sun-Sat)
  13840. * * `'HH'`: Hour in day, padded (00-23)
  13841. * * `'H'`: Hour in day (0-23)
  13842. * * `'hh'`: Hour in am/pm, padded (01-12)
  13843. * * `'h'`: Hour in am/pm, (1-12)
  13844. * * `'mm'`: Minute in hour, padded (00-59)
  13845. * * `'m'`: Minute in hour (0-59)
  13846. * * `'ss'`: Second in minute, padded (00-59)
  13847. * * `'s'`: Second in minute (0-59)
  13848. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13849. * * `'a'`: am/pm marker
  13850. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13851. *
  13852. * `format` string can also be one of the following predefined
  13853. * {@link guide/i18n localizable formats}:
  13854. *
  13855. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13856. * (e.g. Sep 3, 2010 12:05:08 pm)
  13857. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13858. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13859. * (e.g. Friday, September 3, 2010)
  13860. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13861. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13862. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13863. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13864. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13865. *
  13866. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  13867. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  13868. * (e.g. `"h 'o''clock'"`).
  13869. *
  13870. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13871. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  13872. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13873. * specified in the string input, the time is considered to be in the local timezone.
  13874. * @param {string=} format Formatting rules (see Description). If not specified,
  13875. * `mediumDate` is used.
  13876. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13877. *
  13878. * @example
  13879. <example>
  13880. <file name="index.html">
  13881. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13882. <span>{{1288323623006 | date:'medium'}}</span><br>
  13883. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13884. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13885. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13886. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13887. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  13888. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  13889. </file>
  13890. <file name="protractor.js" type="protractor">
  13891. it('should format date', function() {
  13892. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13893. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13894. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13895. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13896. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13897. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13898. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  13899. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  13900. });
  13901. </file>
  13902. </example>
  13903. */
  13904. dateFilter.$inject = ['$locale'];
  13905. function dateFilter($locale) {
  13906. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13907. // 1 2 3 4 5 6 7 8 9 10 11
  13908. function jsonStringToDate(string) {
  13909. var match;
  13910. if (match = string.match(R_ISO8601_STR)) {
  13911. var date = new Date(0),
  13912. tzHour = 0,
  13913. tzMin = 0,
  13914. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13915. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13916. if (match[9]) {
  13917. tzHour = int(match[9] + match[10]);
  13918. tzMin = int(match[9] + match[11]);
  13919. }
  13920. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13921. var h = int(match[4]||0) - tzHour;
  13922. var m = int(match[5]||0) - tzMin;
  13923. var s = int(match[6]||0);
  13924. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13925. timeSetter.call(date, h, m, s, ms);
  13926. return date;
  13927. }
  13928. return string;
  13929. }
  13930. return function(date, format) {
  13931. var text = '',
  13932. parts = [],
  13933. fn, match;
  13934. format = format || 'mediumDate';
  13935. format = $locale.DATETIME_FORMATS[format] || format;
  13936. if (isString(date)) {
  13937. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  13938. }
  13939. if (isNumber(date)) {
  13940. date = new Date(date);
  13941. }
  13942. if (!isDate(date)) {
  13943. return date;
  13944. }
  13945. while(format) {
  13946. match = DATE_FORMATS_SPLIT.exec(format);
  13947. if (match) {
  13948. parts = concat(parts, match, 1);
  13949. format = parts.pop();
  13950. } else {
  13951. parts.push(format);
  13952. format = null;
  13953. }
  13954. }
  13955. forEach(parts, function(value){
  13956. fn = DATE_FORMATS[value];
  13957. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13958. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13959. });
  13960. return text;
  13961. };
  13962. }
  13963. /**
  13964. * @ngdoc filter
  13965. * @name json
  13966. * @kind function
  13967. *
  13968. * @description
  13969. * Allows you to convert a JavaScript object into JSON string.
  13970. *
  13971. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13972. * the binding is automatically converted to JSON.
  13973. *
  13974. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13975. * @returns {string} JSON string.
  13976. *
  13977. *
  13978. * @example
  13979. <example>
  13980. <file name="index.html">
  13981. <pre>{{ {'name':'value'} | json }}</pre>
  13982. </file>
  13983. <file name="protractor.js" type="protractor">
  13984. it('should jsonify filtered objects', function() {
  13985. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  13986. });
  13987. </file>
  13988. </example>
  13989. *
  13990. */
  13991. function jsonFilter() {
  13992. return function(object) {
  13993. return toJson(object, true);
  13994. };
  13995. }
  13996. /**
  13997. * @ngdoc filter
  13998. * @name lowercase
  13999. * @kind function
  14000. * @description
  14001. * Converts string to lowercase.
  14002. * @see angular.lowercase
  14003. */
  14004. var lowercaseFilter = valueFn(lowercase);
  14005. /**
  14006. * @ngdoc filter
  14007. * @name uppercase
  14008. * @kind function
  14009. * @description
  14010. * Converts string to uppercase.
  14011. * @see angular.uppercase
  14012. */
  14013. var uppercaseFilter = valueFn(uppercase);
  14014. /**
  14015. * @ngdoc filter
  14016. * @name limitTo
  14017. * @kind function
  14018. *
  14019. * @description
  14020. * Creates a new array or string containing only a specified number of elements. The elements
  14021. * are taken from either the beginning or the end of the source array or string, as specified by
  14022. * the value and sign (positive or negative) of `limit`.
  14023. *
  14024. * @param {Array|string} input Source array or string to be limited.
  14025. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  14026. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  14027. * If the number is negative, `limit` number of items from the end of the source array/string
  14028. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  14029. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  14030. * had less than `limit` elements.
  14031. *
  14032. * @example
  14033. <example module="limitToExample">
  14034. <file name="index.html">
  14035. <script>
  14036. angular.module('limitToExample', [])
  14037. .controller('ExampleController', ['$scope', function($scope) {
  14038. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  14039. $scope.letters = "abcdefghi";
  14040. $scope.numLimit = 3;
  14041. $scope.letterLimit = 3;
  14042. }]);
  14043. </script>
  14044. <div ng-controller="ExampleController">
  14045. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  14046. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  14047. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  14048. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  14049. </div>
  14050. </file>
  14051. <file name="protractor.js" type="protractor">
  14052. var numLimitInput = element(by.model('numLimit'));
  14053. var letterLimitInput = element(by.model('letterLimit'));
  14054. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  14055. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  14056. it('should limit the number array to first three items', function() {
  14057. expect(numLimitInput.getAttribute('value')).toBe('3');
  14058. expect(letterLimitInput.getAttribute('value')).toBe('3');
  14059. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  14060. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  14061. });
  14062. // There is a bug in safari and protractor that doesn't like the minus key
  14063. // it('should update the output when -3 is entered', function() {
  14064. // numLimitInput.clear();
  14065. // numLimitInput.sendKeys('-3');
  14066. // letterLimitInput.clear();
  14067. // letterLimitInput.sendKeys('-3');
  14068. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  14069. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  14070. // });
  14071. it('should not exceed the maximum size of input array', function() {
  14072. numLimitInput.clear();
  14073. numLimitInput.sendKeys('100');
  14074. letterLimitInput.clear();
  14075. letterLimitInput.sendKeys('100');
  14076. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  14077. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  14078. });
  14079. </file>
  14080. </example>
  14081. */
  14082. function limitToFilter(){
  14083. return function(input, limit) {
  14084. if (!isArray(input) && !isString(input)) return input;
  14085. if (Math.abs(Number(limit)) === Infinity) {
  14086. limit = Number(limit);
  14087. } else {
  14088. limit = int(limit);
  14089. }
  14090. if (isString(input)) {
  14091. //NaN check on limit
  14092. if (limit) {
  14093. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  14094. } else {
  14095. return "";
  14096. }
  14097. }
  14098. var out = [],
  14099. i, n;
  14100. // if abs(limit) exceeds maximum length, trim it
  14101. if (limit > input.length)
  14102. limit = input.length;
  14103. else if (limit < -input.length)
  14104. limit = -input.length;
  14105. if (limit > 0) {
  14106. i = 0;
  14107. n = limit;
  14108. } else {
  14109. i = input.length + limit;
  14110. n = input.length;
  14111. }
  14112. for (; i<n; i++) {
  14113. out.push(input[i]);
  14114. }
  14115. return out;
  14116. };
  14117. }
  14118. /**
  14119. * @ngdoc filter
  14120. * @name orderBy
  14121. * @kind function
  14122. *
  14123. * @description
  14124. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  14125. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  14126. * correctly, make sure they are actually being saved as numbers and not strings.
  14127. *
  14128. * @param {Array} array The array to sort.
  14129. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  14130. * used by the comparator to determine the order of elements.
  14131. *
  14132. * Can be one of:
  14133. *
  14134. * - `function`: Getter function. The result of this function will be sorted using the
  14135. * `<`, `=`, `>` operator.
  14136. * - `string`: An Angular expression. The result of this expression is used to compare elements
  14137. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  14138. * 3 first characters of a property called `name`). The result of a constant expression
  14139. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  14140. * to sort object by the value of their `special name` property). An expression can be
  14141. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  14142. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  14143. * element itself is used to compare where sorting.
  14144. * - `Array`: An array of function or string predicates. The first predicate in the array
  14145. * is used for sorting, but when two items are equivalent, the next predicate is used.
  14146. *
  14147. * If the predicate is missing or empty then it defaults to `'+'`.
  14148. *
  14149. * @param {boolean=} reverse Reverse the order of the array.
  14150. * @returns {Array} Sorted copy of the source array.
  14151. *
  14152. * @example
  14153. <example module="orderByExample">
  14154. <file name="index.html">
  14155. <script>
  14156. angular.module('orderByExample', [])
  14157. .controller('ExampleController', ['$scope', function($scope) {
  14158. $scope.friends =
  14159. [{name:'John', phone:'555-1212', age:10},
  14160. {name:'Mary', phone:'555-9876', age:19},
  14161. {name:'Mike', phone:'555-4321', age:21},
  14162. {name:'Adam', phone:'555-5678', age:35},
  14163. {name:'Julie', phone:'555-8765', age:29}];
  14164. $scope.predicate = '-age';
  14165. }]);
  14166. </script>
  14167. <div ng-controller="ExampleController">
  14168. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  14169. <hr/>
  14170. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  14171. <table class="friend">
  14172. <tr>
  14173. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  14174. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  14175. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  14176. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  14177. </tr>
  14178. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  14179. <td>{{friend.name}}</td>
  14180. <td>{{friend.phone}}</td>
  14181. <td>{{friend.age}}</td>
  14182. </tr>
  14183. </table>
  14184. </div>
  14185. </file>
  14186. </example>
  14187. *
  14188. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  14189. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  14190. * desired parameters.
  14191. *
  14192. * Example:
  14193. *
  14194. * @example
  14195. <example module="orderByExample">
  14196. <file name="index.html">
  14197. <div ng-controller="ExampleController">
  14198. <table class="friend">
  14199. <tr>
  14200. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  14201. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  14202. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  14203. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  14204. </tr>
  14205. <tr ng-repeat="friend in friends">
  14206. <td>{{friend.name}}</td>
  14207. <td>{{friend.phone}}</td>
  14208. <td>{{friend.age}}</td>
  14209. </tr>
  14210. </table>
  14211. </div>
  14212. </file>
  14213. <file name="script.js">
  14214. angular.module('orderByExample', [])
  14215. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  14216. var orderBy = $filter('orderBy');
  14217. $scope.friends = [
  14218. { name: 'John', phone: '555-1212', age: 10 },
  14219. { name: 'Mary', phone: '555-9876', age: 19 },
  14220. { name: 'Mike', phone: '555-4321', age: 21 },
  14221. { name: 'Adam', phone: '555-5678', age: 35 },
  14222. { name: 'Julie', phone: '555-8765', age: 29 }
  14223. ];
  14224. $scope.order = function(predicate, reverse) {
  14225. $scope.friends = orderBy($scope.friends, predicate, reverse);
  14226. };
  14227. $scope.order('-age',false);
  14228. }]);
  14229. </file>
  14230. </example>
  14231. */
  14232. orderByFilter.$inject = ['$parse'];
  14233. function orderByFilter($parse){
  14234. return function(array, sortPredicate, reverseOrder) {
  14235. if (!(isArrayLike(array))) return array;
  14236. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  14237. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  14238. sortPredicate = map(sortPredicate, function(predicate){
  14239. var descending = false, get = predicate || identity;
  14240. if (isString(predicate)) {
  14241. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  14242. descending = predicate.charAt(0) == '-';
  14243. predicate = predicate.substring(1);
  14244. }
  14245. if ( predicate === '' ) {
  14246. // Effectively no predicate was passed so we compare identity
  14247. return reverseComparator(function(a,b) {
  14248. return compare(a, b);
  14249. }, descending);
  14250. }
  14251. get = $parse(predicate);
  14252. if (get.constant) {
  14253. var key = get();
  14254. return reverseComparator(function(a,b) {
  14255. return compare(a[key], b[key]);
  14256. }, descending);
  14257. }
  14258. }
  14259. return reverseComparator(function(a,b){
  14260. return compare(get(a),get(b));
  14261. }, descending);
  14262. });
  14263. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  14264. function comparator(o1, o2){
  14265. for ( var i = 0; i < sortPredicate.length; i++) {
  14266. var comp = sortPredicate[i](o1, o2);
  14267. if (comp !== 0) return comp;
  14268. }
  14269. return 0;
  14270. }
  14271. function reverseComparator(comp, descending) {
  14272. return toBoolean(descending)
  14273. ? function(a,b){return comp(b,a);}
  14274. : comp;
  14275. }
  14276. function compare(v1, v2){
  14277. var t1 = typeof v1;
  14278. var t2 = typeof v2;
  14279. if (t1 == t2) {
  14280. if (isDate(v1) && isDate(v2)) {
  14281. v1 = v1.valueOf();
  14282. v2 = v2.valueOf();
  14283. }
  14284. if (t1 == "string") {
  14285. v1 = v1.toLowerCase();
  14286. v2 = v2.toLowerCase();
  14287. }
  14288. if (v1 === v2) return 0;
  14289. return v1 < v2 ? -1 : 1;
  14290. } else {
  14291. return t1 < t2 ? -1 : 1;
  14292. }
  14293. }
  14294. };
  14295. }
  14296. function ngDirective(directive) {
  14297. if (isFunction(directive)) {
  14298. directive = {
  14299. link: directive
  14300. };
  14301. }
  14302. directive.restrict = directive.restrict || 'AC';
  14303. return valueFn(directive);
  14304. }
  14305. /**
  14306. * @ngdoc directive
  14307. * @name a
  14308. * @restrict E
  14309. *
  14310. * @description
  14311. * Modifies the default behavior of the html A tag so that the default action is prevented when
  14312. * the href attribute is empty.
  14313. *
  14314. * This change permits the easy creation of action links with the `ngClick` directive
  14315. * without changing the location or causing page reloads, e.g.:
  14316. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  14317. */
  14318. var htmlAnchorDirective = valueFn({
  14319. restrict: 'E',
  14320. compile: function(element, attr) {
  14321. if (msie <= 8) {
  14322. // turn <a href ng-click="..">link</a> into a stylable link in IE
  14323. // but only if it doesn't have name attribute, in which case it's an anchor
  14324. if (!attr.href && !attr.name) {
  14325. attr.$set('href', '');
  14326. }
  14327. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  14328. // to new attribute content if attribute is updated with value containing @ and element also
  14329. // contains value with @
  14330. // see issue #1949
  14331. element.append(document.createComment('IE fix'));
  14332. }
  14333. if (!attr.href && !attr.xlinkHref && !attr.name) {
  14334. return function(scope, element) {
  14335. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  14336. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  14337. 'xlink:href' : 'href';
  14338. element.on('click', function(event){
  14339. // if we have no href url, then don't navigate anywhere.
  14340. if (!element.attr(href)) {
  14341. event.preventDefault();
  14342. }
  14343. });
  14344. };
  14345. }
  14346. }
  14347. });
  14348. /**
  14349. * @ngdoc directive
  14350. * @name ngHref
  14351. * @restrict A
  14352. * @priority 99
  14353. *
  14354. * @description
  14355. * Using Angular markup like `{{hash}}` in an href attribute will
  14356. * make the link go to the wrong URL if the user clicks it before
  14357. * Angular has a chance to replace the `{{hash}}` markup with its
  14358. * value. Until Angular replaces the markup the link will be broken
  14359. * and will most likely return a 404 error. The `ngHref` directive
  14360. * solves this problem.
  14361. *
  14362. * The wrong way to write it:
  14363. * ```html
  14364. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  14365. * ```
  14366. *
  14367. * The correct way to write it:
  14368. * ```html
  14369. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  14370. * ```
  14371. *
  14372. * @element A
  14373. * @param {template} ngHref any string which can contain `{{}}` markup.
  14374. *
  14375. * @example
  14376. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  14377. * in links and their different behaviors:
  14378. <example>
  14379. <file name="index.html">
  14380. <input ng-model="value" /><br />
  14381. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  14382. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  14383. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  14384. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  14385. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  14386. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  14387. </file>
  14388. <file name="protractor.js" type="protractor">
  14389. it('should execute ng-click but not reload when href without value', function() {
  14390. element(by.id('link-1')).click();
  14391. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  14392. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  14393. });
  14394. it('should execute ng-click but not reload when href empty string', function() {
  14395. element(by.id('link-2')).click();
  14396. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  14397. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  14398. });
  14399. it('should execute ng-click and change url when ng-href specified', function() {
  14400. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  14401. element(by.id('link-3')).click();
  14402. // At this point, we navigate away from an Angular page, so we need
  14403. // to use browser.driver to get the base webdriver.
  14404. browser.wait(function() {
  14405. return browser.driver.getCurrentUrl().then(function(url) {
  14406. return url.match(/\/123$/);
  14407. });
  14408. }, 5000, 'page should navigate to /123');
  14409. });
  14410. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  14411. element(by.id('link-4')).click();
  14412. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  14413. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  14414. });
  14415. it('should execute ng-click but not reload when no href but name specified', function() {
  14416. element(by.id('link-5')).click();
  14417. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  14418. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  14419. });
  14420. it('should only change url when only ng-href', function() {
  14421. element(by.model('value')).clear();
  14422. element(by.model('value')).sendKeys('6');
  14423. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  14424. element(by.id('link-6')).click();
  14425. // At this point, we navigate away from an Angular page, so we need
  14426. // to use browser.driver to get the base webdriver.
  14427. browser.wait(function() {
  14428. return browser.driver.getCurrentUrl().then(function(url) {
  14429. return url.match(/\/6$/);
  14430. });
  14431. }, 5000, 'page should navigate to /6');
  14432. });
  14433. </file>
  14434. </example>
  14435. */
  14436. /**
  14437. * @ngdoc directive
  14438. * @name ngSrc
  14439. * @restrict A
  14440. * @priority 99
  14441. *
  14442. * @description
  14443. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  14444. * work right: The browser will fetch from the URL with the literal
  14445. * text `{{hash}}` until Angular replaces the expression inside
  14446. * `{{hash}}`. The `ngSrc` directive solves this problem.
  14447. *
  14448. * The buggy way to write it:
  14449. * ```html
  14450. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  14451. * ```
  14452. *
  14453. * The correct way to write it:
  14454. * ```html
  14455. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  14456. * ```
  14457. *
  14458. * @element IMG
  14459. * @param {template} ngSrc any string which can contain `{{}}` markup.
  14460. */
  14461. /**
  14462. * @ngdoc directive
  14463. * @name ngSrcset
  14464. * @restrict A
  14465. * @priority 99
  14466. *
  14467. * @description
  14468. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14469. * work right: The browser will fetch from the URL with the literal
  14470. * text `{{hash}}` until Angular replaces the expression inside
  14471. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14472. *
  14473. * The buggy way to write it:
  14474. * ```html
  14475. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14476. * ```
  14477. *
  14478. * The correct way to write it:
  14479. * ```html
  14480. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14481. * ```
  14482. *
  14483. * @element IMG
  14484. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14485. */
  14486. /**
  14487. * @ngdoc directive
  14488. * @name ngDisabled
  14489. * @restrict A
  14490. * @priority 100
  14491. *
  14492. * @description
  14493. *
  14494. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14495. * ```html
  14496. * <div ng-init="scope = { isDisabled: false }">
  14497. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14498. * </div>
  14499. * ```
  14500. *
  14501. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14502. * such as disabled. (Their presence means true and their absence means false.)
  14503. * If we put an Angular interpolation expression into such an attribute then the
  14504. * binding information would be lost when the browser removes the attribute.
  14505. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14506. * This complementary directive is not removed by the browser and so provides
  14507. * a permanent reliable place to store the binding information.
  14508. *
  14509. * @example
  14510. <example>
  14511. <file name="index.html">
  14512. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14513. <button ng-model="button" ng-disabled="checked">Button</button>
  14514. </file>
  14515. <file name="protractor.js" type="protractor">
  14516. it('should toggle button', function() {
  14517. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14518. element(by.model('checked')).click();
  14519. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14520. });
  14521. </file>
  14522. </example>
  14523. *
  14524. * @element INPUT
  14525. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14526. * then special attribute "disabled" will be set on the element
  14527. */
  14528. /**
  14529. * @ngdoc directive
  14530. * @name ngChecked
  14531. * @restrict A
  14532. * @priority 100
  14533. *
  14534. * @description
  14535. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14536. * such as checked. (Their presence means true and their absence means false.)
  14537. * If we put an Angular interpolation expression into such an attribute then the
  14538. * binding information would be lost when the browser removes the attribute.
  14539. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14540. * This complementary directive is not removed by the browser and so provides
  14541. * a permanent reliable place to store the binding information.
  14542. * @example
  14543. <example>
  14544. <file name="index.html">
  14545. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14546. <input id="checkSlave" type="checkbox" ng-checked="master">
  14547. </file>
  14548. <file name="protractor.js" type="protractor">
  14549. it('should check both checkBoxes', function() {
  14550. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14551. element(by.model('master')).click();
  14552. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14553. });
  14554. </file>
  14555. </example>
  14556. *
  14557. * @element INPUT
  14558. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14559. * then special attribute "checked" will be set on the element
  14560. */
  14561. /**
  14562. * @ngdoc directive
  14563. * @name ngReadonly
  14564. * @restrict A
  14565. * @priority 100
  14566. *
  14567. * @description
  14568. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14569. * such as readonly. (Their presence means true and their absence means false.)
  14570. * If we put an Angular interpolation expression into such an attribute then the
  14571. * binding information would be lost when the browser removes the attribute.
  14572. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14573. * This complementary directive is not removed by the browser and so provides
  14574. * a permanent reliable place to store the binding information.
  14575. * @example
  14576. <example>
  14577. <file name="index.html">
  14578. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14579. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14580. </file>
  14581. <file name="protractor.js" type="protractor">
  14582. it('should toggle readonly attr', function() {
  14583. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14584. element(by.model('checked')).click();
  14585. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14586. });
  14587. </file>
  14588. </example>
  14589. *
  14590. * @element INPUT
  14591. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14592. * then special attribute "readonly" will be set on the element
  14593. */
  14594. /**
  14595. * @ngdoc directive
  14596. * @name ngSelected
  14597. * @restrict A
  14598. * @priority 100
  14599. *
  14600. * @description
  14601. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14602. * such as selected. (Their presence means true and their absence means false.)
  14603. * If we put an Angular interpolation expression into such an attribute then the
  14604. * binding information would be lost when the browser removes the attribute.
  14605. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14606. * This complementary directive is not removed by the browser and so provides
  14607. * a permanent reliable place to store the binding information.
  14608. *
  14609. * @example
  14610. <example>
  14611. <file name="index.html">
  14612. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14613. <select>
  14614. <option>Hello!</option>
  14615. <option id="greet" ng-selected="selected">Greetings!</option>
  14616. </select>
  14617. </file>
  14618. <file name="protractor.js" type="protractor">
  14619. it('should select Greetings!', function() {
  14620. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14621. element(by.model('selected')).click();
  14622. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14623. });
  14624. </file>
  14625. </example>
  14626. *
  14627. * @element OPTION
  14628. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14629. * then special attribute "selected" will be set on the element
  14630. */
  14631. /**
  14632. * @ngdoc directive
  14633. * @name ngOpen
  14634. * @restrict A
  14635. * @priority 100
  14636. *
  14637. * @description
  14638. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14639. * such as open. (Their presence means true and their absence means false.)
  14640. * If we put an Angular interpolation expression into such an attribute then the
  14641. * binding information would be lost when the browser removes the attribute.
  14642. * The `ngOpen` directive solves this problem for the `open` attribute.
  14643. * This complementary directive is not removed by the browser and so provides
  14644. * a permanent reliable place to store the binding information.
  14645. * @example
  14646. <example>
  14647. <file name="index.html">
  14648. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14649. <details id="details" ng-open="open">
  14650. <summary>Show/Hide me</summary>
  14651. </details>
  14652. </file>
  14653. <file name="protractor.js" type="protractor">
  14654. it('should toggle open', function() {
  14655. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14656. element(by.model('open')).click();
  14657. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14658. });
  14659. </file>
  14660. </example>
  14661. *
  14662. * @element DETAILS
  14663. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14664. * then special attribute "open" will be set on the element
  14665. */
  14666. var ngAttributeAliasDirectives = {};
  14667. // boolean attrs are evaluated
  14668. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14669. // binding to multiple is not supported
  14670. if (propName == "multiple") return;
  14671. var normalized = directiveNormalize('ng-' + attrName);
  14672. ngAttributeAliasDirectives[normalized] = function() {
  14673. return {
  14674. priority: 100,
  14675. link: function(scope, element, attr) {
  14676. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14677. attr.$set(attrName, !!value);
  14678. });
  14679. }
  14680. };
  14681. };
  14682. });
  14683. // ng-src, ng-srcset, ng-href are interpolated
  14684. forEach(['src', 'srcset', 'href'], function(attrName) {
  14685. var normalized = directiveNormalize('ng-' + attrName);
  14686. ngAttributeAliasDirectives[normalized] = function() {
  14687. return {
  14688. priority: 99, // it needs to run after the attributes are interpolated
  14689. link: function(scope, element, attr) {
  14690. var propName = attrName,
  14691. name = attrName;
  14692. if (attrName === 'href' &&
  14693. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14694. name = 'xlinkHref';
  14695. attr.$attr[name] = 'xlink:href';
  14696. propName = null;
  14697. }
  14698. attr.$observe(normalized, function(value) {
  14699. if (!value) {
  14700. if (attrName === 'href') {
  14701. attr.$set(name, null);
  14702. }
  14703. return;
  14704. }
  14705. attr.$set(name, value);
  14706. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14707. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14708. // to set the property as well to achieve the desired effect.
  14709. // we use attr[attrName] value since $set can sanitize the url.
  14710. if (msie && propName) element.prop(propName, attr[name]);
  14711. });
  14712. }
  14713. };
  14714. };
  14715. });
  14716. /* global -nullFormCtrl */
  14717. var nullFormCtrl = {
  14718. $addControl: noop,
  14719. $removeControl: noop,
  14720. $setValidity: noop,
  14721. $setDirty: noop,
  14722. $setPristine: noop
  14723. };
  14724. /**
  14725. * @ngdoc type
  14726. * @name form.FormController
  14727. *
  14728. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14729. * @property {boolean} $dirty True if user has already interacted with the form.
  14730. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14731. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14732. *
  14733. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14734. * forms, where:
  14735. *
  14736. * - keys are validation tokens (error names),
  14737. * - values are arrays of controls or forms that are invalid for given error name.
  14738. *
  14739. *
  14740. * Built-in validation tokens:
  14741. *
  14742. * - `email`
  14743. * - `max`
  14744. * - `maxlength`
  14745. * - `min`
  14746. * - `minlength`
  14747. * - `number`
  14748. * - `pattern`
  14749. * - `required`
  14750. * - `url`
  14751. *
  14752. * @description
  14753. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  14754. * such as being valid/invalid or dirty/pristine.
  14755. *
  14756. * Each {@link ng.directive:form form} directive creates an instance
  14757. * of `FormController`.
  14758. *
  14759. */
  14760. //asks for $scope to fool the BC controller module
  14761. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14762. function FormController(element, attrs, $scope, $animate) {
  14763. var form = this,
  14764. parentForm = element.parent().controller('form') || nullFormCtrl,
  14765. invalidCount = 0, // used to easily determine if we are valid
  14766. errors = form.$error = {},
  14767. controls = [];
  14768. // init state
  14769. form.$name = attrs.name || attrs.ngForm;
  14770. form.$dirty = false;
  14771. form.$pristine = true;
  14772. form.$valid = true;
  14773. form.$invalid = false;
  14774. parentForm.$addControl(form);
  14775. // Setup initial state of the control
  14776. element.addClass(PRISTINE_CLASS);
  14777. toggleValidCss(true);
  14778. // convenience method for easy toggling of classes
  14779. function toggleValidCss(isValid, validationErrorKey) {
  14780. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14781. $animate.setClass(element,
  14782. (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey,
  14783. (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14784. }
  14785. /**
  14786. * @ngdoc method
  14787. * @name form.FormController#$addControl
  14788. *
  14789. * @description
  14790. * Register a control with the form.
  14791. *
  14792. * Input elements using ngModelController do this automatically when they are linked.
  14793. */
  14794. form.$addControl = function(control) {
  14795. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14796. // and not added to the scope. Now we throw an error.
  14797. assertNotHasOwnProperty(control.$name, 'input');
  14798. controls.push(control);
  14799. if (control.$name) {
  14800. form[control.$name] = control;
  14801. }
  14802. };
  14803. /**
  14804. * @ngdoc method
  14805. * @name form.FormController#$removeControl
  14806. *
  14807. * @description
  14808. * Deregister a control from the form.
  14809. *
  14810. * Input elements using ngModelController do this automatically when they are destroyed.
  14811. */
  14812. form.$removeControl = function(control) {
  14813. if (control.$name && form[control.$name] === control) {
  14814. delete form[control.$name];
  14815. }
  14816. forEach(errors, function(queue, validationToken) {
  14817. form.$setValidity(validationToken, true, control);
  14818. });
  14819. arrayRemove(controls, control);
  14820. };
  14821. /**
  14822. * @ngdoc method
  14823. * @name form.FormController#$setValidity
  14824. *
  14825. * @description
  14826. * Sets the validity of a form control.
  14827. *
  14828. * This method will also propagate to parent forms.
  14829. */
  14830. form.$setValidity = function(validationToken, isValid, control) {
  14831. var queue = errors[validationToken];
  14832. if (isValid) {
  14833. if (queue) {
  14834. arrayRemove(queue, control);
  14835. if (!queue.length) {
  14836. invalidCount--;
  14837. if (!invalidCount) {
  14838. toggleValidCss(isValid);
  14839. form.$valid = true;
  14840. form.$invalid = false;
  14841. }
  14842. errors[validationToken] = false;
  14843. toggleValidCss(true, validationToken);
  14844. parentForm.$setValidity(validationToken, true, form);
  14845. }
  14846. }
  14847. } else {
  14848. if (!invalidCount) {
  14849. toggleValidCss(isValid);
  14850. }
  14851. if (queue) {
  14852. if (includes(queue, control)) return;
  14853. } else {
  14854. errors[validationToken] = queue = [];
  14855. invalidCount++;
  14856. toggleValidCss(false, validationToken);
  14857. parentForm.$setValidity(validationToken, false, form);
  14858. }
  14859. queue.push(control);
  14860. form.$valid = false;
  14861. form.$invalid = true;
  14862. }
  14863. };
  14864. /**
  14865. * @ngdoc method
  14866. * @name form.FormController#$setDirty
  14867. *
  14868. * @description
  14869. * Sets the form to a dirty state.
  14870. *
  14871. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14872. * state (ng-dirty class). This method will also propagate to parent forms.
  14873. */
  14874. form.$setDirty = function() {
  14875. $animate.removeClass(element, PRISTINE_CLASS);
  14876. $animate.addClass(element, DIRTY_CLASS);
  14877. form.$dirty = true;
  14878. form.$pristine = false;
  14879. parentForm.$setDirty();
  14880. };
  14881. /**
  14882. * @ngdoc method
  14883. * @name form.FormController#$setPristine
  14884. *
  14885. * @description
  14886. * Sets the form to its pristine state.
  14887. *
  14888. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14889. * state (ng-pristine class). This method will also propagate to all the controls contained
  14890. * in this form.
  14891. *
  14892. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14893. * saving or resetting it.
  14894. */
  14895. form.$setPristine = function () {
  14896. $animate.removeClass(element, DIRTY_CLASS);
  14897. $animate.addClass(element, PRISTINE_CLASS);
  14898. form.$dirty = false;
  14899. form.$pristine = true;
  14900. forEach(controls, function(control) {
  14901. control.$setPristine();
  14902. });
  14903. };
  14904. }
  14905. /**
  14906. * @ngdoc directive
  14907. * @name ngForm
  14908. * @restrict EAC
  14909. *
  14910. * @description
  14911. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14912. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14913. * sub-group of controls needs to be determined.
  14914. *
  14915. * Note: the purpose of `ngForm` is to group controls,
  14916. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14917. * (e.g. posting to the server, ...).
  14918. *
  14919. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14920. * related scope, under this name.
  14921. *
  14922. */
  14923. /**
  14924. * @ngdoc directive
  14925. * @name form
  14926. * @restrict E
  14927. *
  14928. * @description
  14929. * Directive that instantiates
  14930. * {@link form.FormController FormController}.
  14931. *
  14932. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14933. * this name.
  14934. *
  14935. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14936. *
  14937. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14938. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14939. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14940. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14941. * using Angular validation directives in forms that are dynamically generated using the
  14942. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14943. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14944. * `ngForm` directive and nest these in an outer `form` element.
  14945. *
  14946. *
  14947. * # CSS classes
  14948. * - `ng-valid` is set if the form is valid.
  14949. * - `ng-invalid` is set if the form is invalid.
  14950. * - `ng-pristine` is set if the form is pristine.
  14951. * - `ng-dirty` is set if the form is dirty.
  14952. *
  14953. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14954. *
  14955. *
  14956. * # Submitting a form and preventing the default action
  14957. *
  14958. * Since the role of forms in client-side Angular applications is different than in classical
  14959. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14960. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14961. * to handle the form submission in an application-specific way.
  14962. *
  14963. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14964. * `<form>` element has an `action` attribute specified.
  14965. *
  14966. * You can use one of the following two ways to specify what javascript method should be called when
  14967. * a form is submitted:
  14968. *
  14969. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14970. * - {@link ng.directive:ngClick ngClick} directive on the first
  14971. * button or input field of type submit (input[type=submit])
  14972. *
  14973. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14974. * or {@link ng.directive:ngClick ngClick} directives.
  14975. * This is because of the following form submission rules in the HTML specification:
  14976. *
  14977. * - If a form has only one input field then hitting enter in this field triggers form submit
  14978. * (`ngSubmit`)
  14979. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14980. * doesn't trigger submit
  14981. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14982. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14983. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14984. *
  14985. *
  14986. * ## Animation Hooks
  14987. *
  14988. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  14989. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  14990. * other validations that are performed within the form. Animations in ngForm are similar to how
  14991. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  14992. * as JS animations.
  14993. *
  14994. * The following example shows a simple way to utilize CSS transitions to style a form element
  14995. * that has been rendered as invalid after it has been validated:
  14996. *
  14997. * <pre>
  14998. * //be sure to include ngAnimate as a module to hook into more
  14999. * //advanced animations
  15000. * .my-form {
  15001. * transition:0.5s linear all;
  15002. * background: white;
  15003. * }
  15004. * .my-form.ng-invalid {
  15005. * background: red;
  15006. * color:white;
  15007. * }
  15008. * </pre>
  15009. *
  15010. * @example
  15011. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  15012. <file name="index.html">
  15013. <script>
  15014. angular.module('formExample', [])
  15015. .controller('FormController', ['$scope', function($scope) {
  15016. $scope.userType = 'guest';
  15017. }]);
  15018. </script>
  15019. <style>
  15020. .my-form {
  15021. -webkit-transition:all linear 0.5s;
  15022. transition:all linear 0.5s;
  15023. background: transparent;
  15024. }
  15025. .my-form.ng-invalid {
  15026. background: red;
  15027. }
  15028. </style>
  15029. <form name="myForm" ng-controller="FormController" class="my-form">
  15030. userType: <input name="input" ng-model="userType" required>
  15031. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  15032. <tt>userType = {{userType}}</tt><br>
  15033. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  15034. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  15035. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15036. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15037. </form>
  15038. </file>
  15039. <file name="protractor.js" type="protractor">
  15040. it('should initialize to model', function() {
  15041. var userType = element(by.binding('userType'));
  15042. var valid = element(by.binding('myForm.input.$valid'));
  15043. expect(userType.getText()).toContain('guest');
  15044. expect(valid.getText()).toContain('true');
  15045. });
  15046. it('should be invalid if empty', function() {
  15047. var userType = element(by.binding('userType'));
  15048. var valid = element(by.binding('myForm.input.$valid'));
  15049. var userInput = element(by.model('userType'));
  15050. userInput.clear();
  15051. userInput.sendKeys('');
  15052. expect(userType.getText()).toEqual('userType =');
  15053. expect(valid.getText()).toContain('false');
  15054. });
  15055. </file>
  15056. </example>
  15057. *
  15058. * @param {string=} name Name of the form. If specified, the form controller will be published into
  15059. * related scope, under this name.
  15060. */
  15061. var formDirectiveFactory = function(isNgForm) {
  15062. return ['$timeout', function($timeout) {
  15063. var formDirective = {
  15064. name: 'form',
  15065. restrict: isNgForm ? 'EAC' : 'E',
  15066. controller: FormController,
  15067. compile: function() {
  15068. return {
  15069. pre: function(scope, formElement, attr, controller) {
  15070. if (!attr.action) {
  15071. // we can't use jq events because if a form is destroyed during submission the default
  15072. // action is not prevented. see #1238
  15073. //
  15074. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  15075. // page reload if the form was destroyed by submission of the form via a click handler
  15076. // on a button in the form. Looks like an IE9 specific bug.
  15077. var preventDefaultListener = function(event) {
  15078. event.preventDefault
  15079. ? event.preventDefault()
  15080. : event.returnValue = false; // IE
  15081. };
  15082. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15083. // unregister the preventDefault listener so that we don't not leak memory but in a
  15084. // way that will achieve the prevention of the default action.
  15085. formElement.on('$destroy', function() {
  15086. $timeout(function() {
  15087. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15088. }, 0, false);
  15089. });
  15090. }
  15091. var parentFormCtrl = formElement.parent().controller('form'),
  15092. alias = attr.name || attr.ngForm;
  15093. if (alias) {
  15094. setter(scope, alias, controller, alias);
  15095. }
  15096. if (parentFormCtrl) {
  15097. formElement.on('$destroy', function() {
  15098. parentFormCtrl.$removeControl(controller);
  15099. if (alias) {
  15100. setter(scope, alias, undefined, alias);
  15101. }
  15102. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  15103. });
  15104. }
  15105. }
  15106. };
  15107. }
  15108. };
  15109. return formDirective;
  15110. }];
  15111. };
  15112. var formDirective = formDirectiveFactory();
  15113. var ngFormDirective = formDirectiveFactory(true);
  15114. /* global VALID_CLASS: true,
  15115. INVALID_CLASS: true,
  15116. PRISTINE_CLASS: true,
  15117. DIRTY_CLASS: true
  15118. */
  15119. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  15120. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  15121. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  15122. var inputType = {
  15123. /**
  15124. * @ngdoc input
  15125. * @name input[text]
  15126. *
  15127. * @description
  15128. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  15129. *
  15130. * *NOTE* Not every feature offered is available for all input types.
  15131. *
  15132. * @param {string} ngModel Assignable angular expression to data-bind to.
  15133. * @param {string=} name Property name of the form under which the control is published.
  15134. * @param {string=} required Adds `required` validation error key if the value is not entered.
  15135. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15136. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15137. * `required` when you want to data-bind to the `required` attribute.
  15138. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15139. * minlength.
  15140. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15141. * maxlength.
  15142. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15143. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15144. * patterns defined as scope expressions.
  15145. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15146. * interaction with the input element.
  15147. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15148. * This parameter is ignored for input[type=password] controls, which will never trim the
  15149. * input.
  15150. *
  15151. * @example
  15152. <example name="text-input-directive" module="textInputExample">
  15153. <file name="index.html">
  15154. <script>
  15155. angular.module('textInputExample', [])
  15156. .controller('ExampleController', ['$scope', function($scope) {
  15157. $scope.text = 'guest';
  15158. $scope.word = /^\s*\w*\s*$/;
  15159. }]);
  15160. </script>
  15161. <form name="myForm" ng-controller="ExampleController">
  15162. Single word: <input type="text" name="input" ng-model="text"
  15163. ng-pattern="word" required ng-trim="false">
  15164. <span class="error" ng-show="myForm.input.$error.required">
  15165. Required!</span>
  15166. <span class="error" ng-show="myForm.input.$error.pattern">
  15167. Single word only!</span>
  15168. <tt>text = {{text}}</tt><br/>
  15169. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15170. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15171. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15172. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15173. </form>
  15174. </file>
  15175. <file name="protractor.js" type="protractor">
  15176. var text = element(by.binding('text'));
  15177. var valid = element(by.binding('myForm.input.$valid'));
  15178. var input = element(by.model('text'));
  15179. it('should initialize to model', function() {
  15180. expect(text.getText()).toContain('guest');
  15181. expect(valid.getText()).toContain('true');
  15182. });
  15183. it('should be invalid if empty', function() {
  15184. input.clear();
  15185. input.sendKeys('');
  15186. expect(text.getText()).toEqual('text =');
  15187. expect(valid.getText()).toContain('false');
  15188. });
  15189. it('should be invalid if multi word', function() {
  15190. input.clear();
  15191. input.sendKeys('hello world');
  15192. expect(valid.getText()).toContain('false');
  15193. });
  15194. </file>
  15195. </example>
  15196. */
  15197. 'text': textInputType,
  15198. /**
  15199. * @ngdoc input
  15200. * @name input[number]
  15201. *
  15202. * @description
  15203. * Text input with number validation and transformation. Sets the `number` validation
  15204. * error if not a valid number.
  15205. *
  15206. * @param {string} ngModel Assignable angular expression to data-bind to.
  15207. * @param {string=} name Property name of the form under which the control is published.
  15208. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  15209. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  15210. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15211. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15212. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15213. * `required` when you want to data-bind to the `required` attribute.
  15214. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15215. * minlength.
  15216. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15217. * maxlength.
  15218. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15219. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15220. * patterns defined as scope expressions.
  15221. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15222. * interaction with the input element.
  15223. *
  15224. * @example
  15225. <example name="number-input-directive" module="numberExample">
  15226. <file name="index.html">
  15227. <script>
  15228. angular.module('numberExample', [])
  15229. .controller('ExampleController', ['$scope', function($scope) {
  15230. $scope.value = 12;
  15231. }]);
  15232. </script>
  15233. <form name="myForm" ng-controller="ExampleController">
  15234. Number: <input type="number" name="input" ng-model="value"
  15235. min="0" max="99" required>
  15236. <span class="error" ng-show="myForm.input.$error.required">
  15237. Required!</span>
  15238. <span class="error" ng-show="myForm.input.$error.number">
  15239. Not valid number!</span>
  15240. <tt>value = {{value}}</tt><br/>
  15241. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15242. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15243. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15244. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15245. </form>
  15246. </file>
  15247. <file name="protractor.js" type="protractor">
  15248. var value = element(by.binding('value'));
  15249. var valid = element(by.binding('myForm.input.$valid'));
  15250. var input = element(by.model('value'));
  15251. it('should initialize to model', function() {
  15252. expect(value.getText()).toContain('12');
  15253. expect(valid.getText()).toContain('true');
  15254. });
  15255. it('should be invalid if empty', function() {
  15256. input.clear();
  15257. input.sendKeys('');
  15258. expect(value.getText()).toEqual('value =');
  15259. expect(valid.getText()).toContain('false');
  15260. });
  15261. it('should be invalid if over max', function() {
  15262. input.clear();
  15263. input.sendKeys('123');
  15264. expect(value.getText()).toEqual('value =');
  15265. expect(valid.getText()).toContain('false');
  15266. });
  15267. </file>
  15268. </example>
  15269. */
  15270. 'number': numberInputType,
  15271. /**
  15272. * @ngdoc input
  15273. * @name input[url]
  15274. *
  15275. * @description
  15276. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  15277. * valid URL.
  15278. *
  15279. * @param {string} ngModel Assignable angular expression to data-bind to.
  15280. * @param {string=} name Property name of the form under which the control is published.
  15281. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15282. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15283. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15284. * `required` when you want to data-bind to the `required` attribute.
  15285. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15286. * minlength.
  15287. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15288. * maxlength.
  15289. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15290. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15291. * patterns defined as scope expressions.
  15292. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15293. * interaction with the input element.
  15294. *
  15295. * @example
  15296. <example name="url-input-directive" module="urlExample">
  15297. <file name="index.html">
  15298. <script>
  15299. angular.module('urlExample', [])
  15300. .controller('ExampleController', ['$scope', function($scope) {
  15301. $scope.text = 'http://google.com';
  15302. }]);
  15303. </script>
  15304. <form name="myForm" ng-controller="ExampleController">
  15305. URL: <input type="url" name="input" ng-model="text" required>
  15306. <span class="error" ng-show="myForm.input.$error.required">
  15307. Required!</span>
  15308. <span class="error" ng-show="myForm.input.$error.url">
  15309. Not valid url!</span>
  15310. <tt>text = {{text}}</tt><br/>
  15311. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15312. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15313. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15314. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15315. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  15316. </form>
  15317. </file>
  15318. <file name="protractor.js" type="protractor">
  15319. var text = element(by.binding('text'));
  15320. var valid = element(by.binding('myForm.input.$valid'));
  15321. var input = element(by.model('text'));
  15322. it('should initialize to model', function() {
  15323. expect(text.getText()).toContain('http://google.com');
  15324. expect(valid.getText()).toContain('true');
  15325. });
  15326. it('should be invalid if empty', function() {
  15327. input.clear();
  15328. input.sendKeys('');
  15329. expect(text.getText()).toEqual('text =');
  15330. expect(valid.getText()).toContain('false');
  15331. });
  15332. it('should be invalid if not url', function() {
  15333. input.clear();
  15334. input.sendKeys('box');
  15335. expect(valid.getText()).toContain('false');
  15336. });
  15337. </file>
  15338. </example>
  15339. */
  15340. 'url': urlInputType,
  15341. /**
  15342. * @ngdoc input
  15343. * @name input[email]
  15344. *
  15345. * @description
  15346. * Text input with email validation. Sets the `email` validation error key if not a valid email
  15347. * address.
  15348. *
  15349. * @param {string} ngModel Assignable angular expression to data-bind to.
  15350. * @param {string=} name Property name of the form under which the control is published.
  15351. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15352. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15353. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15354. * `required` when you want to data-bind to the `required` attribute.
  15355. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15356. * minlength.
  15357. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15358. * maxlength.
  15359. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15360. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15361. * patterns defined as scope expressions.
  15362. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15363. * interaction with the input element.
  15364. *
  15365. * @example
  15366. <example name="email-input-directive" module="emailExample">
  15367. <file name="index.html">
  15368. <script>
  15369. angular.module('emailExample', [])
  15370. .controller('ExampleController', ['$scope', function($scope) {
  15371. $scope.text = 'me@example.com';
  15372. }]);
  15373. </script>
  15374. <form name="myForm" ng-controller="ExampleController">
  15375. Email: <input type="email" name="input" ng-model="text" required>
  15376. <span class="error" ng-show="myForm.input.$error.required">
  15377. Required!</span>
  15378. <span class="error" ng-show="myForm.input.$error.email">
  15379. Not valid email!</span>
  15380. <tt>text = {{text}}</tt><br/>
  15381. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15382. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15383. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15384. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15385. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  15386. </form>
  15387. </file>
  15388. <file name="protractor.js" type="protractor">
  15389. var text = element(by.binding('text'));
  15390. var valid = element(by.binding('myForm.input.$valid'));
  15391. var input = element(by.model('text'));
  15392. it('should initialize to model', function() {
  15393. expect(text.getText()).toContain('me@example.com');
  15394. expect(valid.getText()).toContain('true');
  15395. });
  15396. it('should be invalid if empty', function() {
  15397. input.clear();
  15398. input.sendKeys('');
  15399. expect(text.getText()).toEqual('text =');
  15400. expect(valid.getText()).toContain('false');
  15401. });
  15402. it('should be invalid if not email', function() {
  15403. input.clear();
  15404. input.sendKeys('xxx');
  15405. expect(valid.getText()).toContain('false');
  15406. });
  15407. </file>
  15408. </example>
  15409. */
  15410. 'email': emailInputType,
  15411. /**
  15412. * @ngdoc input
  15413. * @name input[radio]
  15414. *
  15415. * @description
  15416. * HTML radio button.
  15417. *
  15418. * @param {string} ngModel Assignable angular expression to data-bind to.
  15419. * @param {string} value The value to which the expression should be set when selected.
  15420. * @param {string=} name Property name of the form under which the control is published.
  15421. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15422. * interaction with the input element.
  15423. * @param {string} ngValue Angular expression which sets the value to which the expression should
  15424. * be set when selected.
  15425. *
  15426. * @example
  15427. <example name="radio-input-directive" module="radioExample">
  15428. <file name="index.html">
  15429. <script>
  15430. angular.module('radioExample', [])
  15431. .controller('ExampleController', ['$scope', function($scope) {
  15432. $scope.color = 'blue';
  15433. $scope.specialValue = {
  15434. "id": "12345",
  15435. "value": "green"
  15436. };
  15437. }]);
  15438. </script>
  15439. <form name="myForm" ng-controller="ExampleController">
  15440. <input type="radio" ng-model="color" value="red"> Red <br/>
  15441. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  15442. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  15443. <tt>color = {{color | json}}</tt><br/>
  15444. </form>
  15445. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  15446. </file>
  15447. <file name="protractor.js" type="protractor">
  15448. it('should change state', function() {
  15449. var color = element(by.binding('color'));
  15450. expect(color.getText()).toContain('blue');
  15451. element.all(by.model('color')).get(0).click();
  15452. expect(color.getText()).toContain('red');
  15453. });
  15454. </file>
  15455. </example>
  15456. */
  15457. 'radio': radioInputType,
  15458. /**
  15459. * @ngdoc input
  15460. * @name input[checkbox]
  15461. *
  15462. * @description
  15463. * HTML checkbox.
  15464. *
  15465. * @param {string} ngModel Assignable angular expression to data-bind to.
  15466. * @param {string=} name Property name of the form under which the control is published.
  15467. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  15468. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  15469. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15470. * interaction with the input element.
  15471. *
  15472. * @example
  15473. <example name="checkbox-input-directive" module="checkboxExample">
  15474. <file name="index.html">
  15475. <script>
  15476. angular.module('checkboxExample', [])
  15477. .controller('ExampleController', ['$scope', function($scope) {
  15478. $scope.value1 = true;
  15479. $scope.value2 = 'YES'
  15480. }]);
  15481. </script>
  15482. <form name="myForm" ng-controller="ExampleController">
  15483. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15484. Value2: <input type="checkbox" ng-model="value2"
  15485. ng-true-value="YES" ng-false-value="NO"> <br/>
  15486. <tt>value1 = {{value1}}</tt><br/>
  15487. <tt>value2 = {{value2}}</tt><br/>
  15488. </form>
  15489. </file>
  15490. <file name="protractor.js" type="protractor">
  15491. it('should change state', function() {
  15492. var value1 = element(by.binding('value1'));
  15493. var value2 = element(by.binding('value2'));
  15494. expect(value1.getText()).toContain('true');
  15495. expect(value2.getText()).toContain('YES');
  15496. element(by.model('value1')).click();
  15497. element(by.model('value2')).click();
  15498. expect(value1.getText()).toContain('false');
  15499. expect(value2.getText()).toContain('NO');
  15500. });
  15501. </file>
  15502. </example>
  15503. */
  15504. 'checkbox': checkboxInputType,
  15505. 'hidden': noop,
  15506. 'button': noop,
  15507. 'submit': noop,
  15508. 'reset': noop,
  15509. 'file': noop
  15510. };
  15511. // A helper function to call $setValidity and return the value / undefined,
  15512. // a pattern that is repeated a lot in the input validation logic.
  15513. function validate(ctrl, validatorName, validity, value){
  15514. ctrl.$setValidity(validatorName, validity);
  15515. return validity ? value : undefined;
  15516. }
  15517. function testFlags(validity, flags) {
  15518. var i, flag;
  15519. if (flags) {
  15520. for (i=0; i<flags.length; ++i) {
  15521. flag = flags[i];
  15522. if (validity[flag]) {
  15523. return true;
  15524. }
  15525. }
  15526. }
  15527. return false;
  15528. }
  15529. // Pass validity so that behaviour can be mocked easier.
  15530. function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
  15531. if (isObject(validity)) {
  15532. ctrl.$$hasNativeValidators = true;
  15533. var validator = function(value) {
  15534. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15535. // perform the required validation)
  15536. if (!ctrl.$error[validatorName] &&
  15537. !testFlags(validity, ignoreFlags) &&
  15538. testFlags(validity, badFlags)) {
  15539. ctrl.$setValidity(validatorName, false);
  15540. return;
  15541. }
  15542. return value;
  15543. };
  15544. ctrl.$parsers.push(validator);
  15545. }
  15546. }
  15547. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15548. var validity = element.prop(VALIDITY_STATE_PROPERTY);
  15549. var placeholder = element[0].placeholder, noevent = {};
  15550. var type = lowercase(element[0].type);
  15551. ctrl.$$validityState = validity;
  15552. // In composition mode, users are still inputing intermediate text buffer,
  15553. // hold the listener until composition is done.
  15554. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15555. if (!$sniffer.android) {
  15556. var composing = false;
  15557. element.on('compositionstart', function(data) {
  15558. composing = true;
  15559. });
  15560. element.on('compositionend', function() {
  15561. composing = false;
  15562. listener();
  15563. });
  15564. }
  15565. var listener = function(ev) {
  15566. if (composing) return;
  15567. var value = element.val();
  15568. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  15569. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  15570. // IE also sends input events for other non-input-related things, (such as focusing on a
  15571. // form control), so this change is not entirely enough to solve this.
  15572. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  15573. placeholder = element[0].placeholder;
  15574. return;
  15575. }
  15576. // By default we will trim the value
  15577. // If the attribute ng-trim exists we will avoid trimming
  15578. // If input type is 'password', the value is never trimmed
  15579. if (type !== 'password' && (toBoolean(attr.ngTrim || 'T'))) {
  15580. value = trim(value);
  15581. }
  15582. // If a control is suffering from bad input, browsers discard its value, so it may be
  15583. // necessary to revalidate even if the control's value is the same empty value twice in
  15584. // a row.
  15585. var revalidate = validity && ctrl.$$hasNativeValidators;
  15586. if (ctrl.$viewValue !== value || (value === '' && revalidate)) {
  15587. if (scope.$root.$$phase) {
  15588. ctrl.$setViewValue(value);
  15589. } else {
  15590. scope.$apply(function() {
  15591. ctrl.$setViewValue(value);
  15592. });
  15593. }
  15594. }
  15595. };
  15596. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15597. // input event on backspace, delete or cut
  15598. if ($sniffer.hasEvent('input')) {
  15599. element.on('input', listener);
  15600. } else {
  15601. var timeout;
  15602. var deferListener = function() {
  15603. if (!timeout) {
  15604. timeout = $browser.defer(function() {
  15605. listener();
  15606. timeout = null;
  15607. });
  15608. }
  15609. };
  15610. element.on('keydown', function(event) {
  15611. var key = event.keyCode;
  15612. // ignore
  15613. // command modifiers arrows
  15614. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15615. deferListener();
  15616. });
  15617. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15618. if ($sniffer.hasEvent('paste')) {
  15619. element.on('paste cut', deferListener);
  15620. }
  15621. }
  15622. // if user paste into input using mouse on older browser
  15623. // or form autocomplete on newer browser, we need "change" event to catch it
  15624. element.on('change', listener);
  15625. ctrl.$render = function() {
  15626. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15627. };
  15628. // pattern validator
  15629. var pattern = attr.ngPattern,
  15630. patternValidator,
  15631. match;
  15632. if (pattern) {
  15633. var validateRegex = function(regexp, value) {
  15634. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15635. };
  15636. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15637. if (match) {
  15638. pattern = new RegExp(match[1], match[2]);
  15639. patternValidator = function(value) {
  15640. return validateRegex(pattern, value);
  15641. };
  15642. } else {
  15643. patternValidator = function(value) {
  15644. var patternObj = scope.$eval(pattern);
  15645. if (!patternObj || !patternObj.test) {
  15646. throw minErr('ngPattern')('noregexp',
  15647. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15648. patternObj, startingTag(element));
  15649. }
  15650. return validateRegex(patternObj, value);
  15651. };
  15652. }
  15653. ctrl.$formatters.push(patternValidator);
  15654. ctrl.$parsers.push(patternValidator);
  15655. }
  15656. // min length validator
  15657. if (attr.ngMinlength) {
  15658. var minlength = int(attr.ngMinlength);
  15659. var minLengthValidator = function(value) {
  15660. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15661. };
  15662. ctrl.$parsers.push(minLengthValidator);
  15663. ctrl.$formatters.push(minLengthValidator);
  15664. }
  15665. // max length validator
  15666. if (attr.ngMaxlength) {
  15667. var maxlength = int(attr.ngMaxlength);
  15668. var maxLengthValidator = function(value) {
  15669. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15670. };
  15671. ctrl.$parsers.push(maxLengthValidator);
  15672. ctrl.$formatters.push(maxLengthValidator);
  15673. }
  15674. }
  15675. var numberBadFlags = ['badInput'];
  15676. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15677. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15678. ctrl.$parsers.push(function(value) {
  15679. var empty = ctrl.$isEmpty(value);
  15680. if (empty || NUMBER_REGEXP.test(value)) {
  15681. ctrl.$setValidity('number', true);
  15682. return value === '' ? null : (empty ? value : parseFloat(value));
  15683. } else {
  15684. ctrl.$setValidity('number', false);
  15685. return undefined;
  15686. }
  15687. });
  15688. addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
  15689. ctrl.$formatters.push(function(value) {
  15690. return ctrl.$isEmpty(value) ? '' : '' + value;
  15691. });
  15692. if (attr.min) {
  15693. var minValidator = function(value) {
  15694. var min = parseFloat(attr.min);
  15695. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15696. };
  15697. ctrl.$parsers.push(minValidator);
  15698. ctrl.$formatters.push(minValidator);
  15699. }
  15700. if (attr.max) {
  15701. var maxValidator = function(value) {
  15702. var max = parseFloat(attr.max);
  15703. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15704. };
  15705. ctrl.$parsers.push(maxValidator);
  15706. ctrl.$formatters.push(maxValidator);
  15707. }
  15708. ctrl.$formatters.push(function(value) {
  15709. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15710. });
  15711. }
  15712. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15713. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15714. var urlValidator = function(value) {
  15715. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15716. };
  15717. ctrl.$formatters.push(urlValidator);
  15718. ctrl.$parsers.push(urlValidator);
  15719. }
  15720. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15721. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15722. var emailValidator = function(value) {
  15723. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15724. };
  15725. ctrl.$formatters.push(emailValidator);
  15726. ctrl.$parsers.push(emailValidator);
  15727. }
  15728. function radioInputType(scope, element, attr, ctrl) {
  15729. // make the name unique, if not defined
  15730. if (isUndefined(attr.name)) {
  15731. element.attr('name', nextUid());
  15732. }
  15733. element.on('click', function() {
  15734. if (element[0].checked) {
  15735. scope.$apply(function() {
  15736. ctrl.$setViewValue(attr.value);
  15737. });
  15738. }
  15739. });
  15740. ctrl.$render = function() {
  15741. var value = attr.value;
  15742. element[0].checked = (value == ctrl.$viewValue);
  15743. };
  15744. attr.$observe('value', ctrl.$render);
  15745. }
  15746. function checkboxInputType(scope, element, attr, ctrl) {
  15747. var trueValue = attr.ngTrueValue,
  15748. falseValue = attr.ngFalseValue;
  15749. if (!isString(trueValue)) trueValue = true;
  15750. if (!isString(falseValue)) falseValue = false;
  15751. element.on('click', function() {
  15752. scope.$apply(function() {
  15753. ctrl.$setViewValue(element[0].checked);
  15754. });
  15755. });
  15756. ctrl.$render = function() {
  15757. element[0].checked = ctrl.$viewValue;
  15758. };
  15759. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15760. ctrl.$isEmpty = function(value) {
  15761. return value !== trueValue;
  15762. };
  15763. ctrl.$formatters.push(function(value) {
  15764. return value === trueValue;
  15765. });
  15766. ctrl.$parsers.push(function(value) {
  15767. return value ? trueValue : falseValue;
  15768. });
  15769. }
  15770. /**
  15771. * @ngdoc directive
  15772. * @name textarea
  15773. * @restrict E
  15774. *
  15775. * @description
  15776. * HTML textarea element control with angular data-binding. The data-binding and validation
  15777. * properties of this element are exactly the same as those of the
  15778. * {@link ng.directive:input input element}.
  15779. *
  15780. * @param {string} ngModel Assignable angular expression to data-bind to.
  15781. * @param {string=} name Property name of the form under which the control is published.
  15782. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15783. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15784. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15785. * `required` when you want to data-bind to the `required` attribute.
  15786. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15787. * minlength.
  15788. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15789. * maxlength.
  15790. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15791. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15792. * patterns defined as scope expressions.
  15793. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15794. * interaction with the input element.
  15795. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15796. */
  15797. /**
  15798. * @ngdoc directive
  15799. * @name input
  15800. * @restrict E
  15801. *
  15802. * @description
  15803. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15804. * and polyfills the HTML5 validation behavior for older browsers.
  15805. *
  15806. * *NOTE* Not every feature offered is available for all input types.
  15807. *
  15808. * @param {string} ngModel Assignable angular expression to data-bind to.
  15809. * @param {string=} name Property name of the form under which the control is published.
  15810. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15811. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15812. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15813. * minlength.
  15814. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15815. * maxlength.
  15816. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15817. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15818. * patterns defined as scope expressions.
  15819. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15820. * interaction with the input element.
  15821. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15822. * This parameter is ignored for input[type=password] controls, which will never trim the
  15823. * input.
  15824. *
  15825. * @example
  15826. <example name="input-directive" module="inputExample">
  15827. <file name="index.html">
  15828. <script>
  15829. angular.module('inputExample', [])
  15830. .controller('ExampleController', ['$scope', function($scope) {
  15831. $scope.user = {name: 'guest', last: 'visitor'};
  15832. }]);
  15833. </script>
  15834. <div ng-controller="ExampleController">
  15835. <form name="myForm">
  15836. User name: <input type="text" name="userName" ng-model="user.name" required>
  15837. <span class="error" ng-show="myForm.userName.$error.required">
  15838. Required!</span><br>
  15839. Last name: <input type="text" name="lastName" ng-model="user.last"
  15840. ng-minlength="3" ng-maxlength="10">
  15841. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15842. Too short!</span>
  15843. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15844. Too long!</span><br>
  15845. </form>
  15846. <hr>
  15847. <tt>user = {{user}}</tt><br/>
  15848. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15849. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15850. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15851. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15852. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15853. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15854. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15855. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15856. </div>
  15857. </file>
  15858. <file name="protractor.js" type="protractor">
  15859. var user = element(by.binding('{{user}}'));
  15860. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15861. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15862. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15863. var formValid = element(by.binding('myForm.$valid'));
  15864. var userNameInput = element(by.model('user.name'));
  15865. var userLastInput = element(by.model('user.last'));
  15866. it('should initialize to model', function() {
  15867. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15868. expect(userNameValid.getText()).toContain('true');
  15869. expect(formValid.getText()).toContain('true');
  15870. });
  15871. it('should be invalid if empty when required', function() {
  15872. userNameInput.clear();
  15873. userNameInput.sendKeys('');
  15874. expect(user.getText()).toContain('{"last":"visitor"}');
  15875. expect(userNameValid.getText()).toContain('false');
  15876. expect(formValid.getText()).toContain('false');
  15877. });
  15878. it('should be valid if empty when min length is set', function() {
  15879. userLastInput.clear();
  15880. userLastInput.sendKeys('');
  15881. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15882. expect(lastNameValid.getText()).toContain('true');
  15883. expect(formValid.getText()).toContain('true');
  15884. });
  15885. it('should be invalid if less than required min length', function() {
  15886. userLastInput.clear();
  15887. userLastInput.sendKeys('xx');
  15888. expect(user.getText()).toContain('{"name":"guest"}');
  15889. expect(lastNameValid.getText()).toContain('false');
  15890. expect(lastNameError.getText()).toContain('minlength');
  15891. expect(formValid.getText()).toContain('false');
  15892. });
  15893. it('should be invalid if longer than max length', function() {
  15894. userLastInput.clear();
  15895. userLastInput.sendKeys('some ridiculously long name');
  15896. expect(user.getText()).toContain('{"name":"guest"}');
  15897. expect(lastNameValid.getText()).toContain('false');
  15898. expect(lastNameError.getText()).toContain('maxlength');
  15899. expect(formValid.getText()).toContain('false');
  15900. });
  15901. </file>
  15902. </example>
  15903. */
  15904. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15905. return {
  15906. restrict: 'E',
  15907. require: '?ngModel',
  15908. link: function(scope, element, attr, ctrl) {
  15909. if (ctrl) {
  15910. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15911. $browser);
  15912. }
  15913. }
  15914. };
  15915. }];
  15916. var VALID_CLASS = 'ng-valid',
  15917. INVALID_CLASS = 'ng-invalid',
  15918. PRISTINE_CLASS = 'ng-pristine',
  15919. DIRTY_CLASS = 'ng-dirty';
  15920. /**
  15921. * @ngdoc type
  15922. * @name ngModel.NgModelController
  15923. *
  15924. * @property {string} $viewValue Actual string value in the view.
  15925. * @property {*} $modelValue The value in the model, that the control is bound to.
  15926. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15927. the control reads value from the DOM. Each function is called, in turn, passing the value
  15928. through to the next. The last return value is used to populate the model.
  15929. Used to sanitize / convert the value as well as validation. For validation,
  15930. the parsers should update the validity state using
  15931. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15932. and return `undefined` for invalid values.
  15933. *
  15934. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15935. the model value changes. Each function is called, in turn, passing the value through to the
  15936. next. Used to format / convert values for display in the control and validation.
  15937. * ```js
  15938. * function formatter(value) {
  15939. * if (value) {
  15940. * return value.toUpperCase();
  15941. * }
  15942. * }
  15943. * ngModel.$formatters.push(formatter);
  15944. * ```
  15945. *
  15946. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15947. * view value has changed. It is called with no arguments, and its return value is ignored.
  15948. * This can be used in place of additional $watches against the model value.
  15949. *
  15950. * @property {Object} $error An object hash with all errors as keys.
  15951. *
  15952. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15953. * @property {boolean} $dirty True if user has already interacted with the control.
  15954. * @property {boolean} $valid True if there is no error.
  15955. * @property {boolean} $invalid True if at least one error on the control.
  15956. *
  15957. * @description
  15958. *
  15959. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15960. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15961. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15962. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15963. * `NgModelController` for data-binding.
  15964. *
  15965. * ## Custom Control Example
  15966. * This example shows how to use `NgModelController` with a custom control to achieve
  15967. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  15968. * collaborate together to achieve the desired result.
  15969. *
  15970. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  15971. * contents be edited in place by the user. This will not work on older browsers.
  15972. *
  15973. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  15974. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  15975. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  15976. * that content using the `$sce` service.
  15977. *
  15978. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  15979. <file name="style.css">
  15980. [contenteditable] {
  15981. border: 1px solid black;
  15982. background-color: white;
  15983. min-height: 20px;
  15984. }
  15985. .ng-invalid {
  15986. border: 1px solid red;
  15987. }
  15988. </file>
  15989. <file name="script.js">
  15990. angular.module('customControl', ['ngSanitize']).
  15991. directive('contenteditable', ['$sce', function($sce) {
  15992. return {
  15993. restrict: 'A', // only activate on element attribute
  15994. require: '?ngModel', // get a hold of NgModelController
  15995. link: function(scope, element, attrs, ngModel) {
  15996. if(!ngModel) return; // do nothing if no ng-model
  15997. // Specify how UI should be updated
  15998. ngModel.$render = function() {
  15999. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  16000. };
  16001. // Listen for change events to enable binding
  16002. element.on('blur keyup change', function() {
  16003. scope.$evalAsync(read);
  16004. });
  16005. read(); // initialize
  16006. // Write data to the model
  16007. function read() {
  16008. var html = element.html();
  16009. // When we clear the content editable the browser leaves a <br> behind
  16010. // If strip-br attribute is provided then we strip this out
  16011. if( attrs.stripBr && html == '<br>' ) {
  16012. html = '';
  16013. }
  16014. ngModel.$setViewValue(html);
  16015. }
  16016. }
  16017. };
  16018. }]);
  16019. </file>
  16020. <file name="index.html">
  16021. <form name="myForm">
  16022. <div contenteditable
  16023. name="myWidget" ng-model="userContent"
  16024. strip-br="true"
  16025. required>Change me!</div>
  16026. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  16027. <hr>
  16028. <textarea ng-model="userContent"></textarea>
  16029. </form>
  16030. </file>
  16031. <file name="protractor.js" type="protractor">
  16032. it('should data-bind and become invalid', function() {
  16033. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  16034. // SafariDriver can't handle contenteditable
  16035. // and Firefox driver can't clear contenteditables very well
  16036. return;
  16037. }
  16038. var contentEditable = element(by.css('[contenteditable]'));
  16039. var content = 'Change me!';
  16040. expect(contentEditable.getText()).toEqual(content);
  16041. contentEditable.clear();
  16042. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  16043. expect(contentEditable.getText()).toEqual('');
  16044. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  16045. });
  16046. </file>
  16047. * </example>
  16048. *
  16049. *
  16050. */
  16051. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  16052. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  16053. this.$viewValue = Number.NaN;
  16054. this.$modelValue = Number.NaN;
  16055. this.$parsers = [];
  16056. this.$formatters = [];
  16057. this.$viewChangeListeners = [];
  16058. this.$pristine = true;
  16059. this.$dirty = false;
  16060. this.$valid = true;
  16061. this.$invalid = false;
  16062. this.$name = $attr.name;
  16063. var ngModelGet = $parse($attr.ngModel),
  16064. ngModelSet = ngModelGet.assign;
  16065. if (!ngModelSet) {
  16066. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  16067. $attr.ngModel, startingTag($element));
  16068. }
  16069. /**
  16070. * @ngdoc method
  16071. * @name ngModel.NgModelController#$render
  16072. *
  16073. * @description
  16074. * Called when the view needs to be updated. It is expected that the user of the ng-model
  16075. * directive will implement this method.
  16076. */
  16077. this.$render = noop;
  16078. /**
  16079. * @ngdoc method
  16080. * @name ngModel.NgModelController#$isEmpty
  16081. *
  16082. * @description
  16083. * This is called when we need to determine if the value of the input is empty.
  16084. *
  16085. * For instance, the required directive does this to work out if the input has data or not.
  16086. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  16087. *
  16088. * You can override this for input directives whose concept of being empty is different to the
  16089. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  16090. * implies empty.
  16091. *
  16092. * @param {*} value Reference to check.
  16093. * @returns {boolean} True if `value` is empty.
  16094. */
  16095. this.$isEmpty = function(value) {
  16096. return isUndefined(value) || value === '' || value === null || value !== value;
  16097. };
  16098. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  16099. invalidCount = 0, // used to easily determine if we are valid
  16100. $error = this.$error = {}; // keep invalid keys here
  16101. // Setup initial state of the control
  16102. $element.addClass(PRISTINE_CLASS);
  16103. toggleValidCss(true);
  16104. // convenience method for easy toggling of classes
  16105. function toggleValidCss(isValid, validationErrorKey) {
  16106. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  16107. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  16108. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  16109. }
  16110. /**
  16111. * @ngdoc method
  16112. * @name ngModel.NgModelController#$setValidity
  16113. *
  16114. * @description
  16115. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  16116. * does not notify form if given validator is already marked as invalid).
  16117. *
  16118. * This method should be called by validators - i.e. the parser or formatter functions.
  16119. *
  16120. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  16121. * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding.
  16122. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  16123. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  16124. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  16125. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  16126. */
  16127. this.$setValidity = function(validationErrorKey, isValid) {
  16128. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  16129. // jshint -W018
  16130. if ($error[validationErrorKey] === !isValid) return;
  16131. // jshint +W018
  16132. if (isValid) {
  16133. if ($error[validationErrorKey]) invalidCount--;
  16134. if (!invalidCount) {
  16135. toggleValidCss(true);
  16136. this.$valid = true;
  16137. this.$invalid = false;
  16138. }
  16139. } else {
  16140. toggleValidCss(false);
  16141. this.$invalid = true;
  16142. this.$valid = false;
  16143. invalidCount++;
  16144. }
  16145. $error[validationErrorKey] = !isValid;
  16146. toggleValidCss(isValid, validationErrorKey);
  16147. parentForm.$setValidity(validationErrorKey, isValid, this);
  16148. };
  16149. /**
  16150. * @ngdoc method
  16151. * @name ngModel.NgModelController#$setPristine
  16152. *
  16153. * @description
  16154. * Sets the control to its pristine state.
  16155. *
  16156. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  16157. * state (ng-pristine class).
  16158. */
  16159. this.$setPristine = function () {
  16160. this.$dirty = false;
  16161. this.$pristine = true;
  16162. $animate.removeClass($element, DIRTY_CLASS);
  16163. $animate.addClass($element, PRISTINE_CLASS);
  16164. };
  16165. /**
  16166. * @ngdoc method
  16167. * @name ngModel.NgModelController#$setViewValue
  16168. *
  16169. * @description
  16170. * Update the view value.
  16171. *
  16172. * This method should be called when the view value changes, typically from within a DOM event handler.
  16173. * For example {@link ng.directive:input input} and
  16174. * {@link ng.directive:select select} directives call it.
  16175. *
  16176. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  16177. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  16178. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  16179. *
  16180. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  16181. *
  16182. * Note that calling this function does not trigger a `$digest`.
  16183. *
  16184. * @param {string} value Value from the view.
  16185. */
  16186. this.$setViewValue = function(value) {
  16187. this.$viewValue = value;
  16188. // change to dirty
  16189. if (this.$pristine) {
  16190. this.$dirty = true;
  16191. this.$pristine = false;
  16192. $animate.removeClass($element, PRISTINE_CLASS);
  16193. $animate.addClass($element, DIRTY_CLASS);
  16194. parentForm.$setDirty();
  16195. }
  16196. forEach(this.$parsers, function(fn) {
  16197. value = fn(value);
  16198. });
  16199. if (this.$modelValue !== value) {
  16200. this.$modelValue = value;
  16201. ngModelSet($scope, value);
  16202. forEach(this.$viewChangeListeners, function(listener) {
  16203. try {
  16204. listener();
  16205. } catch(e) {
  16206. $exceptionHandler(e);
  16207. }
  16208. });
  16209. }
  16210. };
  16211. // model -> value
  16212. var ctrl = this;
  16213. $scope.$watch(function ngModelWatch() {
  16214. var value = ngModelGet($scope);
  16215. // if scope model value and ngModel value are out of sync
  16216. if (ctrl.$modelValue !== value) {
  16217. var formatters = ctrl.$formatters,
  16218. idx = formatters.length;
  16219. ctrl.$modelValue = value;
  16220. while(idx--) {
  16221. value = formatters[idx](value);
  16222. }
  16223. if (ctrl.$viewValue !== value) {
  16224. ctrl.$viewValue = value;
  16225. ctrl.$render();
  16226. }
  16227. }
  16228. return value;
  16229. });
  16230. }];
  16231. /**
  16232. * @ngdoc directive
  16233. * @name ngModel
  16234. *
  16235. * @element input
  16236. *
  16237. * @description
  16238. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  16239. * property on the scope using {@link ngModel.NgModelController NgModelController},
  16240. * which is created and exposed by this directive.
  16241. *
  16242. * `ngModel` is responsible for:
  16243. *
  16244. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  16245. * require.
  16246. * - Providing validation behavior (i.e. required, number, email, url).
  16247. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  16248. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  16249. * - Registering the control with its parent {@link ng.directive:form form}.
  16250. *
  16251. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  16252. * current scope. If the property doesn't already exist on this scope, it will be created
  16253. * implicitly and added to the scope.
  16254. *
  16255. * For best practices on using `ngModel`, see:
  16256. *
  16257. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  16258. *
  16259. * For basic examples, how to use `ngModel`, see:
  16260. *
  16261. * - {@link ng.directive:input input}
  16262. * - {@link input[text] text}
  16263. * - {@link input[checkbox] checkbox}
  16264. * - {@link input[radio] radio}
  16265. * - {@link input[number] number}
  16266. * - {@link input[email] email}
  16267. * - {@link input[url] url}
  16268. * - {@link ng.directive:select select}
  16269. * - {@link ng.directive:textarea textarea}
  16270. *
  16271. * # CSS classes
  16272. * The following CSS classes are added and removed on the associated input/select/textarea element
  16273. * depending on the validity of the model.
  16274. *
  16275. * - `ng-valid` is set if the model is valid.
  16276. * - `ng-invalid` is set if the model is invalid.
  16277. * - `ng-pristine` is set if the model is pristine.
  16278. * - `ng-dirty` is set if the model is dirty.
  16279. *
  16280. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16281. *
  16282. * ## Animation Hooks
  16283. *
  16284. * Animations within models are triggered when any of the associated CSS classes are added and removed
  16285. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  16286. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  16287. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  16288. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  16289. *
  16290. * The following example shows a simple way to utilize CSS transitions to style an input element
  16291. * that has been rendered as invalid after it has been validated:
  16292. *
  16293. * <pre>
  16294. * //be sure to include ngAnimate as a module to hook into more
  16295. * //advanced animations
  16296. * .my-input {
  16297. * transition:0.5s linear all;
  16298. * background: white;
  16299. * }
  16300. * .my-input.ng-invalid {
  16301. * background: red;
  16302. * color:white;
  16303. * }
  16304. * </pre>
  16305. *
  16306. * @example
  16307. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  16308. <file name="index.html">
  16309. <script>
  16310. angular.module('inputExample', [])
  16311. .controller('ExampleController', ['$scope', function($scope) {
  16312. $scope.val = '1';
  16313. }]);
  16314. </script>
  16315. <style>
  16316. .my-input {
  16317. -webkit-transition:all linear 0.5s;
  16318. transition:all linear 0.5s;
  16319. background: transparent;
  16320. }
  16321. .my-input.ng-invalid {
  16322. color:white;
  16323. background: red;
  16324. }
  16325. </style>
  16326. Update input to see transitions when valid/invalid.
  16327. Integer is a valid value.
  16328. <form name="testForm" ng-controller="ExampleController">
  16329. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  16330. </form>
  16331. </file>
  16332. * </example>
  16333. */
  16334. var ngModelDirective = function() {
  16335. return {
  16336. require: ['ngModel', '^?form'],
  16337. controller: NgModelController,
  16338. link: function(scope, element, attr, ctrls) {
  16339. // notify others, especially parent forms
  16340. var modelCtrl = ctrls[0],
  16341. formCtrl = ctrls[1] || nullFormCtrl;
  16342. formCtrl.$addControl(modelCtrl);
  16343. scope.$on('$destroy', function() {
  16344. formCtrl.$removeControl(modelCtrl);
  16345. });
  16346. }
  16347. };
  16348. };
  16349. /**
  16350. * @ngdoc directive
  16351. * @name ngChange
  16352. *
  16353. * @description
  16354. * Evaluate the given expression when the user changes the input.
  16355. * The expression is evaluated immediately, unlike the JavaScript onchange event
  16356. * which only triggers at the end of a change (usually, when the user leaves the
  16357. * form element or presses the return key).
  16358. * The expression is not evaluated when the value change is coming from the model.
  16359. *
  16360. * Note, this directive requires `ngModel` to be present.
  16361. *
  16362. * @element input
  16363. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  16364. * in input value.
  16365. *
  16366. * @example
  16367. * <example name="ngChange-directive" module="changeExample">
  16368. * <file name="index.html">
  16369. * <script>
  16370. * angular.module('changeExample', [])
  16371. * .controller('ExampleController', ['$scope', function($scope) {
  16372. * $scope.counter = 0;
  16373. * $scope.change = function() {
  16374. * $scope.counter++;
  16375. * };
  16376. * }]);
  16377. * </script>
  16378. * <div ng-controller="ExampleController">
  16379. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  16380. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  16381. * <label for="ng-change-example2">Confirmed</label><br />
  16382. * <tt>debug = {{confirmed}}</tt><br/>
  16383. * <tt>counter = {{counter}}</tt><br/>
  16384. * </div>
  16385. * </file>
  16386. * <file name="protractor.js" type="protractor">
  16387. * var counter = element(by.binding('counter'));
  16388. * var debug = element(by.binding('confirmed'));
  16389. *
  16390. * it('should evaluate the expression if changing from view', function() {
  16391. * expect(counter.getText()).toContain('0');
  16392. *
  16393. * element(by.id('ng-change-example1')).click();
  16394. *
  16395. * expect(counter.getText()).toContain('1');
  16396. * expect(debug.getText()).toContain('true');
  16397. * });
  16398. *
  16399. * it('should not evaluate the expression if changing from model', function() {
  16400. * element(by.id('ng-change-example2')).click();
  16401. * expect(counter.getText()).toContain('0');
  16402. * expect(debug.getText()).toContain('true');
  16403. * });
  16404. * </file>
  16405. * </example>
  16406. */
  16407. var ngChangeDirective = valueFn({
  16408. require: 'ngModel',
  16409. link: function(scope, element, attr, ctrl) {
  16410. ctrl.$viewChangeListeners.push(function() {
  16411. scope.$eval(attr.ngChange);
  16412. });
  16413. }
  16414. });
  16415. var requiredDirective = function() {
  16416. return {
  16417. require: '?ngModel',
  16418. link: function(scope, elm, attr, ctrl) {
  16419. if (!ctrl) return;
  16420. attr.required = true; // force truthy in case we are on non input element
  16421. var validator = function(value) {
  16422. if (attr.required && ctrl.$isEmpty(value)) {
  16423. ctrl.$setValidity('required', false);
  16424. return;
  16425. } else {
  16426. ctrl.$setValidity('required', true);
  16427. return value;
  16428. }
  16429. };
  16430. ctrl.$formatters.push(validator);
  16431. ctrl.$parsers.unshift(validator);
  16432. attr.$observe('required', function() {
  16433. validator(ctrl.$viewValue);
  16434. });
  16435. }
  16436. };
  16437. };
  16438. /**
  16439. * @ngdoc directive
  16440. * @name ngList
  16441. *
  16442. * @description
  16443. * Text input that converts between a delimited string and an array of strings. The delimiter
  16444. * can be a fixed string (by default a comma) or a regular expression.
  16445. *
  16446. * @element input
  16447. * @param {string=} ngList optional delimiter that should be used to split the value. If
  16448. * specified in form `/something/` then the value will be converted into a regular expression.
  16449. *
  16450. * @example
  16451. <example name="ngList-directive" module="listExample">
  16452. <file name="index.html">
  16453. <script>
  16454. angular.module('listExample', [])
  16455. .controller('ExampleController', ['$scope', function($scope) {
  16456. $scope.names = ['igor', 'misko', 'vojta'];
  16457. }]);
  16458. </script>
  16459. <form name="myForm" ng-controller="ExampleController">
  16460. List: <input name="namesInput" ng-model="names" ng-list required>
  16461. <span class="error" ng-show="myForm.namesInput.$error.required">
  16462. Required!</span>
  16463. <br>
  16464. <tt>names = {{names}}</tt><br/>
  16465. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  16466. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  16467. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16468. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16469. </form>
  16470. </file>
  16471. <file name="protractor.js" type="protractor">
  16472. var listInput = element(by.model('names'));
  16473. var names = element(by.binding('{{names}}'));
  16474. var valid = element(by.binding('myForm.namesInput.$valid'));
  16475. var error = element(by.css('span.error'));
  16476. it('should initialize to model', function() {
  16477. expect(names.getText()).toContain('["igor","misko","vojta"]');
  16478. expect(valid.getText()).toContain('true');
  16479. expect(error.getCssValue('display')).toBe('none');
  16480. });
  16481. it('should be invalid if empty', function() {
  16482. listInput.clear();
  16483. listInput.sendKeys('');
  16484. expect(names.getText()).toContain('');
  16485. expect(valid.getText()).toContain('false');
  16486. expect(error.getCssValue('display')).not.toBe('none'); });
  16487. </file>
  16488. </example>
  16489. */
  16490. var ngListDirective = function() {
  16491. return {
  16492. require: 'ngModel',
  16493. link: function(scope, element, attr, ctrl) {
  16494. var match = /\/(.*)\//.exec(attr.ngList),
  16495. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  16496. var parse = function(viewValue) {
  16497. // If the viewValue is invalid (say required but empty) it will be `undefined`
  16498. if (isUndefined(viewValue)) return;
  16499. var list = [];
  16500. if (viewValue) {
  16501. forEach(viewValue.split(separator), function(value) {
  16502. if (value) list.push(trim(value));
  16503. });
  16504. }
  16505. return list;
  16506. };
  16507. ctrl.$parsers.push(parse);
  16508. ctrl.$formatters.push(function(value) {
  16509. if (isArray(value)) {
  16510. return value.join(', ');
  16511. }
  16512. return undefined;
  16513. });
  16514. // Override the standard $isEmpty because an empty array means the input is empty.
  16515. ctrl.$isEmpty = function(value) {
  16516. return !value || !value.length;
  16517. };
  16518. }
  16519. };
  16520. };
  16521. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  16522. /**
  16523. * @ngdoc directive
  16524. * @name ngValue
  16525. *
  16526. * @description
  16527. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16528. * that when the element is selected, the `ngModel` of that element is set to the
  16529. * bound value.
  16530. *
  16531. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16532. * shown below.
  16533. *
  16534. * @element input
  16535. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16536. * of the `input` element
  16537. *
  16538. * @example
  16539. <example name="ngValue-directive" module="valueExample">
  16540. <file name="index.html">
  16541. <script>
  16542. angular.module('valueExample', [])
  16543. .controller('ExampleController', ['$scope', function($scope) {
  16544. $scope.names = ['pizza', 'unicorns', 'robots'];
  16545. $scope.my = { favorite: 'unicorns' };
  16546. }]);
  16547. </script>
  16548. <form ng-controller="ExampleController">
  16549. <h2>Which is your favorite?</h2>
  16550. <label ng-repeat="name in names" for="{{name}}">
  16551. {{name}}
  16552. <input type="radio"
  16553. ng-model="my.favorite"
  16554. ng-value="name"
  16555. id="{{name}}"
  16556. name="favorite">
  16557. </label>
  16558. <div>You chose {{my.favorite}}</div>
  16559. </form>
  16560. </file>
  16561. <file name="protractor.js" type="protractor">
  16562. var favorite = element(by.binding('my.favorite'));
  16563. it('should initialize to model', function() {
  16564. expect(favorite.getText()).toContain('unicorns');
  16565. });
  16566. it('should bind the values to the inputs', function() {
  16567. element.all(by.model('my.favorite')).get(0).click();
  16568. expect(favorite.getText()).toContain('pizza');
  16569. });
  16570. </file>
  16571. </example>
  16572. */
  16573. var ngValueDirective = function() {
  16574. return {
  16575. priority: 100,
  16576. compile: function(tpl, tplAttr) {
  16577. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16578. return function ngValueConstantLink(scope, elm, attr) {
  16579. attr.$set('value', scope.$eval(attr.ngValue));
  16580. };
  16581. } else {
  16582. return function ngValueLink(scope, elm, attr) {
  16583. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16584. attr.$set('value', value);
  16585. });
  16586. };
  16587. }
  16588. }
  16589. };
  16590. };
  16591. /**
  16592. * @ngdoc directive
  16593. * @name ngBind
  16594. * @restrict AC
  16595. *
  16596. * @description
  16597. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16598. * with the value of a given expression, and to update the text content when the value of that
  16599. * expression changes.
  16600. *
  16601. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16602. * `{{ expression }}` which is similar but less verbose.
  16603. *
  16604. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  16605. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16606. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16607. *
  16608. * An alternative solution to this problem would be using the
  16609. * {@link ng.directive:ngCloak ngCloak} directive.
  16610. *
  16611. *
  16612. * @element ANY
  16613. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16614. *
  16615. * @example
  16616. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16617. <example module="bindExample">
  16618. <file name="index.html">
  16619. <script>
  16620. angular.module('bindExample', [])
  16621. .controller('ExampleController', ['$scope', function($scope) {
  16622. $scope.name = 'Whirled';
  16623. }]);
  16624. </script>
  16625. <div ng-controller="ExampleController">
  16626. Enter name: <input type="text" ng-model="name"><br>
  16627. Hello <span ng-bind="name"></span>!
  16628. </div>
  16629. </file>
  16630. <file name="protractor.js" type="protractor">
  16631. it('should check ng-bind', function() {
  16632. var nameInput = element(by.model('name'));
  16633. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16634. nameInput.clear();
  16635. nameInput.sendKeys('world');
  16636. expect(element(by.binding('name')).getText()).toBe('world');
  16637. });
  16638. </file>
  16639. </example>
  16640. */
  16641. var ngBindDirective = ngDirective({
  16642. compile: function(templateElement) {
  16643. templateElement.addClass('ng-binding');
  16644. return function (scope, element, attr) {
  16645. element.data('$binding', attr.ngBind);
  16646. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16647. // We are purposefully using == here rather than === because we want to
  16648. // catch when value is "null or undefined"
  16649. // jshint -W041
  16650. element.text(value == undefined ? '' : value);
  16651. });
  16652. };
  16653. }
  16654. });
  16655. /**
  16656. * @ngdoc directive
  16657. * @name ngBindTemplate
  16658. *
  16659. * @description
  16660. * The `ngBindTemplate` directive specifies that the element
  16661. * text content should be replaced with the interpolation of the template
  16662. * in the `ngBindTemplate` attribute.
  16663. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16664. * expressions. This directive is needed since some HTML elements
  16665. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16666. *
  16667. * @element ANY
  16668. * @param {string} ngBindTemplate template of form
  16669. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16670. *
  16671. * @example
  16672. * Try it here: enter text in text box and watch the greeting change.
  16673. <example module="bindExample">
  16674. <file name="index.html">
  16675. <script>
  16676. angular.module('bindExample', [])
  16677. .controller('ExampleController', ['$scope', function ($scope) {
  16678. $scope.salutation = 'Hello';
  16679. $scope.name = 'World';
  16680. }]);
  16681. </script>
  16682. <div ng-controller="ExampleController">
  16683. Salutation: <input type="text" ng-model="salutation"><br>
  16684. Name: <input type="text" ng-model="name"><br>
  16685. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16686. </div>
  16687. </file>
  16688. <file name="protractor.js" type="protractor">
  16689. it('should check ng-bind', function() {
  16690. var salutationElem = element(by.binding('salutation'));
  16691. var salutationInput = element(by.model('salutation'));
  16692. var nameInput = element(by.model('name'));
  16693. expect(salutationElem.getText()).toBe('Hello World!');
  16694. salutationInput.clear();
  16695. salutationInput.sendKeys('Greetings');
  16696. nameInput.clear();
  16697. nameInput.sendKeys('user');
  16698. expect(salutationElem.getText()).toBe('Greetings user!');
  16699. });
  16700. </file>
  16701. </example>
  16702. */
  16703. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16704. return function(scope, element, attr) {
  16705. // TODO: move this to scenario runner
  16706. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16707. element.addClass('ng-binding').data('$binding', interpolateFn);
  16708. attr.$observe('ngBindTemplate', function(value) {
  16709. element.text(value);
  16710. });
  16711. };
  16712. }];
  16713. /**
  16714. * @ngdoc directive
  16715. * @name ngBindHtml
  16716. *
  16717. * @description
  16718. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16719. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16720. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16721. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16722. * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
  16723. * include "angular-sanitize.js" in your application.
  16724. *
  16725. * You may also bypass sanitization for values you know are safe. To do so, bind to
  16726. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16727. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16728. *
  16729. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16730. * will have an exception (instead of an exploit.)
  16731. *
  16732. * @element ANY
  16733. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16734. *
  16735. * @example
  16736. <example module="bindHtmlExample" deps="angular-sanitize.js">
  16737. <file name="index.html">
  16738. <div ng-controller="ExampleController">
  16739. <p ng-bind-html="myHTML"></p>
  16740. </div>
  16741. </file>
  16742. <file name="script.js">
  16743. angular.module('bindHtmlExample', ['ngSanitize'])
  16744. .controller('ExampleController', ['$scope', function($scope) {
  16745. $scope.myHTML =
  16746. 'I am an <code>HTML</code>string with ' +
  16747. '<a href="#">links!</a> and other <em>stuff</em>';
  16748. }]);
  16749. </file>
  16750. <file name="protractor.js" type="protractor">
  16751. it('should check ng-bind-html', function() {
  16752. expect(element(by.binding('myHTML')).getText()).toBe(
  16753. 'I am an HTMLstring with links! and other stuff');
  16754. });
  16755. </file>
  16756. </example>
  16757. */
  16758. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16759. return {
  16760. compile: function (tElement) {
  16761. tElement.addClass('ng-binding');
  16762. return function (scope, element, attr) {
  16763. element.data('$binding', attr.ngBindHtml);
  16764. var parsed = $parse(attr.ngBindHtml);
  16765. function getStringValue() {
  16766. return (parsed(scope) || '').toString();
  16767. }
  16768. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16769. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16770. });
  16771. };
  16772. }
  16773. };
  16774. }];
  16775. function classDirective(name, selector) {
  16776. name = 'ngClass' + name;
  16777. return ['$animate', function($animate) {
  16778. return {
  16779. restrict: 'AC',
  16780. link: function(scope, element, attr) {
  16781. var oldVal;
  16782. scope.$watch(attr[name], ngClassWatchAction, true);
  16783. attr.$observe('class', function(value) {
  16784. ngClassWatchAction(scope.$eval(attr[name]));
  16785. });
  16786. if (name !== 'ngClass') {
  16787. scope.$watch('$index', function($index, old$index) {
  16788. // jshint bitwise: false
  16789. var mod = $index & 1;
  16790. if (mod !== (old$index & 1)) {
  16791. var classes = arrayClasses(scope.$eval(attr[name]));
  16792. mod === selector ?
  16793. addClasses(classes) :
  16794. removeClasses(classes);
  16795. }
  16796. });
  16797. }
  16798. function addClasses(classes) {
  16799. var newClasses = digestClassCounts(classes, 1);
  16800. attr.$addClass(newClasses);
  16801. }
  16802. function removeClasses(classes) {
  16803. var newClasses = digestClassCounts(classes, -1);
  16804. attr.$removeClass(newClasses);
  16805. }
  16806. function digestClassCounts (classes, count) {
  16807. var classCounts = element.data('$classCounts') || {};
  16808. var classesToUpdate = [];
  16809. forEach(classes, function (className) {
  16810. if (count > 0 || classCounts[className]) {
  16811. classCounts[className] = (classCounts[className] || 0) + count;
  16812. if (classCounts[className] === +(count > 0)) {
  16813. classesToUpdate.push(className);
  16814. }
  16815. }
  16816. });
  16817. element.data('$classCounts', classCounts);
  16818. return classesToUpdate.join(' ');
  16819. }
  16820. function updateClasses (oldClasses, newClasses) {
  16821. var toAdd = arrayDifference(newClasses, oldClasses);
  16822. var toRemove = arrayDifference(oldClasses, newClasses);
  16823. toRemove = digestClassCounts(toRemove, -1);
  16824. toAdd = digestClassCounts(toAdd, 1);
  16825. if (toAdd.length === 0) {
  16826. $animate.removeClass(element, toRemove);
  16827. } else if (toRemove.length === 0) {
  16828. $animate.addClass(element, toAdd);
  16829. } else {
  16830. $animate.setClass(element, toAdd, toRemove);
  16831. }
  16832. }
  16833. function ngClassWatchAction(newVal) {
  16834. if (selector === true || scope.$index % 2 === selector) {
  16835. var newClasses = arrayClasses(newVal || []);
  16836. if (!oldVal) {
  16837. addClasses(newClasses);
  16838. } else if (!equals(newVal,oldVal)) {
  16839. var oldClasses = arrayClasses(oldVal);
  16840. updateClasses(oldClasses, newClasses);
  16841. }
  16842. }
  16843. oldVal = shallowCopy(newVal);
  16844. }
  16845. }
  16846. };
  16847. function arrayDifference(tokens1, tokens2) {
  16848. var values = [];
  16849. outer:
  16850. for(var i = 0; i < tokens1.length; i++) {
  16851. var token = tokens1[i];
  16852. for(var j = 0; j < tokens2.length; j++) {
  16853. if(token == tokens2[j]) continue outer;
  16854. }
  16855. values.push(token);
  16856. }
  16857. return values;
  16858. }
  16859. function arrayClasses (classVal) {
  16860. if (isArray(classVal)) {
  16861. return classVal;
  16862. } else if (isString(classVal)) {
  16863. return classVal.split(' ');
  16864. } else if (isObject(classVal)) {
  16865. var classes = [], i = 0;
  16866. forEach(classVal, function(v, k) {
  16867. if (v) {
  16868. classes = classes.concat(k.split(' '));
  16869. }
  16870. });
  16871. return classes;
  16872. }
  16873. return classVal;
  16874. }
  16875. }];
  16876. }
  16877. /**
  16878. * @ngdoc directive
  16879. * @name ngClass
  16880. * @restrict AC
  16881. *
  16882. * @description
  16883. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16884. * an expression that represents all classes to be added.
  16885. *
  16886. * The directive operates in three different ways, depending on which of three types the expression
  16887. * evaluates to:
  16888. *
  16889. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16890. * names.
  16891. *
  16892. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16893. * one or more space-delimited class names.
  16894. *
  16895. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16896. * object with a truthy value the corresponding key is used as a class name.
  16897. *
  16898. * The directive won't add duplicate classes if a particular class was already set.
  16899. *
  16900. * When the expression changes, the previously added classes are removed and only then the
  16901. * new classes are added.
  16902. *
  16903. * @animations
  16904. * add - happens just before the class is applied to the element
  16905. * remove - happens just before the class is removed from the element
  16906. *
  16907. * @element ANY
  16908. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16909. * of the evaluation can be a string representing space delimited class
  16910. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16911. * names of the properties whose values are truthy will be added as css classes to the
  16912. * element.
  16913. *
  16914. * @example Example that demonstrates basic bindings via ngClass directive.
  16915. <example>
  16916. <file name="index.html">
  16917. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16918. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16919. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16920. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16921. <hr>
  16922. <p ng-class="style">Using String Syntax</p>
  16923. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16924. <hr>
  16925. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16926. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16927. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16928. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16929. </file>
  16930. <file name="style.css">
  16931. .strike {
  16932. text-decoration: line-through;
  16933. }
  16934. .bold {
  16935. font-weight: bold;
  16936. }
  16937. .red {
  16938. color: red;
  16939. }
  16940. </file>
  16941. <file name="protractor.js" type="protractor">
  16942. var ps = element.all(by.css('p'));
  16943. it('should let you toggle the class', function() {
  16944. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16945. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16946. element(by.model('important')).click();
  16947. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16948. element(by.model('error')).click();
  16949. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16950. });
  16951. it('should let you toggle string example', function() {
  16952. expect(ps.get(1).getAttribute('class')).toBe('');
  16953. element(by.model('style')).clear();
  16954. element(by.model('style')).sendKeys('red');
  16955. expect(ps.get(1).getAttribute('class')).toBe('red');
  16956. });
  16957. it('array example should have 3 classes', function() {
  16958. expect(ps.last().getAttribute('class')).toBe('');
  16959. element(by.model('style1')).sendKeys('bold');
  16960. element(by.model('style2')).sendKeys('strike');
  16961. element(by.model('style3')).sendKeys('red');
  16962. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16963. });
  16964. </file>
  16965. </example>
  16966. ## Animations
  16967. The example below demonstrates how to perform animations using ngClass.
  16968. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  16969. <file name="index.html">
  16970. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  16971. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  16972. <br>
  16973. <span class="base-class" ng-class="myVar">Sample Text</span>
  16974. </file>
  16975. <file name="style.css">
  16976. .base-class {
  16977. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16978. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16979. }
  16980. .base-class.my-class {
  16981. color: red;
  16982. font-size:3em;
  16983. }
  16984. </file>
  16985. <file name="protractor.js" type="protractor">
  16986. it('should check ng-class', function() {
  16987. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16988. toMatch(/my-class/);
  16989. element(by.id('setbtn')).click();
  16990. expect(element(by.css('.base-class')).getAttribute('class')).
  16991. toMatch(/my-class/);
  16992. element(by.id('clearbtn')).click();
  16993. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16994. toMatch(/my-class/);
  16995. });
  16996. </file>
  16997. </example>
  16998. ## ngClass and pre-existing CSS3 Transitions/Animations
  16999. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  17000. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  17001. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  17002. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  17003. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  17004. */
  17005. var ngClassDirective = classDirective('', true);
  17006. /**
  17007. * @ngdoc directive
  17008. * @name ngClassOdd
  17009. * @restrict AC
  17010. *
  17011. * @description
  17012. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  17013. * {@link ng.directive:ngClass ngClass}, except they work in
  17014. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  17015. *
  17016. * This directive can be applied only within the scope of an
  17017. * {@link ng.directive:ngRepeat ngRepeat}.
  17018. *
  17019. * @element ANY
  17020. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  17021. * of the evaluation can be a string representing space delimited class names or an array.
  17022. *
  17023. * @example
  17024. <example>
  17025. <file name="index.html">
  17026. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17027. <li ng-repeat="name in names">
  17028. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17029. {{name}}
  17030. </span>
  17031. </li>
  17032. </ol>
  17033. </file>
  17034. <file name="style.css">
  17035. .odd {
  17036. color: red;
  17037. }
  17038. .even {
  17039. color: blue;
  17040. }
  17041. </file>
  17042. <file name="protractor.js" type="protractor">
  17043. it('should check ng-class-odd and ng-class-even', function() {
  17044. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17045. toMatch(/odd/);
  17046. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17047. toMatch(/even/);
  17048. });
  17049. </file>
  17050. </example>
  17051. */
  17052. var ngClassOddDirective = classDirective('Odd', 0);
  17053. /**
  17054. * @ngdoc directive
  17055. * @name ngClassEven
  17056. * @restrict AC
  17057. *
  17058. * @description
  17059. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  17060. * {@link ng.directive:ngClass ngClass}, except they work in
  17061. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  17062. *
  17063. * This directive can be applied only within the scope of an
  17064. * {@link ng.directive:ngRepeat ngRepeat}.
  17065. *
  17066. * @element ANY
  17067. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  17068. * result of the evaluation can be a string representing space delimited class names or an array.
  17069. *
  17070. * @example
  17071. <example>
  17072. <file name="index.html">
  17073. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17074. <li ng-repeat="name in names">
  17075. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17076. {{name}} &nbsp; &nbsp; &nbsp;
  17077. </span>
  17078. </li>
  17079. </ol>
  17080. </file>
  17081. <file name="style.css">
  17082. .odd {
  17083. color: red;
  17084. }
  17085. .even {
  17086. color: blue;
  17087. }
  17088. </file>
  17089. <file name="protractor.js" type="protractor">
  17090. it('should check ng-class-odd and ng-class-even', function() {
  17091. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17092. toMatch(/odd/);
  17093. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17094. toMatch(/even/);
  17095. });
  17096. </file>
  17097. </example>
  17098. */
  17099. var ngClassEvenDirective = classDirective('Even', 1);
  17100. /**
  17101. * @ngdoc directive
  17102. * @name ngCloak
  17103. * @restrict AC
  17104. *
  17105. * @description
  17106. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  17107. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  17108. * directive to avoid the undesirable flicker effect caused by the html template display.
  17109. *
  17110. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  17111. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  17112. * of the browser view.
  17113. *
  17114. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  17115. * `angular.min.js`.
  17116. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17117. *
  17118. * ```css
  17119. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  17120. * display: none !important;
  17121. * }
  17122. * ```
  17123. *
  17124. * When this css rule is loaded by the browser, all html elements (including their children) that
  17125. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  17126. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  17127. * the compiled element visible.
  17128. *
  17129. * For the best result, the `angular.js` script must be loaded in the head section of the html
  17130. * document; alternatively, the css rule above must be included in the external stylesheet of the
  17131. * application.
  17132. *
  17133. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  17134. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  17135. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  17136. *
  17137. * @element ANY
  17138. *
  17139. * @example
  17140. <example>
  17141. <file name="index.html">
  17142. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  17143. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  17144. </file>
  17145. <file name="protractor.js" type="protractor">
  17146. it('should remove the template directive and css class', function() {
  17147. expect($('#template1').getAttribute('ng-cloak')).
  17148. toBeNull();
  17149. expect($('#template2').getAttribute('ng-cloak')).
  17150. toBeNull();
  17151. });
  17152. </file>
  17153. </example>
  17154. *
  17155. */
  17156. var ngCloakDirective = ngDirective({
  17157. compile: function(element, attr) {
  17158. attr.$set('ngCloak', undefined);
  17159. element.removeClass('ng-cloak');
  17160. }
  17161. });
  17162. /**
  17163. * @ngdoc directive
  17164. * @name ngController
  17165. *
  17166. * @description
  17167. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  17168. * supports the principles behind the Model-View-Controller design pattern.
  17169. *
  17170. * MVC components in angular:
  17171. *
  17172. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  17173. * are accessed through bindings.
  17174. * * View — The template (HTML with data bindings) that is rendered into the View.
  17175. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  17176. * logic behind the application to decorate the scope with functions and values
  17177. *
  17178. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  17179. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  17180. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  17181. * and executed twice.
  17182. *
  17183. * @element ANY
  17184. * @scope
  17185. * @priority 500
  17186. * @param {expression} ngController Name of a globally accessible constructor function or an
  17187. * {@link guide/expression expression} that on the current scope evaluates to a
  17188. * constructor function. The controller instance can be published into a scope property
  17189. * by specifying `as propertyName`.
  17190. *
  17191. * @example
  17192. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  17193. * greeting are methods declared on the controller (see source tab). These methods can
  17194. * easily be called from the angular markup. Any changes to the data are automatically reflected
  17195. * in the View without the need for a manual update.
  17196. *
  17197. * Two different declaration styles are included below:
  17198. *
  17199. * * one binds methods and properties directly onto the controller using `this`:
  17200. * `ng-controller="SettingsController1 as settings"`
  17201. * * one injects `$scope` into the controller:
  17202. * `ng-controller="SettingsController2"`
  17203. *
  17204. * The second option is more common in the Angular community, and is generally used in boilerplates
  17205. * and in this guide. However, there are advantages to binding properties directly to the controller
  17206. * and avoiding scope.
  17207. *
  17208. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  17209. * multiple controllers apply to an element.
  17210. * * If you are writing your controllers as classes you have easier access to the properties and
  17211. * methods, which will appear on the scope, from inside the controller code.
  17212. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  17213. * inheritance masking primitives.
  17214. *
  17215. * This example demonstrates the `controller as` syntax.
  17216. *
  17217. * <example name="ngControllerAs" module="controllerAsExample">
  17218. * <file name="index.html">
  17219. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  17220. * Name: <input type="text" ng-model="settings.name"/>
  17221. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  17222. * Contact:
  17223. * <ul>
  17224. * <li ng-repeat="contact in settings.contacts">
  17225. * <select ng-model="contact.type">
  17226. * <option>phone</option>
  17227. * <option>email</option>
  17228. * </select>
  17229. * <input type="text" ng-model="contact.value"/>
  17230. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  17231. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  17232. * </li>
  17233. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  17234. * </ul>
  17235. * </div>
  17236. * </file>
  17237. * <file name="app.js">
  17238. * angular.module('controllerAsExample', [])
  17239. * .controller('SettingsController1', SettingsController1);
  17240. *
  17241. * function SettingsController1() {
  17242. * this.name = "John Smith";
  17243. * this.contacts = [
  17244. * {type: 'phone', value: '408 555 1212'},
  17245. * {type: 'email', value: 'john.smith@example.org'} ];
  17246. * }
  17247. *
  17248. * SettingsController1.prototype.greet = function() {
  17249. * alert(this.name);
  17250. * };
  17251. *
  17252. * SettingsController1.prototype.addContact = function() {
  17253. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  17254. * };
  17255. *
  17256. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  17257. * var index = this.contacts.indexOf(contactToRemove);
  17258. * this.contacts.splice(index, 1);
  17259. * };
  17260. *
  17261. * SettingsController1.prototype.clearContact = function(contact) {
  17262. * contact.type = 'phone';
  17263. * contact.value = '';
  17264. * };
  17265. * </file>
  17266. * <file name="protractor.js" type="protractor">
  17267. * it('should check controller as', function() {
  17268. * var container = element(by.id('ctrl-as-exmpl'));
  17269. * expect(container.element(by.model('settings.name'))
  17270. * .getAttribute('value')).toBe('John Smith');
  17271. *
  17272. * var firstRepeat =
  17273. * container.element(by.repeater('contact in settings.contacts').row(0));
  17274. * var secondRepeat =
  17275. * container.element(by.repeater('contact in settings.contacts').row(1));
  17276. *
  17277. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17278. * .toBe('408 555 1212');
  17279. *
  17280. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17281. * .toBe('john.smith@example.org');
  17282. *
  17283. * firstRepeat.element(by.linkText('clear')).click();
  17284. *
  17285. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17286. * .toBe('');
  17287. *
  17288. * container.element(by.linkText('add')).click();
  17289. *
  17290. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  17291. * .element(by.model('contact.value'))
  17292. * .getAttribute('value'))
  17293. * .toBe('yourname@example.org');
  17294. * });
  17295. * </file>
  17296. * </example>
  17297. *
  17298. * This example demonstrates the "attach to `$scope`" style of controller.
  17299. *
  17300. * <example name="ngController" module="controllerExample">
  17301. * <file name="index.html">
  17302. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  17303. * Name: <input type="text" ng-model="name"/>
  17304. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  17305. * Contact:
  17306. * <ul>
  17307. * <li ng-repeat="contact in contacts">
  17308. * <select ng-model="contact.type">
  17309. * <option>phone</option>
  17310. * <option>email</option>
  17311. * </select>
  17312. * <input type="text" ng-model="contact.value"/>
  17313. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  17314. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  17315. * </li>
  17316. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  17317. * </ul>
  17318. * </div>
  17319. * </file>
  17320. * <file name="app.js">
  17321. * angular.module('controllerExample', [])
  17322. * .controller('SettingsController2', ['$scope', SettingsController2]);
  17323. *
  17324. * function SettingsController2($scope) {
  17325. * $scope.name = "John Smith";
  17326. * $scope.contacts = [
  17327. * {type:'phone', value:'408 555 1212'},
  17328. * {type:'email', value:'john.smith@example.org'} ];
  17329. *
  17330. * $scope.greet = function() {
  17331. * alert($scope.name);
  17332. * };
  17333. *
  17334. * $scope.addContact = function() {
  17335. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  17336. * };
  17337. *
  17338. * $scope.removeContact = function(contactToRemove) {
  17339. * var index = $scope.contacts.indexOf(contactToRemove);
  17340. * $scope.contacts.splice(index, 1);
  17341. * };
  17342. *
  17343. * $scope.clearContact = function(contact) {
  17344. * contact.type = 'phone';
  17345. * contact.value = '';
  17346. * };
  17347. * }
  17348. * </file>
  17349. * <file name="protractor.js" type="protractor">
  17350. * it('should check controller', function() {
  17351. * var container = element(by.id('ctrl-exmpl'));
  17352. *
  17353. * expect(container.element(by.model('name'))
  17354. * .getAttribute('value')).toBe('John Smith');
  17355. *
  17356. * var firstRepeat =
  17357. * container.element(by.repeater('contact in contacts').row(0));
  17358. * var secondRepeat =
  17359. * container.element(by.repeater('contact in contacts').row(1));
  17360. *
  17361. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17362. * .toBe('408 555 1212');
  17363. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17364. * .toBe('john.smith@example.org');
  17365. *
  17366. * firstRepeat.element(by.linkText('clear')).click();
  17367. *
  17368. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17369. * .toBe('');
  17370. *
  17371. * container.element(by.linkText('add')).click();
  17372. *
  17373. * expect(container.element(by.repeater('contact in contacts').row(2))
  17374. * .element(by.model('contact.value'))
  17375. * .getAttribute('value'))
  17376. * .toBe('yourname@example.org');
  17377. * });
  17378. * </file>
  17379. *</example>
  17380. */
  17381. var ngControllerDirective = [function() {
  17382. return {
  17383. scope: true,
  17384. controller: '@',
  17385. priority: 500
  17386. };
  17387. }];
  17388. /**
  17389. * @ngdoc directive
  17390. * @name ngCsp
  17391. *
  17392. * @element html
  17393. * @description
  17394. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  17395. *
  17396. * This is necessary when developing things like Google Chrome Extensions.
  17397. *
  17398. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  17399. * For Angular to be CSP compatible there are only two things that we need to do differently:
  17400. *
  17401. * - don't use `Function` constructor to generate optimized value getters
  17402. * - don't inject custom stylesheet into the document
  17403. *
  17404. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  17405. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  17406. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  17407. * be raised.
  17408. *
  17409. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  17410. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  17411. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  17412. *
  17413. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  17414. * autodetection however triggers a CSP error to be logged in the console:
  17415. *
  17416. * ```
  17417. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  17418. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  17419. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  17420. * ```
  17421. *
  17422. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  17423. * directive on the root element of the application or on the `angular.js` script tag, whichever
  17424. * appears first in the html document.
  17425. *
  17426. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  17427. *
  17428. * @example
  17429. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  17430. ```html
  17431. <!doctype html>
  17432. <html ng-app ng-csp>
  17433. ...
  17434. ...
  17435. </html>
  17436. ```
  17437. */
  17438. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  17439. // bootstrap the system (before $parse is instantiated), for this reason we just have
  17440. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  17441. /**
  17442. * @ngdoc directive
  17443. * @name ngClick
  17444. *
  17445. * @description
  17446. * The ngClick directive allows you to specify custom behavior when
  17447. * an element is clicked.
  17448. *
  17449. * @element ANY
  17450. * @priority 0
  17451. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  17452. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  17453. *
  17454. * @example
  17455. <example>
  17456. <file name="index.html">
  17457. <button ng-click="count = count + 1" ng-init="count=0">
  17458. Increment
  17459. </button>
  17460. <span>
  17461. count: {{count}}
  17462. <span>
  17463. </file>
  17464. <file name="protractor.js" type="protractor">
  17465. it('should check ng-click', function() {
  17466. expect(element(by.binding('count')).getText()).toMatch('0');
  17467. element(by.css('button')).click();
  17468. expect(element(by.binding('count')).getText()).toMatch('1');
  17469. });
  17470. </file>
  17471. </example>
  17472. */
  17473. /*
  17474. * A collection of directives that allows creation of custom event handlers that are defined as
  17475. * angular expressions and are compiled and executed within the current scope.
  17476. */
  17477. var ngEventDirectives = {};
  17478. // For events that might fire synchronously during DOM manipulation
  17479. // we need to execute their event handlers asynchronously using $evalAsync,
  17480. // so that they are not executed in an inconsistent state.
  17481. var forceAsyncEvents = {
  17482. 'blur': true,
  17483. 'focus': true
  17484. };
  17485. forEach(
  17486. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  17487. function(eventName) {
  17488. var directiveName = directiveNormalize('ng-' + eventName);
  17489. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  17490. return {
  17491. compile: function($element, attr) {
  17492. // We expose the powerful $event object on the scope that provides access to the Window,
  17493. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  17494. // checks at the cost of speed since event handler expressions are not executed as
  17495. // frequently as regular change detection.
  17496. var fn = $parse(attr[directiveName], /* expensiveChecks */ true);
  17497. return function ngEventHandler(scope, element) {
  17498. element.on(eventName, function(event) {
  17499. var callback = function() {
  17500. fn(scope, {$event:event});
  17501. };
  17502. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  17503. scope.$evalAsync(callback);
  17504. } else {
  17505. scope.$apply(callback);
  17506. }
  17507. });
  17508. };
  17509. }
  17510. };
  17511. }];
  17512. }
  17513. );
  17514. /**
  17515. * @ngdoc directive
  17516. * @name ngDblclick
  17517. *
  17518. * @description
  17519. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  17520. *
  17521. * @element ANY
  17522. * @priority 0
  17523. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  17524. * a dblclick. (The Event object is available as `$event`)
  17525. *
  17526. * @example
  17527. <example>
  17528. <file name="index.html">
  17529. <button ng-dblclick="count = count + 1" ng-init="count=0">
  17530. Increment (on double click)
  17531. </button>
  17532. count: {{count}}
  17533. </file>
  17534. </example>
  17535. */
  17536. /**
  17537. * @ngdoc directive
  17538. * @name ngMousedown
  17539. *
  17540. * @description
  17541. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  17542. *
  17543. * @element ANY
  17544. * @priority 0
  17545. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  17546. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  17547. *
  17548. * @example
  17549. <example>
  17550. <file name="index.html">
  17551. <button ng-mousedown="count = count + 1" ng-init="count=0">
  17552. Increment (on mouse down)
  17553. </button>
  17554. count: {{count}}
  17555. </file>
  17556. </example>
  17557. */
  17558. /**
  17559. * @ngdoc directive
  17560. * @name ngMouseup
  17561. *
  17562. * @description
  17563. * Specify custom behavior on mouseup event.
  17564. *
  17565. * @element ANY
  17566. * @priority 0
  17567. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  17568. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  17569. *
  17570. * @example
  17571. <example>
  17572. <file name="index.html">
  17573. <button ng-mouseup="count = count + 1" ng-init="count=0">
  17574. Increment (on mouse up)
  17575. </button>
  17576. count: {{count}}
  17577. </file>
  17578. </example>
  17579. */
  17580. /**
  17581. * @ngdoc directive
  17582. * @name ngMouseover
  17583. *
  17584. * @description
  17585. * Specify custom behavior on mouseover event.
  17586. *
  17587. * @element ANY
  17588. * @priority 0
  17589. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  17590. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  17591. *
  17592. * @example
  17593. <example>
  17594. <file name="index.html">
  17595. <button ng-mouseover="count = count + 1" ng-init="count=0">
  17596. Increment (when mouse is over)
  17597. </button>
  17598. count: {{count}}
  17599. </file>
  17600. </example>
  17601. */
  17602. /**
  17603. * @ngdoc directive
  17604. * @name ngMouseenter
  17605. *
  17606. * @description
  17607. * Specify custom behavior on mouseenter event.
  17608. *
  17609. * @element ANY
  17610. * @priority 0
  17611. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  17612. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  17613. *
  17614. * @example
  17615. <example>
  17616. <file name="index.html">
  17617. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  17618. Increment (when mouse enters)
  17619. </button>
  17620. count: {{count}}
  17621. </file>
  17622. </example>
  17623. */
  17624. /**
  17625. * @ngdoc directive
  17626. * @name ngMouseleave
  17627. *
  17628. * @description
  17629. * Specify custom behavior on mouseleave event.
  17630. *
  17631. * @element ANY
  17632. * @priority 0
  17633. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17634. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17635. *
  17636. * @example
  17637. <example>
  17638. <file name="index.html">
  17639. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17640. Increment (when mouse leaves)
  17641. </button>
  17642. count: {{count}}
  17643. </file>
  17644. </example>
  17645. */
  17646. /**
  17647. * @ngdoc directive
  17648. * @name ngMousemove
  17649. *
  17650. * @description
  17651. * Specify custom behavior on mousemove event.
  17652. *
  17653. * @element ANY
  17654. * @priority 0
  17655. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17656. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17657. *
  17658. * @example
  17659. <example>
  17660. <file name="index.html">
  17661. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17662. Increment (when mouse moves)
  17663. </button>
  17664. count: {{count}}
  17665. </file>
  17666. </example>
  17667. */
  17668. /**
  17669. * @ngdoc directive
  17670. * @name ngKeydown
  17671. *
  17672. * @description
  17673. * Specify custom behavior on keydown event.
  17674. *
  17675. * @element ANY
  17676. * @priority 0
  17677. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17678. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17679. *
  17680. * @example
  17681. <example>
  17682. <file name="index.html">
  17683. <input ng-keydown="count = count + 1" ng-init="count=0">
  17684. key down count: {{count}}
  17685. </file>
  17686. </example>
  17687. */
  17688. /**
  17689. * @ngdoc directive
  17690. * @name ngKeyup
  17691. *
  17692. * @description
  17693. * Specify custom behavior on keyup event.
  17694. *
  17695. * @element ANY
  17696. * @priority 0
  17697. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17698. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17699. *
  17700. * @example
  17701. <example>
  17702. <file name="index.html">
  17703. <p>Typing in the input box below updates the key count</p>
  17704. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  17705. <p>Typing in the input box below updates the keycode</p>
  17706. <input ng-keyup="event=$event">
  17707. <p>event keyCode: {{ event.keyCode }}</p>
  17708. <p>event altKey: {{ event.altKey }}</p>
  17709. </file>
  17710. </example>
  17711. */
  17712. /**
  17713. * @ngdoc directive
  17714. * @name ngKeypress
  17715. *
  17716. * @description
  17717. * Specify custom behavior on keypress event.
  17718. *
  17719. * @element ANY
  17720. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17721. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17722. * and can be interrogated for keyCode, altKey, etc.)
  17723. *
  17724. * @example
  17725. <example>
  17726. <file name="index.html">
  17727. <input ng-keypress="count = count + 1" ng-init="count=0">
  17728. key press count: {{count}}
  17729. </file>
  17730. </example>
  17731. */
  17732. /**
  17733. * @ngdoc directive
  17734. * @name ngSubmit
  17735. *
  17736. * @description
  17737. * Enables binding angular expressions to onsubmit events.
  17738. *
  17739. * Additionally it prevents the default action (which for form means sending the request to the
  17740. * server and reloading the current page), but only if the form does not contain `action`,
  17741. * `data-action`, or `x-action` attributes.
  17742. *
  17743. * <div class="alert alert-warning">
  17744. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  17745. * `ngSubmit` handlers together. See the
  17746. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  17747. * for a detailed discussion of when `ngSubmit` may be triggered.
  17748. * </div>
  17749. *
  17750. * @element form
  17751. * @priority 0
  17752. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17753. * ({@link guide/expression#-event- Event object is available as `$event`})
  17754. *
  17755. * @example
  17756. <example module="submitExample">
  17757. <file name="index.html">
  17758. <script>
  17759. angular.module('submitExample', [])
  17760. .controller('ExampleController', ['$scope', function($scope) {
  17761. $scope.list = [];
  17762. $scope.text = 'hello';
  17763. $scope.submit = function() {
  17764. if ($scope.text) {
  17765. $scope.list.push(this.text);
  17766. $scope.text = '';
  17767. }
  17768. };
  17769. }]);
  17770. </script>
  17771. <form ng-submit="submit()" ng-controller="ExampleController">
  17772. Enter text and hit enter:
  17773. <input type="text" ng-model="text" name="text" />
  17774. <input type="submit" id="submit" value="Submit" />
  17775. <pre>list={{list}}</pre>
  17776. </form>
  17777. </file>
  17778. <file name="protractor.js" type="protractor">
  17779. it('should check ng-submit', function() {
  17780. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17781. element(by.css('#submit')).click();
  17782. expect(element(by.binding('list')).getText()).toContain('hello');
  17783. expect(element(by.model('text')).getAttribute('value')).toBe('');
  17784. });
  17785. it('should ignore empty strings', function() {
  17786. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17787. element(by.css('#submit')).click();
  17788. element(by.css('#submit')).click();
  17789. expect(element(by.binding('list')).getText()).toContain('hello');
  17790. });
  17791. </file>
  17792. </example>
  17793. */
  17794. /**
  17795. * @ngdoc directive
  17796. * @name ngFocus
  17797. *
  17798. * @description
  17799. * Specify custom behavior on focus event.
  17800. *
  17801. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  17802. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17803. * during an `$apply` to ensure a consistent state.
  17804. *
  17805. * @element window, input, select, textarea, a
  17806. * @priority 0
  17807. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17808. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17809. *
  17810. * @example
  17811. * See {@link ng.directive:ngClick ngClick}
  17812. */
  17813. /**
  17814. * @ngdoc directive
  17815. * @name ngBlur
  17816. *
  17817. * @description
  17818. * Specify custom behavior on blur event.
  17819. *
  17820. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  17821. * an element has lost focus.
  17822. *
  17823. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  17824. * (e.g. removing a focussed input),
  17825. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17826. * during an `$apply` to ensure a consistent state.
  17827. *
  17828. * @element window, input, select, textarea, a
  17829. * @priority 0
  17830. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17831. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17832. *
  17833. * @example
  17834. * See {@link ng.directive:ngClick ngClick}
  17835. */
  17836. /**
  17837. * @ngdoc directive
  17838. * @name ngCopy
  17839. *
  17840. * @description
  17841. * Specify custom behavior on copy event.
  17842. *
  17843. * @element window, input, select, textarea, a
  17844. * @priority 0
  17845. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17846. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17847. *
  17848. * @example
  17849. <example>
  17850. <file name="index.html">
  17851. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17852. copied: {{copied}}
  17853. </file>
  17854. </example>
  17855. */
  17856. /**
  17857. * @ngdoc directive
  17858. * @name ngCut
  17859. *
  17860. * @description
  17861. * Specify custom behavior on cut event.
  17862. *
  17863. * @element window, input, select, textarea, a
  17864. * @priority 0
  17865. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17866. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17867. *
  17868. * @example
  17869. <example>
  17870. <file name="index.html">
  17871. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17872. cut: {{cut}}
  17873. </file>
  17874. </example>
  17875. */
  17876. /**
  17877. * @ngdoc directive
  17878. * @name ngPaste
  17879. *
  17880. * @description
  17881. * Specify custom behavior on paste event.
  17882. *
  17883. * @element window, input, select, textarea, a
  17884. * @priority 0
  17885. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17886. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17887. *
  17888. * @example
  17889. <example>
  17890. <file name="index.html">
  17891. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17892. pasted: {{paste}}
  17893. </file>
  17894. </example>
  17895. */
  17896. /**
  17897. * @ngdoc directive
  17898. * @name ngIf
  17899. * @restrict A
  17900. *
  17901. * @description
  17902. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17903. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17904. * value then the element is removed from the DOM, otherwise a clone of the
  17905. * element is reinserted into the DOM.
  17906. *
  17907. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17908. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17909. * case when this difference is significant is when using css selectors that rely on an element's
  17910. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17911. *
  17912. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17913. * is created when the element is restored. The scope created within `ngIf` inherits from
  17914. * its parent scope using
  17915. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  17916. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17917. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17918. * variable within the child scope will override (hide) the value in the parent scope.
  17919. *
  17920. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17921. * is if an element's class attribute is directly modified after it's compiled, using something like
  17922. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17923. * the added class will be lost because the original compiled state is used to regenerate the element.
  17924. *
  17925. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17926. * and `leave` effects.
  17927. *
  17928. * @animations
  17929. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  17930. * leave - happens just before the `ngIf` contents are removed from the DOM
  17931. *
  17932. * @element ANY
  17933. * @scope
  17934. * @priority 600
  17935. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17936. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17937. * element is added to the DOM tree.
  17938. *
  17939. * @example
  17940. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17941. <file name="index.html">
  17942. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17943. Show when checked:
  17944. <span ng-if="checked" class="animate-if">
  17945. I'm removed when the checkbox is unchecked.
  17946. </span>
  17947. </file>
  17948. <file name="animations.css">
  17949. .animate-if {
  17950. background:white;
  17951. border:1px solid black;
  17952. padding:10px;
  17953. }
  17954. .animate-if.ng-enter, .animate-if.ng-leave {
  17955. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17956. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17957. }
  17958. .animate-if.ng-enter,
  17959. .animate-if.ng-leave.ng-leave-active {
  17960. opacity:0;
  17961. }
  17962. .animate-if.ng-leave,
  17963. .animate-if.ng-enter.ng-enter-active {
  17964. opacity:1;
  17965. }
  17966. </file>
  17967. </example>
  17968. */
  17969. var ngIfDirective = ['$animate', function($animate) {
  17970. return {
  17971. transclude: 'element',
  17972. priority: 600,
  17973. terminal: true,
  17974. restrict: 'A',
  17975. $$tlb: true,
  17976. link: function ($scope, $element, $attr, ctrl, $transclude) {
  17977. var block, childScope, previousElements;
  17978. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  17979. if (toBoolean(value)) {
  17980. if (!childScope) {
  17981. childScope = $scope.$new();
  17982. $transclude(childScope, function (clone) {
  17983. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  17984. // Note: We only need the first/last node of the cloned nodes.
  17985. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17986. // by a directive with templateUrl when its template arrives.
  17987. block = {
  17988. clone: clone
  17989. };
  17990. $animate.enter(clone, $element.parent(), $element);
  17991. });
  17992. }
  17993. } else {
  17994. if(previousElements) {
  17995. previousElements.remove();
  17996. previousElements = null;
  17997. }
  17998. if(childScope) {
  17999. childScope.$destroy();
  18000. childScope = null;
  18001. }
  18002. if(block) {
  18003. previousElements = getBlockElements(block.clone);
  18004. $animate.leave(previousElements, function() {
  18005. previousElements = null;
  18006. });
  18007. block = null;
  18008. }
  18009. }
  18010. });
  18011. }
  18012. };
  18013. }];
  18014. /**
  18015. * @ngdoc directive
  18016. * @name ngInclude
  18017. * @restrict ECA
  18018. *
  18019. * @description
  18020. * Fetches, compiles and includes an external HTML fragment.
  18021. *
  18022. * By default, the template URL is restricted to the same domain and protocol as the
  18023. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  18024. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  18025. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  18026. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  18027. * ng.$sce Strict Contextual Escaping}.
  18028. *
  18029. * In addition, the browser's
  18030. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  18031. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  18032. * policy may further restrict whether the template is successfully loaded.
  18033. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  18034. * access on some browsers.
  18035. *
  18036. * @animations
  18037. * enter - animation is used to bring new content into the browser.
  18038. * leave - animation is used to animate existing content away.
  18039. *
  18040. * The enter and leave animation occur concurrently.
  18041. *
  18042. * @scope
  18043. * @priority 400
  18044. *
  18045. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  18046. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  18047. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  18048. *
  18049. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  18050. * $anchorScroll} to scroll the viewport after the content is loaded.
  18051. *
  18052. * - If the attribute is not set, disable scrolling.
  18053. * - If the attribute is set without value, enable scrolling.
  18054. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  18055. *
  18056. * @example
  18057. <example module="includeExample" deps="angular-animate.js" animations="true">
  18058. <file name="index.html">
  18059. <div ng-controller="ExampleController">
  18060. <select ng-model="template" ng-options="t.name for t in templates">
  18061. <option value="">(blank)</option>
  18062. </select>
  18063. url of the template: <tt>{{template.url}}</tt>
  18064. <hr/>
  18065. <div class="slide-animate-container">
  18066. <div class="slide-animate" ng-include="template.url"></div>
  18067. </div>
  18068. </div>
  18069. </file>
  18070. <file name="script.js">
  18071. angular.module('includeExample', ['ngAnimate'])
  18072. .controller('ExampleController', ['$scope', function($scope) {
  18073. $scope.templates =
  18074. [ { name: 'template1.html', url: 'template1.html'},
  18075. { name: 'template2.html', url: 'template2.html'} ];
  18076. $scope.template = $scope.templates[0];
  18077. }]);
  18078. </file>
  18079. <file name="template1.html">
  18080. Content of template1.html
  18081. </file>
  18082. <file name="template2.html">
  18083. Content of template2.html
  18084. </file>
  18085. <file name="animations.css">
  18086. .slide-animate-container {
  18087. position:relative;
  18088. background:white;
  18089. border:1px solid black;
  18090. height:40px;
  18091. overflow:hidden;
  18092. }
  18093. .slide-animate {
  18094. padding:10px;
  18095. }
  18096. .slide-animate.ng-enter, .slide-animate.ng-leave {
  18097. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18098. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18099. position:absolute;
  18100. top:0;
  18101. left:0;
  18102. right:0;
  18103. bottom:0;
  18104. display:block;
  18105. padding:10px;
  18106. }
  18107. .slide-animate.ng-enter {
  18108. top:-50px;
  18109. }
  18110. .slide-animate.ng-enter.ng-enter-active {
  18111. top:0;
  18112. }
  18113. .slide-animate.ng-leave {
  18114. top:0;
  18115. }
  18116. .slide-animate.ng-leave.ng-leave-active {
  18117. top:50px;
  18118. }
  18119. </file>
  18120. <file name="protractor.js" type="protractor">
  18121. var templateSelect = element(by.model('template'));
  18122. var includeElem = element(by.css('[ng-include]'));
  18123. it('should load template1.html', function() {
  18124. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  18125. });
  18126. it('should load template2.html', function() {
  18127. if (browser.params.browser == 'firefox') {
  18128. // Firefox can't handle using selects
  18129. // See https://github.com/angular/protractor/issues/480
  18130. return;
  18131. }
  18132. templateSelect.click();
  18133. templateSelect.all(by.css('option')).get(2).click();
  18134. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  18135. });
  18136. it('should change to blank', function() {
  18137. if (browser.params.browser == 'firefox') {
  18138. // Firefox can't handle using selects
  18139. return;
  18140. }
  18141. templateSelect.click();
  18142. templateSelect.all(by.css('option')).get(0).click();
  18143. expect(includeElem.isPresent()).toBe(false);
  18144. });
  18145. </file>
  18146. </example>
  18147. */
  18148. /**
  18149. * @ngdoc event
  18150. * @name ngInclude#$includeContentRequested
  18151. * @eventType emit on the scope ngInclude was declared in
  18152. * @description
  18153. * Emitted every time the ngInclude content is requested.
  18154. */
  18155. /**
  18156. * @ngdoc event
  18157. * @name ngInclude#$includeContentLoaded
  18158. * @eventType emit on the current ngInclude scope
  18159. * @description
  18160. * Emitted every time the ngInclude content is reloaded.
  18161. */
  18162. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  18163. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  18164. return {
  18165. restrict: 'ECA',
  18166. priority: 400,
  18167. terminal: true,
  18168. transclude: 'element',
  18169. controller: angular.noop,
  18170. compile: function(element, attr) {
  18171. var srcExp = attr.ngInclude || attr.src,
  18172. onloadExp = attr.onload || '',
  18173. autoScrollExp = attr.autoscroll;
  18174. return function(scope, $element, $attr, ctrl, $transclude) {
  18175. var changeCounter = 0,
  18176. currentScope,
  18177. previousElement,
  18178. currentElement;
  18179. var cleanupLastIncludeContent = function() {
  18180. if(previousElement) {
  18181. previousElement.remove();
  18182. previousElement = null;
  18183. }
  18184. if(currentScope) {
  18185. currentScope.$destroy();
  18186. currentScope = null;
  18187. }
  18188. if(currentElement) {
  18189. $animate.leave(currentElement, function() {
  18190. previousElement = null;
  18191. });
  18192. previousElement = currentElement;
  18193. currentElement = null;
  18194. }
  18195. };
  18196. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  18197. var afterAnimation = function() {
  18198. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  18199. $anchorScroll();
  18200. }
  18201. };
  18202. var thisChangeId = ++changeCounter;
  18203. if (src) {
  18204. $http.get(src, {cache: $templateCache}).success(function(response) {
  18205. if (thisChangeId !== changeCounter) return;
  18206. var newScope = scope.$new();
  18207. ctrl.template = response;
  18208. // Note: This will also link all children of ng-include that were contained in the original
  18209. // html. If that content contains controllers, ... they could pollute/change the scope.
  18210. // However, using ng-include on an element with additional content does not make sense...
  18211. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  18212. // function is called before linking the content, which would apply child
  18213. // directives to non existing elements.
  18214. var clone = $transclude(newScope, function(clone) {
  18215. cleanupLastIncludeContent();
  18216. $animate.enter(clone, null, $element, afterAnimation);
  18217. });
  18218. currentScope = newScope;
  18219. currentElement = clone;
  18220. currentScope.$emit('$includeContentLoaded');
  18221. scope.$eval(onloadExp);
  18222. }).error(function() {
  18223. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  18224. });
  18225. scope.$emit('$includeContentRequested');
  18226. } else {
  18227. cleanupLastIncludeContent();
  18228. ctrl.template = null;
  18229. }
  18230. });
  18231. };
  18232. }
  18233. };
  18234. }];
  18235. // This directive is called during the $transclude call of the first `ngInclude` directive.
  18236. // It will replace and compile the content of the element with the loaded template.
  18237. // We need this directive so that the element content is already filled when
  18238. // the link function of another directive on the same element as ngInclude
  18239. // is called.
  18240. var ngIncludeFillContentDirective = ['$compile',
  18241. function($compile) {
  18242. return {
  18243. restrict: 'ECA',
  18244. priority: -400,
  18245. require: 'ngInclude',
  18246. link: function(scope, $element, $attr, ctrl) {
  18247. $element.html(ctrl.template);
  18248. $compile($element.contents())(scope);
  18249. }
  18250. };
  18251. }];
  18252. /**
  18253. * @ngdoc directive
  18254. * @name ngInit
  18255. * @restrict AC
  18256. *
  18257. * @description
  18258. * The `ngInit` directive allows you to evaluate an expression in the
  18259. * current scope.
  18260. *
  18261. * <div class="alert alert-error">
  18262. * The only appropriate use of `ngInit` is for aliasing special properties of
  18263. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  18264. * should use {@link guide/controller controllers} rather than `ngInit`
  18265. * to initialize values on a scope.
  18266. * </div>
  18267. * <div class="alert alert-warning">
  18268. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  18269. * sure you have parenthesis for correct precedence:
  18270. * <pre class="prettyprint">
  18271. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  18272. * </pre>
  18273. * </div>
  18274. *
  18275. * @priority 450
  18276. *
  18277. * @element ANY
  18278. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  18279. *
  18280. * @example
  18281. <example module="initExample">
  18282. <file name="index.html">
  18283. <script>
  18284. angular.module('initExample', [])
  18285. .controller('ExampleController', ['$scope', function($scope) {
  18286. $scope.list = [['a', 'b'], ['c', 'd']];
  18287. }]);
  18288. </script>
  18289. <div ng-controller="ExampleController">
  18290. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  18291. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  18292. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  18293. </div>
  18294. </div>
  18295. </div>
  18296. </file>
  18297. <file name="protractor.js" type="protractor">
  18298. it('should alias index positions', function() {
  18299. var elements = element.all(by.css('.example-init'));
  18300. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  18301. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  18302. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  18303. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  18304. });
  18305. </file>
  18306. </example>
  18307. */
  18308. var ngInitDirective = ngDirective({
  18309. priority: 450,
  18310. compile: function() {
  18311. return {
  18312. pre: function(scope, element, attrs) {
  18313. scope.$eval(attrs.ngInit);
  18314. }
  18315. };
  18316. }
  18317. });
  18318. /**
  18319. * @ngdoc directive
  18320. * @name ngNonBindable
  18321. * @restrict AC
  18322. * @priority 1000
  18323. *
  18324. * @description
  18325. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  18326. * DOM element. This is useful if the element contains what appears to be Angular directives and
  18327. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  18328. * displays snippets of code, for instance.
  18329. *
  18330. * @element ANY
  18331. *
  18332. * @example
  18333. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  18334. * but the one wrapped in `ngNonBindable` is left alone.
  18335. *
  18336. * @example
  18337. <example>
  18338. <file name="index.html">
  18339. <div>Normal: {{1 + 2}}</div>
  18340. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  18341. </file>
  18342. <file name="protractor.js" type="protractor">
  18343. it('should check ng-non-bindable', function() {
  18344. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  18345. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  18346. });
  18347. </file>
  18348. </example>
  18349. */
  18350. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  18351. /**
  18352. * @ngdoc directive
  18353. * @name ngPluralize
  18354. * @restrict EA
  18355. *
  18356. * @description
  18357. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  18358. * These rules are bundled with angular.js, but can be overridden
  18359. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  18360. * by specifying the mappings between
  18361. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18362. * and the strings to be displayed.
  18363. *
  18364. * # Plural categories and explicit number rules
  18365. * There are two
  18366. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18367. * in Angular's default en-US locale: "one" and "other".
  18368. *
  18369. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  18370. * any number that is not 1), an explicit number rule can only match one number. For example, the
  18371. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  18372. * and explicit number rules throughout the rest of this documentation.
  18373. *
  18374. * # Configuring ngPluralize
  18375. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  18376. * You can also provide an optional attribute, `offset`.
  18377. *
  18378. * The value of the `count` attribute can be either a string or an {@link guide/expression
  18379. * Angular expression}; these are evaluated on the current scope for its bound value.
  18380. *
  18381. * The `when` attribute specifies the mappings between plural categories and the actual
  18382. * string to be displayed. The value of the attribute should be a JSON object.
  18383. *
  18384. * The following example shows how to configure ngPluralize:
  18385. *
  18386. * ```html
  18387. * <ng-pluralize count="personCount"
  18388. when="{'0': 'Nobody is viewing.',
  18389. * 'one': '1 person is viewing.',
  18390. * 'other': '{} people are viewing.'}">
  18391. * </ng-pluralize>
  18392. *```
  18393. *
  18394. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  18395. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  18396. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  18397. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  18398. * show "a dozen people are viewing".
  18399. *
  18400. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  18401. * into pluralized strings. In the previous example, Angular will replace `{}` with
  18402. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  18403. * for <span ng-non-bindable>{{numberExpression}}</span>.
  18404. *
  18405. * # Configuring ngPluralize with offset
  18406. * The `offset` attribute allows further customization of pluralized text, which can result in
  18407. * a better user experience. For example, instead of the message "4 people are viewing this document",
  18408. * you might display "John, Kate and 2 others are viewing this document".
  18409. * The offset attribute allows you to offset a number by any desired value.
  18410. * Let's take a look at an example:
  18411. *
  18412. * ```html
  18413. * <ng-pluralize count="personCount" offset=2
  18414. * when="{'0': 'Nobody is viewing.',
  18415. * '1': '{{person1}} is viewing.',
  18416. * '2': '{{person1}} and {{person2}} are viewing.',
  18417. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18418. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18419. * </ng-pluralize>
  18420. * ```
  18421. *
  18422. * Notice that we are still using two plural categories(one, other), but we added
  18423. * three explicit number rules 0, 1 and 2.
  18424. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  18425. * When three people view the document, no explicit number rule is found, so
  18426. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  18427. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  18428. * is shown.
  18429. *
  18430. * Note that when you specify offsets, you must provide explicit number rules for
  18431. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  18432. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  18433. * plural categories "one" and "other".
  18434. *
  18435. * @param {string|expression} count The variable to be bound to.
  18436. * @param {string} when The mapping between plural category to its corresponding strings.
  18437. * @param {number=} offset Offset to deduct from the total number.
  18438. *
  18439. * @example
  18440. <example module="pluralizeExample">
  18441. <file name="index.html">
  18442. <script>
  18443. angular.module('pluralizeExample', [])
  18444. .controller('ExampleController', ['$scope', function($scope) {
  18445. $scope.person1 = 'Igor';
  18446. $scope.person2 = 'Misko';
  18447. $scope.personCount = 1;
  18448. }]);
  18449. </script>
  18450. <div ng-controller="ExampleController">
  18451. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  18452. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  18453. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  18454. <!--- Example with simple pluralization rules for en locale --->
  18455. Without Offset:
  18456. <ng-pluralize count="personCount"
  18457. when="{'0': 'Nobody is viewing.',
  18458. 'one': '1 person is viewing.',
  18459. 'other': '{} people are viewing.'}">
  18460. </ng-pluralize><br>
  18461. <!--- Example with offset --->
  18462. With Offset(2):
  18463. <ng-pluralize count="personCount" offset=2
  18464. when="{'0': 'Nobody is viewing.',
  18465. '1': '{{person1}} is viewing.',
  18466. '2': '{{person1}} and {{person2}} are viewing.',
  18467. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18468. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18469. </ng-pluralize>
  18470. </div>
  18471. </file>
  18472. <file name="protractor.js" type="protractor">
  18473. it('should show correct pluralized string', function() {
  18474. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  18475. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18476. var countInput = element(by.model('personCount'));
  18477. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  18478. expect(withOffset.getText()).toEqual('Igor is viewing.');
  18479. countInput.clear();
  18480. countInput.sendKeys('0');
  18481. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  18482. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  18483. countInput.clear();
  18484. countInput.sendKeys('2');
  18485. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  18486. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  18487. countInput.clear();
  18488. countInput.sendKeys('3');
  18489. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  18490. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  18491. countInput.clear();
  18492. countInput.sendKeys('4');
  18493. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  18494. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  18495. });
  18496. it('should show data-bound names', function() {
  18497. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18498. var personCount = element(by.model('personCount'));
  18499. var person1 = element(by.model('person1'));
  18500. var person2 = element(by.model('person2'));
  18501. personCount.clear();
  18502. personCount.sendKeys('4');
  18503. person1.clear();
  18504. person1.sendKeys('Di');
  18505. person2.clear();
  18506. person2.sendKeys('Vojta');
  18507. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  18508. });
  18509. </file>
  18510. </example>
  18511. */
  18512. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  18513. var BRACE = /{}/g;
  18514. return {
  18515. restrict: 'EA',
  18516. link: function(scope, element, attr) {
  18517. var numberExp = attr.count,
  18518. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  18519. offset = attr.offset || 0,
  18520. whens = scope.$eval(whenExp) || {},
  18521. whensExpFns = {},
  18522. startSymbol = $interpolate.startSymbol(),
  18523. endSymbol = $interpolate.endSymbol(),
  18524. isWhen = /^when(Minus)?(.+)$/;
  18525. forEach(attr, function(expression, attributeName) {
  18526. if (isWhen.test(attributeName)) {
  18527. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  18528. element.attr(attr.$attr[attributeName]);
  18529. }
  18530. });
  18531. forEach(whens, function(expression, key) {
  18532. whensExpFns[key] =
  18533. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  18534. offset + endSymbol));
  18535. });
  18536. scope.$watch(function ngPluralizeWatch() {
  18537. var value = parseFloat(scope.$eval(numberExp));
  18538. if (!isNaN(value)) {
  18539. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  18540. //check it against pluralization rules in $locale service
  18541. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  18542. return whensExpFns[value](scope, element, true);
  18543. } else {
  18544. return '';
  18545. }
  18546. }, function ngPluralizeWatchAction(newVal) {
  18547. element.text(newVal);
  18548. });
  18549. }
  18550. };
  18551. }];
  18552. /**
  18553. * @ngdoc directive
  18554. * @name ngRepeat
  18555. *
  18556. * @description
  18557. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  18558. * instance gets its own scope, where the given loop variable is set to the current collection item,
  18559. * and `$index` is set to the item index or key.
  18560. *
  18561. * Special properties are exposed on the local scope of each template instance, including:
  18562. *
  18563. * | Variable | Type | Details |
  18564. * |-----------|-----------------|-----------------------------------------------------------------------------|
  18565. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  18566. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  18567. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  18568. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  18569. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  18570. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  18571. *
  18572. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  18573. * This may be useful when, for instance, nesting ngRepeats.
  18574. *
  18575. * # Special repeat start and end points
  18576. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  18577. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  18578. * 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)
  18579. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  18580. *
  18581. * The example below makes use of this feature:
  18582. * ```html
  18583. * <header ng-repeat-start="item in items">
  18584. * Header {{ item }}
  18585. * </header>
  18586. * <div class="body">
  18587. * Body {{ item }}
  18588. * </div>
  18589. * <footer ng-repeat-end>
  18590. * Footer {{ item }}
  18591. * </footer>
  18592. * ```
  18593. *
  18594. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  18595. * ```html
  18596. * <header>
  18597. * Header A
  18598. * </header>
  18599. * <div class="body">
  18600. * Body A
  18601. * </div>
  18602. * <footer>
  18603. * Footer A
  18604. * </footer>
  18605. * <header>
  18606. * Header B
  18607. * </header>
  18608. * <div class="body">
  18609. * Body B
  18610. * </div>
  18611. * <footer>
  18612. * Footer B
  18613. * </footer>
  18614. * ```
  18615. *
  18616. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  18617. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  18618. *
  18619. * @animations
  18620. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  18621. *
  18622. * **.leave** - when an item is removed from the list or when an item is filtered out
  18623. *
  18624. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  18625. *
  18626. * @element ANY
  18627. * @scope
  18628. * @priority 1000
  18629. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  18630. * formats are currently supported:
  18631. *
  18632. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  18633. * is a scope expression giving the collection to enumerate.
  18634. *
  18635. * For example: `album in artist.albums`.
  18636. *
  18637. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  18638. * and `expression` is the scope expression giving the collection to enumerate.
  18639. *
  18640. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  18641. *
  18642. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  18643. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  18644. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  18645. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  18646. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  18647. * before specifying a tracking expression.
  18648. *
  18649. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  18650. * will be associated by item identity in the array.
  18651. *
  18652. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18653. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18654. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18655. * element in the same way in the DOM.
  18656. *
  18657. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18658. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18659. * property is same.
  18660. *
  18661. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18662. * to items in conjunction with a tracking expression.
  18663. *
  18664. * @example
  18665. * This example initializes the scope to a list of names and
  18666. * then uses `ngRepeat` to display every person:
  18667. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18668. <file name="index.html">
  18669. <div ng-init="friends = [
  18670. {name:'John', age:25, gender:'boy'},
  18671. {name:'Jessie', age:30, gender:'girl'},
  18672. {name:'Johanna', age:28, gender:'girl'},
  18673. {name:'Joy', age:15, gender:'girl'},
  18674. {name:'Mary', age:28, gender:'girl'},
  18675. {name:'Peter', age:95, gender:'boy'},
  18676. {name:'Sebastian', age:50, gender:'boy'},
  18677. {name:'Erika', age:27, gender:'girl'},
  18678. {name:'Patrick', age:40, gender:'boy'},
  18679. {name:'Samantha', age:60, gender:'girl'}
  18680. ]">
  18681. I have {{friends.length}} friends. They are:
  18682. <input type="search" ng-model="q" placeholder="filter friends..." />
  18683. <ul class="example-animate-container">
  18684. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18685. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18686. </li>
  18687. </ul>
  18688. </div>
  18689. </file>
  18690. <file name="animations.css">
  18691. .example-animate-container {
  18692. background:white;
  18693. border:1px solid black;
  18694. list-style:none;
  18695. margin:0;
  18696. padding:0 10px;
  18697. }
  18698. .animate-repeat {
  18699. line-height:40px;
  18700. list-style:none;
  18701. box-sizing:border-box;
  18702. }
  18703. .animate-repeat.ng-move,
  18704. .animate-repeat.ng-enter,
  18705. .animate-repeat.ng-leave {
  18706. -webkit-transition:all linear 0.5s;
  18707. transition:all linear 0.5s;
  18708. }
  18709. .animate-repeat.ng-leave.ng-leave-active,
  18710. .animate-repeat.ng-move,
  18711. .animate-repeat.ng-enter {
  18712. opacity:0;
  18713. max-height:0;
  18714. }
  18715. .animate-repeat.ng-leave,
  18716. .animate-repeat.ng-move.ng-move-active,
  18717. .animate-repeat.ng-enter.ng-enter-active {
  18718. opacity:1;
  18719. max-height:40px;
  18720. }
  18721. </file>
  18722. <file name="protractor.js" type="protractor">
  18723. var friends = element.all(by.repeater('friend in friends'));
  18724. it('should render initial data set', function() {
  18725. expect(friends.count()).toBe(10);
  18726. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18727. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18728. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18729. expect(element(by.binding('friends.length')).getText())
  18730. .toMatch("I have 10 friends. They are:");
  18731. });
  18732. it('should update repeater when filter predicate changes', function() {
  18733. expect(friends.count()).toBe(10);
  18734. element(by.model('q')).sendKeys('ma');
  18735. expect(friends.count()).toBe(2);
  18736. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18737. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18738. });
  18739. </file>
  18740. </example>
  18741. */
  18742. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18743. var NG_REMOVED = '$$NG_REMOVED';
  18744. var ngRepeatMinErr = minErr('ngRepeat');
  18745. return {
  18746. transclude: 'element',
  18747. priority: 1000,
  18748. terminal: true,
  18749. $$tlb: true,
  18750. link: function($scope, $element, $attr, ctrl, $transclude){
  18751. var expression = $attr.ngRepeat;
  18752. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18753. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18754. lhs, rhs, valueIdentifier, keyIdentifier,
  18755. hashFnLocals = {$id: hashKey};
  18756. if (!match) {
  18757. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18758. expression);
  18759. }
  18760. lhs = match[1];
  18761. rhs = match[2];
  18762. trackByExp = match[3];
  18763. if (trackByExp) {
  18764. trackByExpGetter = $parse(trackByExp);
  18765. trackByIdExpFn = function(key, value, index) {
  18766. // assign key, value, and $index to the locals so that they can be used in hash functions
  18767. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18768. hashFnLocals[valueIdentifier] = value;
  18769. hashFnLocals.$index = index;
  18770. return trackByExpGetter($scope, hashFnLocals);
  18771. };
  18772. } else {
  18773. trackByIdArrayFn = function(key, value) {
  18774. return hashKey(value);
  18775. };
  18776. trackByIdObjFn = function(key) {
  18777. return key;
  18778. };
  18779. }
  18780. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18781. if (!match) {
  18782. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18783. lhs);
  18784. }
  18785. valueIdentifier = match[3] || match[1];
  18786. keyIdentifier = match[2];
  18787. // Store a list of elements from previous run. This is a hash where key is the item from the
  18788. // iterator, and the value is objects with following properties.
  18789. // - scope: bound scope
  18790. // - element: previous element.
  18791. // - index: position
  18792. var lastBlockMap = {};
  18793. //watch props
  18794. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18795. var index, length,
  18796. previousNode = $element[0], // current position of the node
  18797. nextNode,
  18798. // Same as lastBlockMap but it has the current state. It will become the
  18799. // lastBlockMap on the next iteration.
  18800. nextBlockMap = {},
  18801. arrayLength,
  18802. childScope,
  18803. key, value, // key/value of iteration
  18804. trackById,
  18805. trackByIdFn,
  18806. collectionKeys,
  18807. block, // last object information {scope, element, id}
  18808. nextBlockOrder = [],
  18809. elementsToRemove;
  18810. if (isArrayLike(collection)) {
  18811. collectionKeys = collection;
  18812. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18813. } else {
  18814. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18815. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18816. collectionKeys = [];
  18817. for (key in collection) {
  18818. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18819. collectionKeys.push(key);
  18820. }
  18821. }
  18822. collectionKeys.sort();
  18823. }
  18824. arrayLength = collectionKeys.length;
  18825. // locate existing items
  18826. length = nextBlockOrder.length = collectionKeys.length;
  18827. for(index = 0; index < length; index++) {
  18828. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18829. value = collection[key];
  18830. trackById = trackByIdFn(key, value, index);
  18831. assertNotHasOwnProperty(trackById, '`track by` id');
  18832. if(lastBlockMap.hasOwnProperty(trackById)) {
  18833. block = lastBlockMap[trackById];
  18834. delete lastBlockMap[trackById];
  18835. nextBlockMap[trackById] = block;
  18836. nextBlockOrder[index] = block;
  18837. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18838. // restore lastBlockMap
  18839. forEach(nextBlockOrder, function(block) {
  18840. if (block && block.scope) lastBlockMap[block.id] = block;
  18841. });
  18842. // This is a duplicate and we need to throw an error
  18843. throw ngRepeatMinErr('dupes',
  18844. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  18845. expression, trackById, toJson(value));
  18846. } else {
  18847. // new never before seen block
  18848. nextBlockOrder[index] = { id: trackById };
  18849. nextBlockMap[trackById] = false;
  18850. }
  18851. }
  18852. // remove existing items
  18853. for (key in lastBlockMap) {
  18854. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18855. if (lastBlockMap.hasOwnProperty(key)) {
  18856. block = lastBlockMap[key];
  18857. elementsToRemove = getBlockElements(block.clone);
  18858. $animate.leave(elementsToRemove);
  18859. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18860. block.scope.$destroy();
  18861. }
  18862. }
  18863. // we are not using forEach for perf reasons (trying to avoid #call)
  18864. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18865. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18866. value = collection[key];
  18867. block = nextBlockOrder[index];
  18868. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18869. if (block.scope) {
  18870. // if we have already seen this object, then we need to reuse the
  18871. // associated scope/element
  18872. childScope = block.scope;
  18873. nextNode = previousNode;
  18874. do {
  18875. nextNode = nextNode.nextSibling;
  18876. } while(nextNode && nextNode[NG_REMOVED]);
  18877. if (getBlockStart(block) != nextNode) {
  18878. // existing item which got moved
  18879. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18880. }
  18881. previousNode = getBlockEnd(block);
  18882. } else {
  18883. // new item which we don't know about
  18884. childScope = $scope.$new();
  18885. }
  18886. childScope[valueIdentifier] = value;
  18887. if (keyIdentifier) childScope[keyIdentifier] = key;
  18888. childScope.$index = index;
  18889. childScope.$first = (index === 0);
  18890. childScope.$last = (index === (arrayLength - 1));
  18891. childScope.$middle = !(childScope.$first || childScope.$last);
  18892. // jshint bitwise: false
  18893. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18894. // jshint bitwise: true
  18895. if (!block.scope) {
  18896. $transclude(childScope, function(clone) {
  18897. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18898. $animate.enter(clone, null, jqLite(previousNode));
  18899. previousNode = clone;
  18900. block.scope = childScope;
  18901. // Note: We only need the first/last node of the cloned nodes.
  18902. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18903. // by a directive with templateUrl when its template arrives.
  18904. block.clone = clone;
  18905. nextBlockMap[block.id] = block;
  18906. });
  18907. }
  18908. }
  18909. lastBlockMap = nextBlockMap;
  18910. });
  18911. }
  18912. };
  18913. function getBlockStart(block) {
  18914. return block.clone[0];
  18915. }
  18916. function getBlockEnd(block) {
  18917. return block.clone[block.clone.length - 1];
  18918. }
  18919. }];
  18920. /**
  18921. * @ngdoc directive
  18922. * @name ngShow
  18923. *
  18924. * @description
  18925. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18926. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  18927. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18928. * in AngularJS and sets the display style to none (using an !important flag).
  18929. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18930. *
  18931. * ```html
  18932. * <!-- when $scope.myValue is truthy (element is visible) -->
  18933. * <div ng-show="myValue"></div>
  18934. *
  18935. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18936. * <div ng-show="myValue" class="ng-hide"></div>
  18937. * ```
  18938. *
  18939. * When the `ngShow` expression evaluates to false then the `.ng-hide` CSS class is added to the class attribute
  18940. * on the element causing it to become hidden. When true, the `.ng-hide` CSS class is removed
  18941. * from the element causing the element not to appear hidden.
  18942. *
  18943. * <div class="alert alert-warning">
  18944. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18945. * "f" / "0" / "false" / "no" / "n" / "[]"
  18946. * </div>
  18947. *
  18948. * ## Why is !important used?
  18949. *
  18950. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  18951. * can be easily overridden by heavier selectors. For example, something as simple
  18952. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18953. * This also becomes a bigger issue when dealing with CSS frameworks.
  18954. *
  18955. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18956. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18957. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18958. *
  18959. * ### Overriding `.ng-hide`
  18960. *
  18961. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18962. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18963. * class in CSS:
  18964. *
  18965. * ```css
  18966. * .ng-hide {
  18967. * //this is just another form of hiding an element
  18968. * display:block!important;
  18969. * position:absolute;
  18970. * top:-9999px;
  18971. * left:-9999px;
  18972. * }
  18973. * ```
  18974. *
  18975. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18976. *
  18977. * ## A note about animations with `ngShow`
  18978. *
  18979. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18980. * is true and false. This system works like the animation system present with ngClass except that
  18981. * you must also include the !important flag to override the display property
  18982. * so that you can perform an animation when the element is hidden during the time of the animation.
  18983. *
  18984. * ```css
  18985. * //
  18986. * //a working example can be found at the bottom of this page
  18987. * //
  18988. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18989. * transition:0.5s linear all;
  18990. * }
  18991. *
  18992. * .my-element.ng-hide-add { ... }
  18993. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18994. * .my-element.ng-hide-remove { ... }
  18995. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18996. * ```
  18997. *
  18998. * 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
  18999. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  19000. *
  19001. * @animations
  19002. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  19003. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  19004. *
  19005. * @element ANY
  19006. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  19007. * then the element is shown or hidden respectively.
  19008. *
  19009. * @example
  19010. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19011. <file name="index.html">
  19012. Click me: <input type="checkbox" ng-model="checked"><br/>
  19013. <div>
  19014. Show:
  19015. <div class="check-element animate-show" ng-show="checked">
  19016. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  19017. </div>
  19018. </div>
  19019. <div>
  19020. Hide:
  19021. <div class="check-element animate-show" ng-hide="checked">
  19022. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19023. </div>
  19024. </div>
  19025. </file>
  19026. <file name="glyphicons.css">
  19027. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19028. </file>
  19029. <file name="animations.css">
  19030. .animate-show {
  19031. -webkit-transition:all linear 0.5s;
  19032. transition:all linear 0.5s;
  19033. line-height:20px;
  19034. opacity:1;
  19035. padding:10px;
  19036. border:1px solid black;
  19037. background:white;
  19038. }
  19039. .animate-show.ng-hide {
  19040. line-height:0;
  19041. opacity:0;
  19042. padding:0 10px;
  19043. }
  19044. .check-element {
  19045. padding:10px;
  19046. border:1px solid black;
  19047. background:white;
  19048. }
  19049. </file>
  19050. <file name="protractor.js" type="protractor">
  19051. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19052. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19053. it('should check ng-show / ng-hide', function() {
  19054. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19055. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19056. element(by.model('checked')).click();
  19057. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19058. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19059. });
  19060. </file>
  19061. </example>
  19062. */
  19063. var ngShowDirective = ['$animate', function($animate) {
  19064. return function(scope, element, attr) {
  19065. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  19066. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  19067. });
  19068. };
  19069. }];
  19070. /**
  19071. * @ngdoc directive
  19072. * @name ngHide
  19073. *
  19074. * @description
  19075. * The `ngHide` directive shows or hides the given HTML element based on the expression
  19076. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  19077. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  19078. * in AngularJS and sets the display style to none (using an !important flag).
  19079. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19080. *
  19081. * ```html
  19082. * <!-- when $scope.myValue is truthy (element is hidden) -->
  19083. * <div ng-hide="myValue" class="ng-hide"></div>
  19084. *
  19085. * <!-- when $scope.myValue is falsy (element is visible) -->
  19086. * <div ng-hide="myValue"></div>
  19087. * ```
  19088. *
  19089. * When the `.ngHide` expression evaluates to true then the `.ng-hide` CSS class is added to the class attribute
  19090. * on the element causing it to become hidden. When false, the `.ng-hide` CSS class is removed
  19091. * from the element causing the element not to appear hidden.
  19092. *
  19093. * <div class="alert alert-warning">
  19094. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  19095. * "f" / "0" / "false" / "no" / "n" / "[]"
  19096. * </div>
  19097. *
  19098. * ## Why is !important used?
  19099. *
  19100. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  19101. * can be easily overridden by heavier selectors. For example, something as simple
  19102. * as changing the display style on a HTML list item would make hidden elements appear visible.
  19103. * This also becomes a bigger issue when dealing with CSS frameworks.
  19104. *
  19105. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  19106. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  19107. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  19108. *
  19109. * ### Overriding `.ng-hide`
  19110. *
  19111. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  19112. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  19113. * class in CSS:
  19114. *
  19115. * ```css
  19116. * .ng-hide {
  19117. * //this is just another form of hiding an element
  19118. * display:block!important;
  19119. * position:absolute;
  19120. * top:-9999px;
  19121. * left:-9999px;
  19122. * }
  19123. * ```
  19124. *
  19125. * By default you don't need to override in CSS anything and the animations will work around the display style.
  19126. *
  19127. * ## A note about animations with `ngHide`
  19128. *
  19129. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  19130. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  19131. * CSS class is added and removed for you instead of your own CSS class.
  19132. *
  19133. * ```css
  19134. * //
  19135. * //a working example can be found at the bottom of this page
  19136. * //
  19137. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  19138. * transition:0.5s linear all;
  19139. * }
  19140. *
  19141. * .my-element.ng-hide-add { ... }
  19142. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  19143. * .my-element.ng-hide-remove { ... }
  19144. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  19145. * ```
  19146. *
  19147. * 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
  19148. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  19149. *
  19150. * @animations
  19151. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  19152. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  19153. *
  19154. * @element ANY
  19155. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  19156. * the element is shown or hidden respectively.
  19157. *
  19158. * @example
  19159. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19160. <file name="index.html">
  19161. Click me: <input type="checkbox" ng-model="checked"><br/>
  19162. <div>
  19163. Show:
  19164. <div class="check-element animate-hide" ng-show="checked">
  19165. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  19166. </div>
  19167. </div>
  19168. <div>
  19169. Hide:
  19170. <div class="check-element animate-hide" ng-hide="checked">
  19171. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19172. </div>
  19173. </div>
  19174. </file>
  19175. <file name="glyphicons.css">
  19176. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19177. </file>
  19178. <file name="animations.css">
  19179. .animate-hide {
  19180. -webkit-transition:all linear 0.5s;
  19181. transition:all linear 0.5s;
  19182. line-height:20px;
  19183. opacity:1;
  19184. padding:10px;
  19185. border:1px solid black;
  19186. background:white;
  19187. }
  19188. .animate-hide.ng-hide {
  19189. line-height:0;
  19190. opacity:0;
  19191. padding:0 10px;
  19192. }
  19193. .check-element {
  19194. padding:10px;
  19195. border:1px solid black;
  19196. background:white;
  19197. }
  19198. </file>
  19199. <file name="protractor.js" type="protractor">
  19200. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19201. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19202. it('should check ng-show / ng-hide', function() {
  19203. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19204. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19205. element(by.model('checked')).click();
  19206. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19207. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19208. });
  19209. </file>
  19210. </example>
  19211. */
  19212. var ngHideDirective = ['$animate', function($animate) {
  19213. return function(scope, element, attr) {
  19214. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  19215. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  19216. });
  19217. };
  19218. }];
  19219. /**
  19220. * @ngdoc directive
  19221. * @name ngStyle
  19222. * @restrict AC
  19223. *
  19224. * @description
  19225. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  19226. *
  19227. * @element ANY
  19228. * @param {expression} ngStyle
  19229. *
  19230. * {@link guide/expression Expression} which evals to an
  19231. * object whose keys are CSS style names and values are corresponding values for those CSS
  19232. * keys.
  19233. *
  19234. * Since some CSS style names are not valid keys for an object, they must be quoted.
  19235. * See the 'background-color' style in the example below.
  19236. *
  19237. * @example
  19238. <example>
  19239. <file name="index.html">
  19240. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  19241. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  19242. <input type="button" value="clear" ng-click="myStyle={}">
  19243. <br/>
  19244. <span ng-style="myStyle">Sample Text</span>
  19245. <pre>myStyle={{myStyle}}</pre>
  19246. </file>
  19247. <file name="style.css">
  19248. span {
  19249. color: black;
  19250. }
  19251. </file>
  19252. <file name="protractor.js" type="protractor">
  19253. var colorSpan = element(by.css('span'));
  19254. it('should check ng-style', function() {
  19255. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19256. element(by.css('input[value=\'set color\']')).click();
  19257. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  19258. element(by.css('input[value=clear]')).click();
  19259. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19260. });
  19261. </file>
  19262. </example>
  19263. */
  19264. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  19265. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  19266. if (oldStyles && (newStyles !== oldStyles)) {
  19267. forEach(oldStyles, function(val, style) { element.css(style, '');});
  19268. }
  19269. if (newStyles) element.css(newStyles);
  19270. }, true);
  19271. });
  19272. /**
  19273. * @ngdoc directive
  19274. * @name ngSwitch
  19275. * @restrict EA
  19276. *
  19277. * @description
  19278. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  19279. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  19280. * as specified in the template.
  19281. *
  19282. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  19283. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  19284. * matches the value obtained from the evaluated expression. In other words, you define a container element
  19285. * (where you place the directive), place an expression on the **`on="..."` attribute**
  19286. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  19287. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  19288. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  19289. * attribute is displayed.
  19290. *
  19291. * <div class="alert alert-info">
  19292. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  19293. * as literal string values to match against.
  19294. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  19295. * value of the expression `$scope.someVal`.
  19296. * </div>
  19297. * @animations
  19298. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  19299. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  19300. *
  19301. * @usage
  19302. *
  19303. * ```
  19304. * <ANY ng-switch="expression">
  19305. * <ANY ng-switch-when="matchValue1">...</ANY>
  19306. * <ANY ng-switch-when="matchValue2">...</ANY>
  19307. * <ANY ng-switch-default>...</ANY>
  19308. * </ANY>
  19309. * ```
  19310. *
  19311. *
  19312. * @scope
  19313. * @priority 800
  19314. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  19315. * On child elements add:
  19316. *
  19317. * * `ngSwitchWhen`: the case statement to match against. If match then this
  19318. * case will be displayed. If the same match appears multiple times, all the
  19319. * elements will be displayed.
  19320. * * `ngSwitchDefault`: the default case when no other case match. If there
  19321. * are multiple default cases, all of them will be displayed when no other
  19322. * case match.
  19323. *
  19324. *
  19325. * @example
  19326. <example module="switchExample" deps="angular-animate.js" animations="true">
  19327. <file name="index.html">
  19328. <div ng-controller="ExampleController">
  19329. <select ng-model="selection" ng-options="item for item in items">
  19330. </select>
  19331. <tt>selection={{selection}}</tt>
  19332. <hr/>
  19333. <div class="animate-switch-container"
  19334. ng-switch on="selection">
  19335. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  19336. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  19337. <div class="animate-switch" ng-switch-default>default</div>
  19338. </div>
  19339. </div>
  19340. </file>
  19341. <file name="script.js">
  19342. angular.module('switchExample', ['ngAnimate'])
  19343. .controller('ExampleController', ['$scope', function($scope) {
  19344. $scope.items = ['settings', 'home', 'other'];
  19345. $scope.selection = $scope.items[0];
  19346. }]);
  19347. </file>
  19348. <file name="animations.css">
  19349. .animate-switch-container {
  19350. position:relative;
  19351. background:white;
  19352. border:1px solid black;
  19353. height:40px;
  19354. overflow:hidden;
  19355. }
  19356. .animate-switch {
  19357. padding:10px;
  19358. }
  19359. .animate-switch.ng-animate {
  19360. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19361. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19362. position:absolute;
  19363. top:0;
  19364. left:0;
  19365. right:0;
  19366. bottom:0;
  19367. }
  19368. .animate-switch.ng-leave.ng-leave-active,
  19369. .animate-switch.ng-enter {
  19370. top:-50px;
  19371. }
  19372. .animate-switch.ng-leave,
  19373. .animate-switch.ng-enter.ng-enter-active {
  19374. top:0;
  19375. }
  19376. </file>
  19377. <file name="protractor.js" type="protractor">
  19378. var switchElem = element(by.css('[ng-switch]'));
  19379. var select = element(by.model('selection'));
  19380. it('should start in settings', function() {
  19381. expect(switchElem.getText()).toMatch(/Settings Div/);
  19382. });
  19383. it('should change to home', function() {
  19384. select.all(by.css('option')).get(1).click();
  19385. expect(switchElem.getText()).toMatch(/Home Span/);
  19386. });
  19387. it('should select default', function() {
  19388. select.all(by.css('option')).get(2).click();
  19389. expect(switchElem.getText()).toMatch(/default/);
  19390. });
  19391. </file>
  19392. </example>
  19393. */
  19394. var ngSwitchDirective = ['$animate', function($animate) {
  19395. return {
  19396. restrict: 'EA',
  19397. require: 'ngSwitch',
  19398. // asks for $scope to fool the BC controller module
  19399. controller: ['$scope', function ngSwitchController() {
  19400. this.cases = {};
  19401. }],
  19402. link: function(scope, element, attr, ngSwitchController) {
  19403. var watchExpr = attr.ngSwitch || attr.on,
  19404. selectedTranscludes = [],
  19405. selectedElements = [],
  19406. previousElements = [],
  19407. selectedScopes = [];
  19408. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  19409. var i, ii;
  19410. for (i = 0, ii = previousElements.length; i < ii; ++i) {
  19411. previousElements[i].remove();
  19412. }
  19413. previousElements.length = 0;
  19414. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  19415. var selected = selectedElements[i];
  19416. selectedScopes[i].$destroy();
  19417. previousElements[i] = selected;
  19418. $animate.leave(selected, function() {
  19419. previousElements.splice(i, 1);
  19420. });
  19421. }
  19422. selectedElements.length = 0;
  19423. selectedScopes.length = 0;
  19424. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  19425. scope.$eval(attr.change);
  19426. forEach(selectedTranscludes, function(selectedTransclude) {
  19427. var selectedScope = scope.$new();
  19428. selectedScopes.push(selectedScope);
  19429. selectedTransclude.transclude(selectedScope, function(caseElement) {
  19430. var anchor = selectedTransclude.element;
  19431. selectedElements.push(caseElement);
  19432. $animate.enter(caseElement, anchor.parent(), anchor);
  19433. });
  19434. });
  19435. }
  19436. });
  19437. }
  19438. };
  19439. }];
  19440. var ngSwitchWhenDirective = ngDirective({
  19441. transclude: 'element',
  19442. priority: 800,
  19443. require: '^ngSwitch',
  19444. link: function(scope, element, attrs, ctrl, $transclude) {
  19445. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  19446. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  19447. }
  19448. });
  19449. var ngSwitchDefaultDirective = ngDirective({
  19450. transclude: 'element',
  19451. priority: 800,
  19452. require: '^ngSwitch',
  19453. link: function(scope, element, attr, ctrl, $transclude) {
  19454. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  19455. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  19456. }
  19457. });
  19458. /**
  19459. * @ngdoc directive
  19460. * @name ngTransclude
  19461. * @restrict AC
  19462. *
  19463. * @description
  19464. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  19465. *
  19466. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  19467. *
  19468. * @element ANY
  19469. *
  19470. * @example
  19471. <example module="transcludeExample">
  19472. <file name="index.html">
  19473. <script>
  19474. angular.module('transcludeExample', [])
  19475. .directive('pane', function(){
  19476. return {
  19477. restrict: 'E',
  19478. transclude: true,
  19479. scope: { title:'@' },
  19480. template: '<div style="border: 1px solid black;">' +
  19481. '<div style="background-color: gray">{{title}}</div>' +
  19482. '<div ng-transclude></div>' +
  19483. '</div>'
  19484. };
  19485. })
  19486. .controller('ExampleController', ['$scope', function($scope) {
  19487. $scope.title = 'Lorem Ipsum';
  19488. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  19489. }]);
  19490. </script>
  19491. <div ng-controller="ExampleController">
  19492. <input ng-model="title"><br>
  19493. <textarea ng-model="text"></textarea> <br/>
  19494. <pane title="{{title}}">{{text}}</pane>
  19495. </div>
  19496. </file>
  19497. <file name="protractor.js" type="protractor">
  19498. it('should have transcluded', function() {
  19499. var titleElement = element(by.model('title'));
  19500. titleElement.clear();
  19501. titleElement.sendKeys('TITLE');
  19502. var textElement = element(by.model('text'));
  19503. textElement.clear();
  19504. textElement.sendKeys('TEXT');
  19505. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  19506. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  19507. });
  19508. </file>
  19509. </example>
  19510. *
  19511. */
  19512. var ngTranscludeDirective = ngDirective({
  19513. link: function($scope, $element, $attrs, controller, $transclude) {
  19514. if (!$transclude) {
  19515. throw minErr('ngTransclude')('orphan',
  19516. 'Illegal use of ngTransclude directive in the template! ' +
  19517. 'No parent directive that requires a transclusion found. ' +
  19518. 'Element: {0}',
  19519. startingTag($element));
  19520. }
  19521. $transclude(function(clone) {
  19522. $element.empty();
  19523. $element.append(clone);
  19524. });
  19525. }
  19526. });
  19527. /**
  19528. * @ngdoc directive
  19529. * @name script
  19530. * @restrict E
  19531. *
  19532. * @description
  19533. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  19534. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  19535. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  19536. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  19537. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  19538. *
  19539. * @param {string} type Must be set to `'text/ng-template'`.
  19540. * @param {string} id Cache name of the template.
  19541. *
  19542. * @example
  19543. <example>
  19544. <file name="index.html">
  19545. <script type="text/ng-template" id="/tpl.html">
  19546. Content of the template.
  19547. </script>
  19548. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  19549. <div id="tpl-content" ng-include src="currentTpl"></div>
  19550. </file>
  19551. <file name="protractor.js" type="protractor">
  19552. it('should load template defined inside script tag', function() {
  19553. element(by.css('#tpl-link')).click();
  19554. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  19555. });
  19556. </file>
  19557. </example>
  19558. */
  19559. var scriptDirective = ['$templateCache', function($templateCache) {
  19560. return {
  19561. restrict: 'E',
  19562. terminal: true,
  19563. compile: function(element, attr) {
  19564. if (attr.type == 'text/ng-template') {
  19565. var templateUrl = attr.id,
  19566. text = element[0].text;
  19567. $templateCache.put(templateUrl, text);
  19568. }
  19569. }
  19570. };
  19571. }];
  19572. var ngOptionsMinErr = minErr('ngOptions');
  19573. /**
  19574. * @ngdoc directive
  19575. * @name select
  19576. * @restrict E
  19577. *
  19578. * @description
  19579. * HTML `SELECT` element with angular data-binding.
  19580. *
  19581. * # `ngOptions`
  19582. *
  19583. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  19584. * elements for the `<select>` element using the array or object obtained by evaluating the
  19585. * `ngOptions` comprehension_expression.
  19586. *
  19587. * When an item in the `<select>` menu is selected, the array element or object property
  19588. * represented by the selected option will be bound to the model identified by the `ngModel`
  19589. * directive.
  19590. *
  19591. * <div class="alert alert-warning">
  19592. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  19593. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  19594. * </div>
  19595. *
  19596. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  19597. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  19598. * option. See example below for demonstration.
  19599. *
  19600. * <div class="alert alert-warning">
  19601. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  19602. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  19603. * `select` model to be bound to a non-string value. This is because an option element can only
  19604. * be bound to string values at present.
  19605. * </div>
  19606. *
  19607. * @param {string} ngModel Assignable angular expression to data-bind to.
  19608. * @param {string=} name Property name of the form under which the control is published.
  19609. * @param {string=} required The control is considered valid only if value is entered.
  19610. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19611. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19612. * `required` when you want to data-bind to the `required` attribute.
  19613. * @param {comprehension_expression=} ngOptions in one of the following forms:
  19614. *
  19615. * * for array data sources:
  19616. * * `label` **`for`** `value` **`in`** `array`
  19617. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  19618. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  19619. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  19620. * * for object data sources:
  19621. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19622. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19623. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  19624. * * `select` **`as`** `label` **`group by`** `group`
  19625. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  19626. *
  19627. * Where:
  19628. *
  19629. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  19630. * * `value`: local variable which will refer to each item in the `array` or each property value
  19631. * of `object` during iteration.
  19632. * * `key`: local variable which will refer to a property name in `object` during iteration.
  19633. * * `label`: The result of this expression will be the label for `<option>` element. The
  19634. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  19635. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  19636. * element. If not specified, `select` expression will default to `value`.
  19637. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  19638. * DOM element.
  19639. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  19640. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  19641. * `value` variable (e.g. `value.propertyName`).
  19642. *
  19643. * @example
  19644. <example module="selectExample">
  19645. <file name="index.html">
  19646. <script>
  19647. angular.module('selectExample', [])
  19648. .controller('ExampleController', ['$scope', function($scope) {
  19649. $scope.colors = [
  19650. {name:'black', shade:'dark'},
  19651. {name:'white', shade:'light'},
  19652. {name:'red', shade:'dark'},
  19653. {name:'blue', shade:'dark'},
  19654. {name:'yellow', shade:'light'}
  19655. ];
  19656. $scope.myColor = $scope.colors[2]; // red
  19657. }]);
  19658. </script>
  19659. <div ng-controller="ExampleController">
  19660. <ul>
  19661. <li ng-repeat="color in colors">
  19662. Name: <input ng-model="color.name">
  19663. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19664. </li>
  19665. <li>
  19666. [<a href ng-click="colors.push({})">add</a>]
  19667. </li>
  19668. </ul>
  19669. <hr/>
  19670. Color (null not allowed):
  19671. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  19672. Color (null allowed):
  19673. <span class="nullable">
  19674. <select ng-model="myColor" ng-options="color.name for color in colors">
  19675. <option value="">-- choose color --</option>
  19676. </select>
  19677. </span><br/>
  19678. Color grouped by shade:
  19679. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  19680. </select><br/>
  19681. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  19682. <hr/>
  19683. Currently selected: {{ {selected_color:myColor} }}
  19684. <div style="border:solid 1px black; height:20px"
  19685. ng-style="{'background-color':myColor.name}">
  19686. </div>
  19687. </div>
  19688. </file>
  19689. <file name="protractor.js" type="protractor">
  19690. it('should check ng-options', function() {
  19691. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  19692. element.all(by.model('myColor')).first().click();
  19693. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  19694. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  19695. element(by.css('.nullable select[ng-model="myColor"]')).click();
  19696. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  19697. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  19698. });
  19699. </file>
  19700. </example>
  19701. */
  19702. var ngOptionsDirective = valueFn({ terminal: true });
  19703. // jshint maxlen: false
  19704. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19705. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19706. 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]+?))?$/,
  19707. nullModelCtrl = {$setViewValue: noop};
  19708. // jshint maxlen: 100
  19709. return {
  19710. restrict: 'E',
  19711. require: ['select', '?ngModel'],
  19712. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19713. var self = this,
  19714. optionsMap = {},
  19715. ngModelCtrl = nullModelCtrl,
  19716. nullOption,
  19717. unknownOption;
  19718. self.databound = $attrs.ngModel;
  19719. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19720. ngModelCtrl = ngModelCtrl_;
  19721. nullOption = nullOption_;
  19722. unknownOption = unknownOption_;
  19723. };
  19724. self.addOption = function(value) {
  19725. assertNotHasOwnProperty(value, '"option value"');
  19726. optionsMap[value] = true;
  19727. if (ngModelCtrl.$viewValue == value) {
  19728. $element.val(value);
  19729. if (unknownOption.parent()) unknownOption.remove();
  19730. }
  19731. };
  19732. self.removeOption = function(value) {
  19733. if (this.hasOption(value)) {
  19734. delete optionsMap[value];
  19735. if (ngModelCtrl.$viewValue == value) {
  19736. this.renderUnknownOption(value);
  19737. }
  19738. }
  19739. };
  19740. self.renderUnknownOption = function(val) {
  19741. var unknownVal = '? ' + hashKey(val) + ' ?';
  19742. unknownOption.val(unknownVal);
  19743. $element.prepend(unknownOption);
  19744. $element.val(unknownVal);
  19745. unknownOption.prop('selected', true); // needed for IE
  19746. };
  19747. self.hasOption = function(value) {
  19748. return optionsMap.hasOwnProperty(value);
  19749. };
  19750. $scope.$on('$destroy', function() {
  19751. // disable unknown option so that we don't do work when the whole select is being destroyed
  19752. self.renderUnknownOption = noop;
  19753. });
  19754. }],
  19755. link: function(scope, element, attr, ctrls) {
  19756. // if ngModel is not defined, we don't need to do anything
  19757. if (!ctrls[1]) return;
  19758. var selectCtrl = ctrls[0],
  19759. ngModelCtrl = ctrls[1],
  19760. multiple = attr.multiple,
  19761. optionsExp = attr.ngOptions,
  19762. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19763. emptyOption,
  19764. // we can't just jqLite('<option>') since jqLite is not smart enough
  19765. // to create it in <select> and IE barfs otherwise.
  19766. optionTemplate = jqLite(document.createElement('option')),
  19767. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19768. unknownOption = optionTemplate.clone();
  19769. // find "null" option
  19770. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19771. if (children[i].value === '') {
  19772. emptyOption = nullOption = children.eq(i);
  19773. break;
  19774. }
  19775. }
  19776. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19777. // required validator
  19778. if (multiple) {
  19779. ngModelCtrl.$isEmpty = function(value) {
  19780. return !value || value.length === 0;
  19781. };
  19782. }
  19783. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19784. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19785. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19786. ////////////////////////////
  19787. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19788. ngModelCtrl.$render = function() {
  19789. var viewValue = ngModelCtrl.$viewValue;
  19790. if (selectCtrl.hasOption(viewValue)) {
  19791. if (unknownOption.parent()) unknownOption.remove();
  19792. selectElement.val(viewValue);
  19793. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19794. } else {
  19795. if (isUndefined(viewValue) && emptyOption) {
  19796. selectElement.val('');
  19797. } else {
  19798. selectCtrl.renderUnknownOption(viewValue);
  19799. }
  19800. }
  19801. };
  19802. selectElement.on('change', function() {
  19803. scope.$apply(function() {
  19804. if (unknownOption.parent()) unknownOption.remove();
  19805. ngModelCtrl.$setViewValue(selectElement.val());
  19806. });
  19807. });
  19808. }
  19809. function setupAsMultiple(scope, selectElement, ctrl) {
  19810. var lastView;
  19811. ctrl.$render = function() {
  19812. var items = new HashMap(ctrl.$viewValue);
  19813. forEach(selectElement.find('option'), function(option) {
  19814. option.selected = isDefined(items.get(option.value));
  19815. });
  19816. };
  19817. // we have to do it on each watch since ngModel watches reference, but
  19818. // we need to work of an array, so we need to see if anything was inserted/removed
  19819. scope.$watch(function selectMultipleWatch() {
  19820. if (!equals(lastView, ctrl.$viewValue)) {
  19821. lastView = shallowCopy(ctrl.$viewValue);
  19822. ctrl.$render();
  19823. }
  19824. });
  19825. selectElement.on('change', function() {
  19826. scope.$apply(function() {
  19827. var array = [];
  19828. forEach(selectElement.find('option'), function(option) {
  19829. if (option.selected) {
  19830. array.push(option.value);
  19831. }
  19832. });
  19833. ctrl.$setViewValue(array);
  19834. });
  19835. });
  19836. }
  19837. function setupAsOptions(scope, selectElement, ctrl) {
  19838. var match;
  19839. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19840. throw ngOptionsMinErr('iexp',
  19841. "Expected expression in form of " +
  19842. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19843. " but got '{0}'. Element: {1}",
  19844. optionsExp, startingTag(selectElement));
  19845. }
  19846. var displayFn = $parse(match[2] || match[1]),
  19847. valueName = match[4] || match[6],
  19848. keyName = match[5],
  19849. groupByFn = $parse(match[3] || ''),
  19850. valueFn = $parse(match[2] ? match[1] : valueName),
  19851. valuesFn = $parse(match[7]),
  19852. track = match[8],
  19853. trackFn = track ? $parse(match[8]) : null,
  19854. // This is an array of array of existing option groups in DOM.
  19855. // We try to reuse these if possible
  19856. // - optionGroupsCache[0] is the options with no option group
  19857. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19858. optionGroupsCache = [[{element: selectElement, label:''}]];
  19859. if (nullOption) {
  19860. // compile the element since there might be bindings in it
  19861. $compile(nullOption)(scope);
  19862. // remove the class, which is added automatically because we recompile the element and it
  19863. // becomes the compilation root
  19864. nullOption.removeClass('ng-scope');
  19865. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19866. // remove the label from the element. wtf?
  19867. nullOption.remove();
  19868. }
  19869. // clear contents, we'll add what's needed based on the model
  19870. selectElement.empty();
  19871. selectElement.on('change', function() {
  19872. scope.$apply(function() {
  19873. var optionGroup,
  19874. collection = valuesFn(scope) || [],
  19875. locals = {},
  19876. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19877. if (multiple) {
  19878. value = [];
  19879. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19880. groupIndex < groupLength;
  19881. groupIndex++) {
  19882. // list of options for that group. (first item has the parent)
  19883. optionGroup = optionGroupsCache[groupIndex];
  19884. for(index = 1, length = optionGroup.length; index < length; index++) {
  19885. if ((optionElement = optionGroup[index].element)[0].selected) {
  19886. key = optionElement.val();
  19887. if (keyName) locals[keyName] = key;
  19888. if (trackFn) {
  19889. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19890. locals[valueName] = collection[trackIndex];
  19891. if (trackFn(scope, locals) == key) break;
  19892. }
  19893. } else {
  19894. locals[valueName] = collection[key];
  19895. }
  19896. value.push(valueFn(scope, locals));
  19897. }
  19898. }
  19899. }
  19900. } else {
  19901. key = selectElement.val();
  19902. if (key == '?') {
  19903. value = undefined;
  19904. } else if (key === ''){
  19905. value = null;
  19906. } else {
  19907. if (trackFn) {
  19908. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19909. locals[valueName] = collection[trackIndex];
  19910. if (trackFn(scope, locals) == key) {
  19911. value = valueFn(scope, locals);
  19912. break;
  19913. }
  19914. }
  19915. } else {
  19916. locals[valueName] = collection[key];
  19917. if (keyName) locals[keyName] = key;
  19918. value = valueFn(scope, locals);
  19919. }
  19920. }
  19921. }
  19922. ctrl.$setViewValue(value);
  19923. render();
  19924. });
  19925. });
  19926. ctrl.$render = render;
  19927. scope.$watchCollection(valuesFn, render);
  19928. scope.$watchCollection(function () {
  19929. var locals = {},
  19930. values = valuesFn(scope);
  19931. if (values) {
  19932. var toDisplay = new Array(values.length);
  19933. for (var i = 0, ii = values.length; i < ii; i++) {
  19934. locals[valueName] = values[i];
  19935. toDisplay[i] = displayFn(scope, locals);
  19936. }
  19937. return toDisplay;
  19938. }
  19939. }, render);
  19940. if ( multiple ) {
  19941. scope.$watchCollection(function() { return ctrl.$modelValue; }, render);
  19942. }
  19943. function getSelectedSet() {
  19944. var selectedSet = false;
  19945. if (multiple) {
  19946. var modelValue = ctrl.$modelValue;
  19947. if (trackFn && isArray(modelValue)) {
  19948. selectedSet = new HashMap([]);
  19949. var locals = {};
  19950. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19951. locals[valueName] = modelValue[trackIndex];
  19952. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19953. }
  19954. } else {
  19955. selectedSet = new HashMap(modelValue);
  19956. }
  19957. }
  19958. return selectedSet;
  19959. }
  19960. function render() {
  19961. // Temporary location for the option groups before we render them
  19962. var optionGroups = {'':[]},
  19963. optionGroupNames = [''],
  19964. optionGroupName,
  19965. optionGroup,
  19966. option,
  19967. existingParent, existingOptions, existingOption,
  19968. modelValue = ctrl.$modelValue,
  19969. values = valuesFn(scope) || [],
  19970. keys = keyName ? sortedKeys(values) : values,
  19971. key,
  19972. groupLength, length,
  19973. groupIndex, index,
  19974. locals = {},
  19975. selected,
  19976. selectedSet = getSelectedSet(),
  19977. lastElement,
  19978. element,
  19979. label;
  19980. // We now build up the list of options we need (we merge later)
  19981. for (index = 0; length = keys.length, index < length; index++) {
  19982. key = index;
  19983. if (keyName) {
  19984. key = keys[index];
  19985. if ( key.charAt(0) === '$' ) continue;
  19986. locals[keyName] = key;
  19987. }
  19988. locals[valueName] = values[key];
  19989. optionGroupName = groupByFn(scope, locals) || '';
  19990. if (!(optionGroup = optionGroups[optionGroupName])) {
  19991. optionGroup = optionGroups[optionGroupName] = [];
  19992. optionGroupNames.push(optionGroupName);
  19993. }
  19994. if (multiple) {
  19995. selected = isDefined(
  19996. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  19997. );
  19998. } else {
  19999. if (trackFn) {
  20000. var modelCast = {};
  20001. modelCast[valueName] = modelValue;
  20002. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  20003. } else {
  20004. selected = modelValue === valueFn(scope, locals);
  20005. }
  20006. selectedSet = selectedSet || selected; // see if at least one item is selected
  20007. }
  20008. label = displayFn(scope, locals); // what will be seen by the user
  20009. // doing displayFn(scope, locals) || '' overwrites zero values
  20010. label = isDefined(label) ? label : '';
  20011. optionGroup.push({
  20012. // either the index into array or key from object
  20013. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  20014. label: label,
  20015. selected: selected // determine if we should be selected
  20016. });
  20017. }
  20018. if (!multiple) {
  20019. if (nullOption || modelValue === null) {
  20020. // insert null option if we have a placeholder, or the model is null
  20021. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  20022. } else if (!selectedSet) {
  20023. // option could not be found, we have to insert the undefined item
  20024. optionGroups[''].unshift({id:'?', label:'', selected:true});
  20025. }
  20026. }
  20027. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  20028. for (groupIndex = 0, groupLength = optionGroupNames.length;
  20029. groupIndex < groupLength;
  20030. groupIndex++) {
  20031. // current option group name or '' if no group
  20032. optionGroupName = optionGroupNames[groupIndex];
  20033. // list of options for that group. (first item has the parent)
  20034. optionGroup = optionGroups[optionGroupName];
  20035. if (optionGroupsCache.length <= groupIndex) {
  20036. // we need to grow the optionGroups
  20037. existingParent = {
  20038. element: optGroupTemplate.clone().attr('label', optionGroupName),
  20039. label: optionGroup.label
  20040. };
  20041. existingOptions = [existingParent];
  20042. optionGroupsCache.push(existingOptions);
  20043. selectElement.append(existingParent.element);
  20044. } else {
  20045. existingOptions = optionGroupsCache[groupIndex];
  20046. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  20047. // update the OPTGROUP label if not the same.
  20048. if (existingParent.label != optionGroupName) {
  20049. existingParent.element.attr('label', existingParent.label = optionGroupName);
  20050. }
  20051. }
  20052. lastElement = null; // start at the beginning
  20053. for(index = 0, length = optionGroup.length; index < length; index++) {
  20054. option = optionGroup[index];
  20055. if ((existingOption = existingOptions[index+1])) {
  20056. // reuse elements
  20057. lastElement = existingOption.element;
  20058. if (existingOption.label !== option.label) {
  20059. lastElement.text(existingOption.label = option.label);
  20060. lastElement.prop('label', existingOption.label);
  20061. }
  20062. if (existingOption.id !== option.id) {
  20063. lastElement.val(existingOption.id = option.id);
  20064. }
  20065. // lastElement.prop('selected') provided by jQuery has side-effects
  20066. if (lastElement[0].selected !== option.selected) {
  20067. lastElement.prop('selected', (existingOption.selected = option.selected));
  20068. if (msie) {
  20069. // See #7692
  20070. // The selected item wouldn't visually update on IE without this.
  20071. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  20072. lastElement.prop('selected', existingOption.selected);
  20073. }
  20074. }
  20075. } else {
  20076. // grow elements
  20077. // if it's a null option
  20078. if (option.id === '' && nullOption) {
  20079. // put back the pre-compiled element
  20080. element = nullOption;
  20081. } else {
  20082. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  20083. // in this version of jQuery on some browser the .text() returns a string
  20084. // rather then the element.
  20085. (element = optionTemplate.clone())
  20086. .val(option.id)
  20087. .prop('selected', option.selected)
  20088. .attr('selected', option.selected)
  20089. .prop('label', option.label)
  20090. .text(option.label);
  20091. }
  20092. existingOptions.push(existingOption = {
  20093. element: element,
  20094. label: option.label,
  20095. id: option.id,
  20096. selected: option.selected
  20097. });
  20098. selectCtrl.addOption(option.label, element);
  20099. if (lastElement) {
  20100. lastElement.after(element);
  20101. } else {
  20102. existingParent.element.append(element);
  20103. }
  20104. lastElement = element;
  20105. }
  20106. }
  20107. // remove any excessive OPTIONs in a group
  20108. index++; // increment since the existingOptions[0] is parent element not OPTION
  20109. while(existingOptions.length > index) {
  20110. option = existingOptions.pop();
  20111. selectCtrl.removeOption(option.label);
  20112. option.element.remove();
  20113. }
  20114. }
  20115. // remove any excessive OPTGROUPs from select
  20116. while(optionGroupsCache.length > groupIndex) {
  20117. optionGroupsCache.pop()[0].element.remove();
  20118. }
  20119. }
  20120. }
  20121. }
  20122. };
  20123. }];
  20124. var optionDirective = ['$interpolate', function($interpolate) {
  20125. var nullSelectCtrl = {
  20126. addOption: noop,
  20127. removeOption: noop
  20128. };
  20129. return {
  20130. restrict: 'E',
  20131. priority: 100,
  20132. compile: function(element, attr) {
  20133. if (isUndefined(attr.value)) {
  20134. var interpolateFn = $interpolate(element.text(), true);
  20135. if (!interpolateFn) {
  20136. attr.$set('value', element.text());
  20137. }
  20138. }
  20139. return function (scope, element, attr) {
  20140. var selectCtrlName = '$selectController',
  20141. parent = element.parent(),
  20142. selectCtrl = parent.data(selectCtrlName) ||
  20143. parent.parent().data(selectCtrlName); // in case we are in optgroup
  20144. if (selectCtrl && selectCtrl.databound) {
  20145. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  20146. // We don't want the view to drive the initialization of the model anyway.
  20147. element.prop('selected', false);
  20148. } else {
  20149. selectCtrl = nullSelectCtrl;
  20150. }
  20151. if (interpolateFn) {
  20152. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  20153. attr.$set('value', newVal);
  20154. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  20155. selectCtrl.addOption(newVal);
  20156. });
  20157. } else {
  20158. selectCtrl.addOption(attr.value);
  20159. }
  20160. element.on('$destroy', function() {
  20161. selectCtrl.removeOption(attr.value);
  20162. });
  20163. };
  20164. }
  20165. };
  20166. }];
  20167. var styleDirective = valueFn({
  20168. restrict: 'E',
  20169. terminal: true
  20170. });
  20171. if (window.angular.bootstrap) {
  20172. //AngularJS is already loaded, so we can return here...
  20173. console.log('WARNING: Tried to load angular more than once.');
  20174. return;
  20175. }
  20176. //try to bind to jquery now so that one can write angular.element().read()
  20177. //but we will rebind on bootstrap again.
  20178. bindJQuery();
  20179. publishExternalAPI(angular);
  20180. jqLite(document).ready(function() {
  20181. angularInit(document, bootstrap);
  20182. });
  20183. })(window, document);
  20184. !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>');