angular.js 770 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133
  1. /**
  2. * @license AngularJS v1.2.27
  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.27/' +
  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 /** holds major version number for IE or NaN for real browsers */
  219. msie,
  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.27', // all of these placeholder strings will be replaced by grunt's
  1790. major: 1, // package task
  1791. minor: 2,
  1792. dot: 27,
  1793. codeName: 'prime-factorization'
  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. $normalize: directiveNormalize,
  5290. /**
  5291. * @ngdoc method
  5292. * @name $compile.directive.Attributes#$addClass
  5293. * @kind function
  5294. *
  5295. * @description
  5296. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5297. * are enabled then an animation will be triggered for the class addition.
  5298. *
  5299. * @param {string} classVal The className value that will be added to the element
  5300. */
  5301. $addClass : function(classVal) {
  5302. if(classVal && classVal.length > 0) {
  5303. $animate.addClass(this.$$element, classVal);
  5304. }
  5305. },
  5306. /**
  5307. * @ngdoc method
  5308. * @name $compile.directive.Attributes#$removeClass
  5309. * @kind function
  5310. *
  5311. * @description
  5312. * Removes the CSS class value specified by the classVal parameter from the element. If
  5313. * animations are enabled then an animation will be triggered for the class removal.
  5314. *
  5315. * @param {string} classVal The className value that will be removed from the element
  5316. */
  5317. $removeClass : function(classVal) {
  5318. if(classVal && classVal.length > 0) {
  5319. $animate.removeClass(this.$$element, classVal);
  5320. }
  5321. },
  5322. /**
  5323. * @ngdoc method
  5324. * @name $compile.directive.Attributes#$updateClass
  5325. * @kind function
  5326. *
  5327. * @description
  5328. * Adds and removes the appropriate CSS class values to the element based on the difference
  5329. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5330. *
  5331. * @param {string} newClasses The current CSS className value
  5332. * @param {string} oldClasses The former CSS className value
  5333. */
  5334. $updateClass : function(newClasses, oldClasses) {
  5335. var toAdd = tokenDifference(newClasses, oldClasses);
  5336. var toRemove = tokenDifference(oldClasses, newClasses);
  5337. if(toAdd.length === 0) {
  5338. $animate.removeClass(this.$$element, toRemove);
  5339. } else if(toRemove.length === 0) {
  5340. $animate.addClass(this.$$element, toAdd);
  5341. } else {
  5342. $animate.setClass(this.$$element, toAdd, toRemove);
  5343. }
  5344. },
  5345. /**
  5346. * Set a normalized attribute on the element in a way such that all directives
  5347. * can share the attribute. This function properly handles boolean attributes.
  5348. * @param {string} key Normalized key. (ie ngAttribute)
  5349. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5350. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5351. * Defaults to true.
  5352. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5353. */
  5354. $set: function(key, value, writeAttr, attrName) {
  5355. // TODO: decide whether or not to throw an error if "class"
  5356. //is set through this function since it may cause $updateClass to
  5357. //become unstable.
  5358. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5359. normalizedVal,
  5360. nodeName;
  5361. if (booleanKey) {
  5362. this.$$element.prop(key, value);
  5363. attrName = booleanKey;
  5364. }
  5365. this[key] = value;
  5366. // translate normalized key to actual key
  5367. if (attrName) {
  5368. this.$attr[key] = attrName;
  5369. } else {
  5370. attrName = this.$attr[key];
  5371. if (!attrName) {
  5372. this.$attr[key] = attrName = snake_case(key, '-');
  5373. }
  5374. }
  5375. nodeName = nodeName_(this.$$element);
  5376. // sanitize a[href] and img[src] values
  5377. if ((nodeName === 'A' && key === 'href') ||
  5378. (nodeName === 'IMG' && key === 'src')) {
  5379. this[key] = value = $$sanitizeUri(value, key === 'src');
  5380. }
  5381. if (writeAttr !== false) {
  5382. if (value === null || value === undefined) {
  5383. this.$$element.removeAttr(attrName);
  5384. } else {
  5385. this.$$element.attr(attrName, value);
  5386. }
  5387. }
  5388. // fire observers
  5389. var $$observers = this.$$observers;
  5390. $$observers && forEach($$observers[key], function(fn) {
  5391. try {
  5392. fn(value);
  5393. } catch (e) {
  5394. $exceptionHandler(e);
  5395. }
  5396. });
  5397. },
  5398. /**
  5399. * @ngdoc method
  5400. * @name $compile.directive.Attributes#$observe
  5401. * @kind function
  5402. *
  5403. * @description
  5404. * Observes an interpolated attribute.
  5405. *
  5406. * The observer function will be invoked once during the next `$digest` following
  5407. * compilation. The observer is then invoked whenever the interpolated value
  5408. * changes.
  5409. *
  5410. * @param {string} key Normalized key. (ie ngAttribute) .
  5411. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5412. the interpolated value of the attribute changes.
  5413. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5414. * @returns {function()} the `fn` parameter.
  5415. */
  5416. $observe: function(key, fn) {
  5417. var attrs = this,
  5418. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5419. listeners = ($$observers[key] || ($$observers[key] = []));
  5420. listeners.push(fn);
  5421. $rootScope.$evalAsync(function() {
  5422. if (!listeners.$$inter) {
  5423. // no one registered attribute interpolation function, so lets call it manually
  5424. fn(attrs[key]);
  5425. }
  5426. });
  5427. return fn;
  5428. }
  5429. };
  5430. var startSymbol = $interpolate.startSymbol(),
  5431. endSymbol = $interpolate.endSymbol(),
  5432. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5433. ? identity
  5434. : function denormalizeTemplate(template) {
  5435. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5436. },
  5437. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5438. return compile;
  5439. //================================
  5440. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5441. previousCompileContext) {
  5442. if (!($compileNodes instanceof jqLite)) {
  5443. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5444. // modify it.
  5445. $compileNodes = jqLite($compileNodes);
  5446. }
  5447. // We can not compile top level text elements since text nodes can be merged and we will
  5448. // not be able to attach scope data to them, so we will wrap them in <span>
  5449. forEach($compileNodes, function(node, index){
  5450. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5451. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5452. }
  5453. });
  5454. var compositeLinkFn =
  5455. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5456. maxPriority, ignoreDirective, previousCompileContext);
  5457. safeAddClass($compileNodes, 'ng-scope');
  5458. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){
  5459. assertArg(scope, 'scope');
  5460. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5461. // and sometimes changes the structure of the DOM.
  5462. var $linkNode = cloneConnectFn
  5463. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5464. : $compileNodes;
  5465. forEach(transcludeControllers, function(instance, name) {
  5466. $linkNode.data('$' + name + 'Controller', instance);
  5467. });
  5468. // Attach scope only to non-text nodes.
  5469. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5470. var node = $linkNode[i],
  5471. nodeType = node.nodeType;
  5472. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5473. $linkNode.eq(i).data('$scope', scope);
  5474. }
  5475. }
  5476. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5477. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  5478. return $linkNode;
  5479. };
  5480. }
  5481. function safeAddClass($element, className) {
  5482. try {
  5483. $element.addClass(className);
  5484. } catch(e) {
  5485. // ignore, since it means that we are trying to set class on
  5486. // SVG element, where class name is read-only.
  5487. }
  5488. }
  5489. /**
  5490. * Compile function matches each node in nodeList against the directives. Once all directives
  5491. * for a particular node are collected their compile functions are executed. The compile
  5492. * functions return values - the linking functions - are combined into a composite linking
  5493. * function, which is the a linking function for the node.
  5494. *
  5495. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5496. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5497. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5498. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5499. * the rootElement must be set the jqLite collection of the compile root. This is
  5500. * needed so that the jqLite collection items can be replaced with widgets.
  5501. * @param {number=} maxPriority Max directive priority.
  5502. * @returns {Function} A composite linking function of all of the matched directives or null.
  5503. */
  5504. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5505. previousCompileContext) {
  5506. var linkFns = [],
  5507. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5508. for (var i = 0; i < nodeList.length; i++) {
  5509. attrs = new Attributes();
  5510. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5511. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5512. ignoreDirective);
  5513. nodeLinkFn = (directives.length)
  5514. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5515. null, [], [], previousCompileContext)
  5516. : null;
  5517. if (nodeLinkFn && nodeLinkFn.scope) {
  5518. safeAddClass(attrs.$$element, 'ng-scope');
  5519. }
  5520. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5521. !(childNodes = nodeList[i].childNodes) ||
  5522. !childNodes.length)
  5523. ? null
  5524. : compileNodes(childNodes,
  5525. nodeLinkFn ? (
  5526. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  5527. && nodeLinkFn.transclude) : transcludeFn);
  5528. linkFns.push(nodeLinkFn, childLinkFn);
  5529. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5530. //use the previous context only for the first element in the virtual group
  5531. previousCompileContext = null;
  5532. }
  5533. // return a linking function if we have found anything, null otherwise
  5534. return linkFnFound ? compositeLinkFn : null;
  5535. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  5536. var nodeLinkFn, childLinkFn, node, childScope, i, ii, n, childBoundTranscludeFn;
  5537. // copy nodeList so that linking doesn't break due to live list updates.
  5538. var nodeListLength = nodeList.length,
  5539. stableNodeList = new Array(nodeListLength);
  5540. for (i = 0; i < nodeListLength; i++) {
  5541. stableNodeList[i] = nodeList[i];
  5542. }
  5543. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5544. node = stableNodeList[n];
  5545. nodeLinkFn = linkFns[i++];
  5546. childLinkFn = linkFns[i++];
  5547. if (nodeLinkFn) {
  5548. if (nodeLinkFn.scope) {
  5549. childScope = scope.$new();
  5550. jqLite.data(node, '$scope', childScope);
  5551. } else {
  5552. childScope = scope;
  5553. }
  5554. if ( nodeLinkFn.transcludeOnThisElement ) {
  5555. childBoundTranscludeFn = createBoundTranscludeFn(scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  5556. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  5557. childBoundTranscludeFn = parentBoundTranscludeFn;
  5558. } else if (!parentBoundTranscludeFn && transcludeFn) {
  5559. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  5560. } else {
  5561. childBoundTranscludeFn = null;
  5562. }
  5563. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  5564. } else if (childLinkFn) {
  5565. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  5566. }
  5567. }
  5568. }
  5569. }
  5570. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  5571. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers) {
  5572. var scopeCreated = false;
  5573. if (!transcludedScope) {
  5574. transcludedScope = scope.$new();
  5575. transcludedScope.$$transcluded = true;
  5576. scopeCreated = true;
  5577. }
  5578. var clone = transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn);
  5579. if (scopeCreated) {
  5580. clone.on('$destroy', function() { transcludedScope.$destroy(); });
  5581. }
  5582. return clone;
  5583. };
  5584. return boundTranscludeFn;
  5585. }
  5586. /**
  5587. * Looks for directives on the given node and adds them to the directive collection which is
  5588. * sorted.
  5589. *
  5590. * @param node Node to search.
  5591. * @param directives An array to which the directives are added to. This array is sorted before
  5592. * the function returns.
  5593. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5594. * @param {number=} maxPriority Max directive priority.
  5595. */
  5596. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5597. var nodeType = node.nodeType,
  5598. attrsMap = attrs.$attr,
  5599. match,
  5600. className;
  5601. switch(nodeType) {
  5602. case 1: /* Element */
  5603. // use the node name: <directive>
  5604. addDirective(directives,
  5605. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5606. // iterate over the attributes
  5607. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  5608. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5609. var attrStartName = false;
  5610. var attrEndName = false;
  5611. attr = nAttrs[j];
  5612. if (!msie || msie >= 8 || attr.specified) {
  5613. name = attr.name;
  5614. value = trim(attr.value);
  5615. // support ngAttr attribute binding
  5616. ngAttrName = directiveNormalize(name);
  5617. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  5618. name = snake_case(ngAttrName.substr(6), '-');
  5619. }
  5620. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5621. if (ngAttrName === directiveNName + 'Start') {
  5622. attrStartName = name;
  5623. attrEndName = name.substr(0, name.length - 5) + 'end';
  5624. name = name.substr(0, name.length - 6);
  5625. }
  5626. nName = directiveNormalize(name.toLowerCase());
  5627. attrsMap[nName] = name;
  5628. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  5629. attrs[nName] = value;
  5630. if (getBooleanAttrName(node, nName)) {
  5631. attrs[nName] = true; // presence means true
  5632. }
  5633. }
  5634. addAttrInterpolateDirective(node, directives, value, nName);
  5635. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5636. attrEndName);
  5637. }
  5638. }
  5639. // use class as directive
  5640. className = node.className;
  5641. if (isString(className) && className !== '') {
  5642. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5643. nName = directiveNormalize(match[2]);
  5644. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5645. attrs[nName] = trim(match[3]);
  5646. }
  5647. className = className.substr(match.index + match[0].length);
  5648. }
  5649. }
  5650. break;
  5651. case 3: /* Text Node */
  5652. addTextInterpolateDirective(directives, node.nodeValue);
  5653. break;
  5654. case 8: /* Comment */
  5655. try {
  5656. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5657. if (match) {
  5658. nName = directiveNormalize(match[1]);
  5659. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5660. attrs[nName] = trim(match[2]);
  5661. }
  5662. }
  5663. } catch (e) {
  5664. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5665. // comment's node value.
  5666. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5667. }
  5668. break;
  5669. }
  5670. directives.sort(byPriority);
  5671. return directives;
  5672. }
  5673. /**
  5674. * Given a node with an directive-start it collects all of the siblings until it finds
  5675. * directive-end.
  5676. * @param node
  5677. * @param attrStart
  5678. * @param attrEnd
  5679. * @returns {*}
  5680. */
  5681. function groupScan(node, attrStart, attrEnd) {
  5682. var nodes = [];
  5683. var depth = 0;
  5684. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5685. var startNode = node;
  5686. do {
  5687. if (!node) {
  5688. throw $compileMinErr('uterdir',
  5689. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5690. attrStart, attrEnd);
  5691. }
  5692. if (node.nodeType == 1 /** Element **/) {
  5693. if (node.hasAttribute(attrStart)) depth++;
  5694. if (node.hasAttribute(attrEnd)) depth--;
  5695. }
  5696. nodes.push(node);
  5697. node = node.nextSibling;
  5698. } while (depth > 0);
  5699. } else {
  5700. nodes.push(node);
  5701. }
  5702. return jqLite(nodes);
  5703. }
  5704. /**
  5705. * Wrapper for linking function which converts normal linking function into a grouped
  5706. * linking function.
  5707. * @param linkFn
  5708. * @param attrStart
  5709. * @param attrEnd
  5710. * @returns {Function}
  5711. */
  5712. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5713. return function(scope, element, attrs, controllers, transcludeFn) {
  5714. element = groupScan(element[0], attrStart, attrEnd);
  5715. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5716. };
  5717. }
  5718. /**
  5719. * Once the directives have been collected, their compile functions are executed. This method
  5720. * is responsible for inlining directive templates as well as terminating the application
  5721. * of the directives if the terminal directive has been reached.
  5722. *
  5723. * @param {Array} directives Array of collected directives to execute their compile function.
  5724. * this needs to be pre-sorted by priority order.
  5725. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5726. * @param {Object} templateAttrs The shared attribute function
  5727. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5728. * scope argument is auto-generated to the new
  5729. * child of the transcluded parent scope.
  5730. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5731. * argument has the root jqLite array so that we can replace nodes
  5732. * on it.
  5733. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5734. * compiling the transclusion.
  5735. * @param {Array.<Function>} preLinkFns
  5736. * @param {Array.<Function>} postLinkFns
  5737. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5738. * node
  5739. * @returns {Function} linkFn
  5740. */
  5741. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5742. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5743. previousCompileContext) {
  5744. previousCompileContext = previousCompileContext || {};
  5745. var terminalPriority = -Number.MAX_VALUE,
  5746. newScopeDirective,
  5747. controllerDirectives = previousCompileContext.controllerDirectives,
  5748. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5749. templateDirective = previousCompileContext.templateDirective,
  5750. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5751. hasTranscludeDirective = false,
  5752. hasTemplate = false,
  5753. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5754. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5755. directive,
  5756. directiveName,
  5757. $template,
  5758. replaceDirective = originalReplaceDirective,
  5759. childTranscludeFn = transcludeFn,
  5760. linkFn,
  5761. directiveValue;
  5762. // executes all directives on the current element
  5763. for(var i = 0, ii = directives.length; i < ii; i++) {
  5764. directive = directives[i];
  5765. var attrStart = directive.$$start;
  5766. var attrEnd = directive.$$end;
  5767. // collect multiblock sections
  5768. if (attrStart) {
  5769. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5770. }
  5771. $template = undefined;
  5772. if (terminalPriority > directive.priority) {
  5773. break; // prevent further processing of directives
  5774. }
  5775. if (directiveValue = directive.scope) {
  5776. newScopeDirective = newScopeDirective || directive;
  5777. // skip the check for directives with async templates, we'll check the derived sync
  5778. // directive when the template arrives
  5779. if (!directive.templateUrl) {
  5780. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5781. $compileNode);
  5782. if (isObject(directiveValue)) {
  5783. newIsolateScopeDirective = directive;
  5784. }
  5785. }
  5786. }
  5787. directiveName = directive.name;
  5788. if (!directive.templateUrl && directive.controller) {
  5789. directiveValue = directive.controller;
  5790. controllerDirectives = controllerDirectives || {};
  5791. assertNoDuplicate("'" + directiveName + "' controller",
  5792. controllerDirectives[directiveName], directive, $compileNode);
  5793. controllerDirectives[directiveName] = directive;
  5794. }
  5795. if (directiveValue = directive.transclude) {
  5796. hasTranscludeDirective = true;
  5797. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5798. // This option should only be used by directives that know how to safely handle element transclusion,
  5799. // where the transcluded nodes are added or replaced after linking.
  5800. if (!directive.$$tlb) {
  5801. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5802. nonTlbTranscludeDirective = directive;
  5803. }
  5804. if (directiveValue == 'element') {
  5805. hasElementTranscludeDirective = true;
  5806. terminalPriority = directive.priority;
  5807. $template = $compileNode;
  5808. $compileNode = templateAttrs.$$element =
  5809. jqLite(document.createComment(' ' + directiveName + ': ' +
  5810. templateAttrs[directiveName] + ' '));
  5811. compileNode = $compileNode[0];
  5812. replaceWith(jqCollection, sliceArgs($template), compileNode);
  5813. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5814. replaceDirective && replaceDirective.name, {
  5815. // Don't pass in:
  5816. // - controllerDirectives - otherwise we'll create duplicates controllers
  5817. // - newIsolateScopeDirective or templateDirective - combining templates with
  5818. // element transclusion doesn't make sense.
  5819. //
  5820. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5821. // on the same element more than once.
  5822. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5823. });
  5824. } else {
  5825. $template = jqLite(jqLiteClone(compileNode)).contents();
  5826. $compileNode.empty(); // clear contents
  5827. childTranscludeFn = compile($template, transcludeFn);
  5828. }
  5829. }
  5830. if (directive.template) {
  5831. hasTemplate = true;
  5832. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5833. templateDirective = directive;
  5834. directiveValue = (isFunction(directive.template))
  5835. ? directive.template($compileNode, templateAttrs)
  5836. : directive.template;
  5837. directiveValue = denormalizeTemplate(directiveValue);
  5838. if (directive.replace) {
  5839. replaceDirective = directive;
  5840. if (jqLiteIsTextNode(directiveValue)) {
  5841. $template = [];
  5842. } else {
  5843. $template = jqLite(trim(directiveValue));
  5844. }
  5845. compileNode = $template[0];
  5846. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5847. throw $compileMinErr('tplrt',
  5848. "Template for directive '{0}' must have exactly one root element. {1}",
  5849. directiveName, '');
  5850. }
  5851. replaceWith(jqCollection, $compileNode, compileNode);
  5852. var newTemplateAttrs = {$attr: {}};
  5853. // combine directives from the original node and from the template:
  5854. // - take the array of directives for this element
  5855. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5856. // - collect directives from the template and sort them by priority
  5857. // - combine directives as: processed + template + unprocessed
  5858. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5859. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5860. if (newIsolateScopeDirective) {
  5861. markDirectivesAsIsolate(templateDirectives);
  5862. }
  5863. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5864. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5865. ii = directives.length;
  5866. } else {
  5867. $compileNode.html(directiveValue);
  5868. }
  5869. }
  5870. if (directive.templateUrl) {
  5871. hasTemplate = true;
  5872. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5873. templateDirective = directive;
  5874. if (directive.replace) {
  5875. replaceDirective = directive;
  5876. }
  5877. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5878. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  5879. controllerDirectives: controllerDirectives,
  5880. newIsolateScopeDirective: newIsolateScopeDirective,
  5881. templateDirective: templateDirective,
  5882. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5883. });
  5884. ii = directives.length;
  5885. } else if (directive.compile) {
  5886. try {
  5887. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5888. if (isFunction(linkFn)) {
  5889. addLinkFns(null, linkFn, attrStart, attrEnd);
  5890. } else if (linkFn) {
  5891. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5892. }
  5893. } catch (e) {
  5894. $exceptionHandler(e, startingTag($compileNode));
  5895. }
  5896. }
  5897. if (directive.terminal) {
  5898. nodeLinkFn.terminal = true;
  5899. terminalPriority = Math.max(terminalPriority, directive.priority);
  5900. }
  5901. }
  5902. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5903. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  5904. nodeLinkFn.templateOnThisElement = hasTemplate;
  5905. nodeLinkFn.transclude = childTranscludeFn;
  5906. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5907. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5908. return nodeLinkFn;
  5909. ////////////////////
  5910. function addLinkFns(pre, post, attrStart, attrEnd) {
  5911. if (pre) {
  5912. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5913. pre.require = directive.require;
  5914. pre.directiveName = directiveName;
  5915. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5916. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5917. }
  5918. preLinkFns.push(pre);
  5919. }
  5920. if (post) {
  5921. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5922. post.require = directive.require;
  5923. post.directiveName = directiveName;
  5924. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5925. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5926. }
  5927. postLinkFns.push(post);
  5928. }
  5929. }
  5930. function getControllers(directiveName, require, $element, elementControllers) {
  5931. var value, retrievalMethod = 'data', optional = false;
  5932. if (isString(require)) {
  5933. while((value = require.charAt(0)) == '^' || value == '?') {
  5934. require = require.substr(1);
  5935. if (value == '^') {
  5936. retrievalMethod = 'inheritedData';
  5937. }
  5938. optional = optional || value == '?';
  5939. }
  5940. value = null;
  5941. if (elementControllers && retrievalMethod === 'data') {
  5942. value = elementControllers[require];
  5943. }
  5944. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5945. if (!value && !optional) {
  5946. throw $compileMinErr('ctreq',
  5947. "Controller '{0}', required by directive '{1}', can't be found!",
  5948. require, directiveName);
  5949. }
  5950. return value;
  5951. } else if (isArray(require)) {
  5952. value = [];
  5953. forEach(require, function(require) {
  5954. value.push(getControllers(directiveName, require, $element, elementControllers));
  5955. });
  5956. }
  5957. return value;
  5958. }
  5959. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5960. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5961. attrs = (compileNode === linkNode)
  5962. ? templateAttrs
  5963. : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5964. $element = attrs.$$element;
  5965. if (newIsolateScopeDirective) {
  5966. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5967. isolateScope = scope.$new(true);
  5968. if (templateDirective && (templateDirective === newIsolateScopeDirective ||
  5969. templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5970. $element.data('$isolateScope', isolateScope);
  5971. } else {
  5972. $element.data('$isolateScopeNoTemplate', isolateScope);
  5973. }
  5974. safeAddClass($element, 'ng-isolate-scope');
  5975. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5976. var match = definition.match(LOCAL_REGEXP) || [],
  5977. attrName = match[3] || scopeName,
  5978. optional = (match[2] == '?'),
  5979. mode = match[1], // @, =, or &
  5980. lastValue,
  5981. parentGet, parentSet, compare;
  5982. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5983. switch (mode) {
  5984. case '@':
  5985. attrs.$observe(attrName, function(value) {
  5986. isolateScope[scopeName] = value;
  5987. });
  5988. attrs.$$observers[attrName].$$scope = scope;
  5989. if( attrs[attrName] ) {
  5990. // If the attribute has been provided then we trigger an interpolation to ensure
  5991. // the value is there for use in the link fn
  5992. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5993. }
  5994. break;
  5995. case '=':
  5996. if (optional && !attrs[attrName]) {
  5997. return;
  5998. }
  5999. parentGet = $parse(attrs[attrName]);
  6000. if (parentGet.literal) {
  6001. compare = equals;
  6002. } else {
  6003. compare = function(a,b) { return a === b || (a !== a && b !== b); };
  6004. }
  6005. parentSet = parentGet.assign || function() {
  6006. // reset the change, or we will throw this exception on every $digest
  6007. lastValue = isolateScope[scopeName] = parentGet(scope);
  6008. throw $compileMinErr('nonassign',
  6009. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6010. attrs[attrName], newIsolateScopeDirective.name);
  6011. };
  6012. lastValue = isolateScope[scopeName] = parentGet(scope);
  6013. isolateScope.$watch(function parentValueWatch() {
  6014. var parentValue = parentGet(scope);
  6015. if (!compare(parentValue, isolateScope[scopeName])) {
  6016. // we are out of sync and need to copy
  6017. if (!compare(parentValue, lastValue)) {
  6018. // parent changed and it has precedence
  6019. isolateScope[scopeName] = parentValue;
  6020. } else {
  6021. // if the parent can be assigned then do so
  6022. parentSet(scope, parentValue = isolateScope[scopeName]);
  6023. }
  6024. }
  6025. return lastValue = parentValue;
  6026. }, null, parentGet.literal);
  6027. break;
  6028. case '&':
  6029. parentGet = $parse(attrs[attrName]);
  6030. isolateScope[scopeName] = function(locals) {
  6031. return parentGet(scope, locals);
  6032. };
  6033. break;
  6034. default:
  6035. throw $compileMinErr('iscp',
  6036. "Invalid isolate scope definition for directive '{0}'." +
  6037. " Definition: {... {1}: '{2}' ...}",
  6038. newIsolateScopeDirective.name, scopeName, definition);
  6039. }
  6040. });
  6041. }
  6042. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  6043. if (controllerDirectives) {
  6044. forEach(controllerDirectives, function(directive) {
  6045. var locals = {
  6046. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6047. $element: $element,
  6048. $attrs: attrs,
  6049. $transclude: transcludeFn
  6050. }, controllerInstance;
  6051. controller = directive.controller;
  6052. if (controller == '@') {
  6053. controller = attrs[directive.name];
  6054. }
  6055. controllerInstance = $controller(controller, locals);
  6056. // For directives with element transclusion the element is a comment,
  6057. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6058. // clean up (http://bugs.jquery.com/ticket/8335).
  6059. // Instead, we save the controllers for the element in a local hash and attach to .data
  6060. // later, once we have the actual element.
  6061. elementControllers[directive.name] = controllerInstance;
  6062. if (!hasElementTranscludeDirective) {
  6063. $element.data('$' + directive.name + 'Controller', controllerInstance);
  6064. }
  6065. if (directive.controllerAs) {
  6066. locals.$scope[directive.controllerAs] = controllerInstance;
  6067. }
  6068. });
  6069. }
  6070. // PRELINKING
  6071. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  6072. try {
  6073. linkFn = preLinkFns[i];
  6074. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6075. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6076. } catch (e) {
  6077. $exceptionHandler(e, startingTag($element));
  6078. }
  6079. }
  6080. // RECURSION
  6081. // We only pass the isolate scope, if the isolate directive has a template,
  6082. // otherwise the child elements do not belong to the isolate directive.
  6083. var scopeToChild = scope;
  6084. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6085. scopeToChild = isolateScope;
  6086. }
  6087. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6088. // POSTLINKING
  6089. for(i = postLinkFns.length - 1; i >= 0; i--) {
  6090. try {
  6091. linkFn = postLinkFns[i];
  6092. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6093. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6094. } catch (e) {
  6095. $exceptionHandler(e, startingTag($element));
  6096. }
  6097. }
  6098. // This is the function that is injected as `$transclude`.
  6099. function controllersBoundTransclude(scope, cloneAttachFn) {
  6100. var transcludeControllers;
  6101. // no scope passed
  6102. if (arguments.length < 2) {
  6103. cloneAttachFn = scope;
  6104. scope = undefined;
  6105. }
  6106. if (hasElementTranscludeDirective) {
  6107. transcludeControllers = elementControllers;
  6108. }
  6109. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  6110. }
  6111. }
  6112. }
  6113. function markDirectivesAsIsolate(directives) {
  6114. // mark all directives as needing isolate scope.
  6115. for (var j = 0, jj = directives.length; j < jj; j++) {
  6116. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6117. }
  6118. }
  6119. /**
  6120. * looks up the directive and decorates it with exception handling and proper parameters. We
  6121. * call this the boundDirective.
  6122. *
  6123. * @param {string} name name of the directive to look up.
  6124. * @param {string} location The directive must be found in specific format.
  6125. * String containing any of theses characters:
  6126. *
  6127. * * `E`: element name
  6128. * * `A': attribute
  6129. * * `C`: class
  6130. * * `M`: comment
  6131. * @returns {boolean} true if directive was added.
  6132. */
  6133. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6134. endAttrName) {
  6135. if (name === ignoreDirective) return null;
  6136. var match = null;
  6137. if (hasDirectives.hasOwnProperty(name)) {
  6138. for(var directive, directives = $injector.get(name + Suffix),
  6139. i = 0, ii = directives.length; i<ii; i++) {
  6140. try {
  6141. directive = directives[i];
  6142. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6143. directive.restrict.indexOf(location) != -1) {
  6144. if (startAttrName) {
  6145. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6146. }
  6147. tDirectives.push(directive);
  6148. match = directive;
  6149. }
  6150. } catch(e) { $exceptionHandler(e); }
  6151. }
  6152. }
  6153. return match;
  6154. }
  6155. /**
  6156. * When the element is replaced with HTML template then the new attributes
  6157. * on the template need to be merged with the existing attributes in the DOM.
  6158. * The desired effect is to have both of the attributes present.
  6159. *
  6160. * @param {object} dst destination attributes (original DOM)
  6161. * @param {object} src source attributes (from the directive template)
  6162. */
  6163. function mergeTemplateAttributes(dst, src) {
  6164. var srcAttr = src.$attr,
  6165. dstAttr = dst.$attr,
  6166. $element = dst.$$element;
  6167. // reapply the old attributes to the new element
  6168. forEach(dst, function(value, key) {
  6169. if (key.charAt(0) != '$') {
  6170. if (src[key] && src[key] !== value) {
  6171. value += (key === 'style' ? ';' : ' ') + src[key];
  6172. }
  6173. dst.$set(key, value, true, srcAttr[key]);
  6174. }
  6175. });
  6176. // copy the new attributes on the old attrs object
  6177. forEach(src, function(value, key) {
  6178. if (key == 'class') {
  6179. safeAddClass($element, value);
  6180. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6181. } else if (key == 'style') {
  6182. $element.attr('style', $element.attr('style') + ';' + value);
  6183. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6184. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6185. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6186. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6187. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6188. dst[key] = value;
  6189. dstAttr[key] = srcAttr[key];
  6190. }
  6191. });
  6192. }
  6193. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6194. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6195. var linkQueue = [],
  6196. afterTemplateNodeLinkFn,
  6197. afterTemplateChildLinkFn,
  6198. beforeTemplateCompileNode = $compileNode[0],
  6199. origAsyncDirective = directives.shift(),
  6200. // The fact that we have to copy and patch the directive seems wrong!
  6201. derivedSyncDirective = extend({}, origAsyncDirective, {
  6202. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6203. }),
  6204. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6205. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6206. : origAsyncDirective.templateUrl;
  6207. $compileNode.empty();
  6208. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6209. success(function(content) {
  6210. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6211. content = denormalizeTemplate(content);
  6212. if (origAsyncDirective.replace) {
  6213. if (jqLiteIsTextNode(content)) {
  6214. $template = [];
  6215. } else {
  6216. $template = jqLite(trim(content));
  6217. }
  6218. compileNode = $template[0];
  6219. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6220. throw $compileMinErr('tplrt',
  6221. "Template for directive '{0}' must have exactly one root element. {1}",
  6222. origAsyncDirective.name, templateUrl);
  6223. }
  6224. tempTemplateAttrs = {$attr: {}};
  6225. replaceWith($rootElement, $compileNode, compileNode);
  6226. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6227. if (isObject(origAsyncDirective.scope)) {
  6228. markDirectivesAsIsolate(templateDirectives);
  6229. }
  6230. directives = templateDirectives.concat(directives);
  6231. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6232. } else {
  6233. compileNode = beforeTemplateCompileNode;
  6234. $compileNode.html(content);
  6235. }
  6236. directives.unshift(derivedSyncDirective);
  6237. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6238. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6239. previousCompileContext);
  6240. forEach($rootElement, function(node, i) {
  6241. if (node == compileNode) {
  6242. $rootElement[i] = $compileNode[0];
  6243. }
  6244. });
  6245. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6246. while(linkQueue.length) {
  6247. var scope = linkQueue.shift(),
  6248. beforeTemplateLinkNode = linkQueue.shift(),
  6249. linkRootElement = linkQueue.shift(),
  6250. boundTranscludeFn = linkQueue.shift(),
  6251. linkNode = $compileNode[0];
  6252. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6253. var oldClasses = beforeTemplateLinkNode.className;
  6254. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6255. origAsyncDirective.replace)) {
  6256. // it was cloned therefore we have to clone as well.
  6257. linkNode = jqLiteClone(compileNode);
  6258. }
  6259. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6260. // Copy in CSS classes from original node
  6261. safeAddClass(jqLite(linkNode), oldClasses);
  6262. }
  6263. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6264. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6265. } else {
  6266. childBoundTranscludeFn = boundTranscludeFn;
  6267. }
  6268. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6269. childBoundTranscludeFn);
  6270. }
  6271. linkQueue = null;
  6272. }).
  6273. error(function(response, code, headers, config) {
  6274. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6275. });
  6276. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6277. var childBoundTranscludeFn = boundTranscludeFn;
  6278. if (linkQueue) {
  6279. linkQueue.push(scope);
  6280. linkQueue.push(node);
  6281. linkQueue.push(rootElement);
  6282. linkQueue.push(childBoundTranscludeFn);
  6283. } else {
  6284. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6285. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6286. }
  6287. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  6288. }
  6289. };
  6290. }
  6291. /**
  6292. * Sorting function for bound directives.
  6293. */
  6294. function byPriority(a, b) {
  6295. var diff = b.priority - a.priority;
  6296. if (diff !== 0) return diff;
  6297. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6298. return a.index - b.index;
  6299. }
  6300. function assertNoDuplicate(what, previousDirective, directive, element) {
  6301. if (previousDirective) {
  6302. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6303. previousDirective.name, directive.name, what, startingTag(element));
  6304. }
  6305. }
  6306. function addTextInterpolateDirective(directives, text) {
  6307. var interpolateFn = $interpolate(text, true);
  6308. if (interpolateFn) {
  6309. directives.push({
  6310. priority: 0,
  6311. compile: function textInterpolateCompileFn(templateNode) {
  6312. // when transcluding a template that has bindings in the root
  6313. // then we don't have a parent and should do this in the linkFn
  6314. var parent = templateNode.parent(), hasCompileParent = parent.length;
  6315. if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding');
  6316. return function textInterpolateLinkFn(scope, node) {
  6317. var parent = node.parent(),
  6318. bindings = parent.data('$binding') || [];
  6319. bindings.push(interpolateFn);
  6320. parent.data('$binding', bindings);
  6321. if (!hasCompileParent) safeAddClass(parent, 'ng-binding');
  6322. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6323. node[0].nodeValue = value;
  6324. });
  6325. };
  6326. }
  6327. });
  6328. }
  6329. }
  6330. function getTrustedContext(node, attrNormalizedName) {
  6331. if (attrNormalizedName == "srcdoc") {
  6332. return $sce.HTML;
  6333. }
  6334. var tag = nodeName_(node);
  6335. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6336. if (attrNormalizedName == "xlinkHref" ||
  6337. (tag == "FORM" && attrNormalizedName == "action") ||
  6338. (tag != "IMG" && (attrNormalizedName == "src" ||
  6339. attrNormalizedName == "ngSrc"))) {
  6340. return $sce.RESOURCE_URL;
  6341. }
  6342. }
  6343. function addAttrInterpolateDirective(node, directives, value, name) {
  6344. var interpolateFn = $interpolate(value, true);
  6345. // no interpolation found -> ignore
  6346. if (!interpolateFn) return;
  6347. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6348. throw $compileMinErr("selmulti",
  6349. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6350. startingTag(node));
  6351. }
  6352. directives.push({
  6353. priority: 100,
  6354. compile: function() {
  6355. return {
  6356. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6357. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6358. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6359. throw $compileMinErr('nodomevents',
  6360. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6361. "ng- versions (such as ng-click instead of onclick) instead.");
  6362. }
  6363. // we need to interpolate again, in case the attribute value has been updated
  6364. // (e.g. by another directive's compile function)
  6365. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6366. // if attribute was updated so that there is no interpolation going on we don't want to
  6367. // register any observers
  6368. if (!interpolateFn) return;
  6369. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6370. // actual attr value
  6371. attr[name] = interpolateFn(scope);
  6372. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6373. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6374. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6375. //special case for class attribute addition + removal
  6376. //so that class changes can tap into the animation
  6377. //hooks provided by the $animate service. Be sure to
  6378. //skip animations when the first digest occurs (when
  6379. //both the new and the old values are the same) since
  6380. //the CSS classes are the non-interpolated values
  6381. if(name === 'class' && newValue != oldValue) {
  6382. attr.$updateClass(newValue, oldValue);
  6383. } else {
  6384. attr.$set(name, newValue);
  6385. }
  6386. });
  6387. }
  6388. };
  6389. }
  6390. });
  6391. }
  6392. /**
  6393. * This is a special jqLite.replaceWith, which can replace items which
  6394. * have no parents, provided that the containing jqLite collection is provided.
  6395. *
  6396. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6397. * in the root of the tree.
  6398. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6399. * the shell, but replace its DOM node reference.
  6400. * @param {Node} newNode The new DOM node.
  6401. */
  6402. function replaceWith($rootElement, elementsToRemove, newNode) {
  6403. var firstElementToRemove = elementsToRemove[0],
  6404. removeCount = elementsToRemove.length,
  6405. parent = firstElementToRemove.parentNode,
  6406. i, ii;
  6407. if ($rootElement) {
  6408. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6409. if ($rootElement[i] == firstElementToRemove) {
  6410. $rootElement[i++] = newNode;
  6411. for (var j = i, j2 = j + removeCount - 1,
  6412. jj = $rootElement.length;
  6413. j < jj; j++, j2++) {
  6414. if (j2 < jj) {
  6415. $rootElement[j] = $rootElement[j2];
  6416. } else {
  6417. delete $rootElement[j];
  6418. }
  6419. }
  6420. $rootElement.length -= removeCount - 1;
  6421. break;
  6422. }
  6423. }
  6424. }
  6425. if (parent) {
  6426. parent.replaceChild(newNode, firstElementToRemove);
  6427. }
  6428. var fragment = document.createDocumentFragment();
  6429. fragment.appendChild(firstElementToRemove);
  6430. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6431. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6432. var element = elementsToRemove[k];
  6433. jqLite(element).remove(); // must do this way to clean up expando
  6434. fragment.appendChild(element);
  6435. delete elementsToRemove[k];
  6436. }
  6437. elementsToRemove[0] = newNode;
  6438. elementsToRemove.length = 1;
  6439. }
  6440. function cloneAndAnnotateFn(fn, annotation) {
  6441. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6442. }
  6443. }];
  6444. }
  6445. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6446. /**
  6447. * Converts all accepted directives format into proper directive name.
  6448. * All of these will become 'myDirective':
  6449. * my:Directive
  6450. * my-directive
  6451. * x-my-directive
  6452. * data-my:directive
  6453. *
  6454. * Also there is special case for Moz prefix starting with upper case letter.
  6455. * @param name Name to normalize
  6456. */
  6457. function directiveNormalize(name) {
  6458. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6459. }
  6460. /**
  6461. * @ngdoc type
  6462. * @name $compile.directive.Attributes
  6463. *
  6464. * @description
  6465. * A shared object between directive compile / linking functions which contains normalized DOM
  6466. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6467. * needed since all of these are treated as equivalent in Angular:
  6468. *
  6469. * ```
  6470. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6471. * ```
  6472. */
  6473. /**
  6474. * @ngdoc property
  6475. * @name $compile.directive.Attributes#$attr
  6476. *
  6477. * @description
  6478. * A map of DOM element attribute names to the normalized name. This is
  6479. * needed to do reverse lookup from normalized name back to actual name.
  6480. */
  6481. /**
  6482. * @ngdoc method
  6483. * @name $compile.directive.Attributes#$set
  6484. * @kind function
  6485. *
  6486. * @description
  6487. * Set DOM element attribute value.
  6488. *
  6489. *
  6490. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6491. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6492. * property to the original name.
  6493. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6494. */
  6495. /**
  6496. * Closure compiler type information
  6497. */
  6498. function nodesetLinkingFn(
  6499. /* angular.Scope */ scope,
  6500. /* NodeList */ nodeList,
  6501. /* Element */ rootElement,
  6502. /* function(Function) */ boundTranscludeFn
  6503. ){}
  6504. function directiveLinkingFn(
  6505. /* nodesetLinkingFn */ nodesetLinkingFn,
  6506. /* angular.Scope */ scope,
  6507. /* Node */ node,
  6508. /* Element */ rootElement,
  6509. /* function(Function) */ boundTranscludeFn
  6510. ){}
  6511. function tokenDifference(str1, str2) {
  6512. var values = '',
  6513. tokens1 = str1.split(/\s+/),
  6514. tokens2 = str2.split(/\s+/);
  6515. outer:
  6516. for(var i = 0; i < tokens1.length; i++) {
  6517. var token = tokens1[i];
  6518. for(var j = 0; j < tokens2.length; j++) {
  6519. if(token == tokens2[j]) continue outer;
  6520. }
  6521. values += (values.length > 0 ? ' ' : '') + token;
  6522. }
  6523. return values;
  6524. }
  6525. /**
  6526. * @ngdoc provider
  6527. * @name $controllerProvider
  6528. * @description
  6529. * The {@link ng.$controller $controller service} is used by Angular to create new
  6530. * controllers.
  6531. *
  6532. * This provider allows controller registration via the
  6533. * {@link ng.$controllerProvider#register register} method.
  6534. */
  6535. function $ControllerProvider() {
  6536. var controllers = {},
  6537. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6538. /**
  6539. * @ngdoc method
  6540. * @name $controllerProvider#register
  6541. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6542. * the names and the values are the constructors.
  6543. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6544. * annotations in the array notation).
  6545. */
  6546. this.register = function(name, constructor) {
  6547. assertNotHasOwnProperty(name, 'controller');
  6548. if (isObject(name)) {
  6549. extend(controllers, name);
  6550. } else {
  6551. controllers[name] = constructor;
  6552. }
  6553. };
  6554. this.$get = ['$injector', '$window', function($injector, $window) {
  6555. /**
  6556. * @ngdoc service
  6557. * @name $controller
  6558. * @requires $injector
  6559. *
  6560. * @param {Function|string} constructor If called with a function then it's considered to be the
  6561. * controller constructor function. Otherwise it's considered to be a string which is used
  6562. * to retrieve the controller constructor using the following steps:
  6563. *
  6564. * * check if a controller with given name is registered via `$controllerProvider`
  6565. * * check if evaluating the string on the current scope returns a constructor
  6566. * * check `window[constructor]` on the global `window` object
  6567. *
  6568. * @param {Object} locals Injection locals for Controller.
  6569. * @return {Object} Instance of given controller.
  6570. *
  6571. * @description
  6572. * `$controller` service is responsible for instantiating controllers.
  6573. *
  6574. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6575. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6576. */
  6577. return function(expression, locals) {
  6578. var instance, match, constructor, identifier;
  6579. if(isString(expression)) {
  6580. match = expression.match(CNTRL_REG),
  6581. constructor = match[1],
  6582. identifier = match[3];
  6583. expression = controllers.hasOwnProperty(constructor)
  6584. ? controllers[constructor]
  6585. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6586. assertArgFn(expression, constructor, true);
  6587. }
  6588. instance = $injector.instantiate(expression, locals);
  6589. if (identifier) {
  6590. if (!(locals && typeof locals.$scope === 'object')) {
  6591. throw minErr('$controller')('noscp',
  6592. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6593. constructor || expression.name, identifier);
  6594. }
  6595. locals.$scope[identifier] = instance;
  6596. }
  6597. return instance;
  6598. };
  6599. }];
  6600. }
  6601. /**
  6602. * @ngdoc service
  6603. * @name $document
  6604. * @requires $window
  6605. *
  6606. * @description
  6607. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6608. *
  6609. * @example
  6610. <example module="documentExample">
  6611. <file name="index.html">
  6612. <div ng-controller="ExampleController">
  6613. <p>$document title: <b ng-bind="title"></b></p>
  6614. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6615. </div>
  6616. </file>
  6617. <file name="script.js">
  6618. angular.module('documentExample', [])
  6619. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  6620. $scope.title = $document[0].title;
  6621. $scope.windowTitle = angular.element(window.document)[0].title;
  6622. }]);
  6623. </file>
  6624. </example>
  6625. */
  6626. function $DocumentProvider(){
  6627. this.$get = ['$window', function(window){
  6628. return jqLite(window.document);
  6629. }];
  6630. }
  6631. /**
  6632. * @ngdoc service
  6633. * @name $exceptionHandler
  6634. * @requires ng.$log
  6635. *
  6636. * @description
  6637. * Any uncaught exception in angular expressions is delegated to this service.
  6638. * The default implementation simply delegates to `$log.error` which logs it into
  6639. * the browser console.
  6640. *
  6641. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6642. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6643. *
  6644. * ## Example:
  6645. *
  6646. * ```js
  6647. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6648. * return function (exception, cause) {
  6649. * exception.message += ' (caused by "' + cause + '")';
  6650. * throw exception;
  6651. * };
  6652. * });
  6653. * ```
  6654. *
  6655. * This example will override the normal action of `$exceptionHandler`, to make angular
  6656. * exceptions fail hard when they happen, instead of just logging to the console.
  6657. *
  6658. * @param {Error} exception Exception associated with the error.
  6659. * @param {string=} cause optional information about the context in which
  6660. * the error was thrown.
  6661. *
  6662. */
  6663. function $ExceptionHandlerProvider() {
  6664. this.$get = ['$log', function($log) {
  6665. return function(exception, cause) {
  6666. $log.error.apply($log, arguments);
  6667. };
  6668. }];
  6669. }
  6670. /**
  6671. * Parse headers into key value object
  6672. *
  6673. * @param {string} headers Raw headers as a string
  6674. * @returns {Object} Parsed headers as key value object
  6675. */
  6676. function parseHeaders(headers) {
  6677. var parsed = {}, key, val, i;
  6678. if (!headers) return parsed;
  6679. forEach(headers.split('\n'), function(line) {
  6680. i = line.indexOf(':');
  6681. key = lowercase(trim(line.substr(0, i)));
  6682. val = trim(line.substr(i + 1));
  6683. if (key) {
  6684. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6685. }
  6686. });
  6687. return parsed;
  6688. }
  6689. /**
  6690. * Returns a function that provides access to parsed headers.
  6691. *
  6692. * Headers are lazy parsed when first requested.
  6693. * @see parseHeaders
  6694. *
  6695. * @param {(string|Object)} headers Headers to provide access to.
  6696. * @returns {function(string=)} Returns a getter function which if called with:
  6697. *
  6698. * - if called with single an argument returns a single header value or null
  6699. * - if called with no arguments returns an object containing all headers.
  6700. */
  6701. function headersGetter(headers) {
  6702. var headersObj = isObject(headers) ? headers : undefined;
  6703. return function(name) {
  6704. if (!headersObj) headersObj = parseHeaders(headers);
  6705. if (name) {
  6706. return headersObj[lowercase(name)] || null;
  6707. }
  6708. return headersObj;
  6709. };
  6710. }
  6711. /**
  6712. * Chain all given functions
  6713. *
  6714. * This function is used for both request and response transforming
  6715. *
  6716. * @param {*} data Data to transform.
  6717. * @param {function(string=)} headers Http headers getter fn.
  6718. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6719. * @returns {*} Transformed data.
  6720. */
  6721. function transformData(data, headers, fns) {
  6722. if (isFunction(fns))
  6723. return fns(data, headers);
  6724. forEach(fns, function(fn) {
  6725. data = fn(data, headers);
  6726. });
  6727. return data;
  6728. }
  6729. function isSuccess(status) {
  6730. return 200 <= status && status < 300;
  6731. }
  6732. /**
  6733. * @ngdoc provider
  6734. * @name $httpProvider
  6735. * @description
  6736. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  6737. * */
  6738. function $HttpProvider() {
  6739. var JSON_START = /^\s*(\[|\{[^\{])/,
  6740. JSON_END = /[\}\]]\s*$/,
  6741. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6742. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6743. /**
  6744. * @ngdoc property
  6745. * @name $httpProvider#defaults
  6746. * @description
  6747. *
  6748. * Object containing default values for all {@link ng.$http $http} requests.
  6749. *
  6750. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  6751. * Defaults value is `'XSRF-TOKEN'`.
  6752. *
  6753. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  6754. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  6755. *
  6756. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  6757. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  6758. * setting default headers.
  6759. * - **`defaults.headers.common`**
  6760. * - **`defaults.headers.post`**
  6761. * - **`defaults.headers.put`**
  6762. * - **`defaults.headers.patch`**
  6763. **/
  6764. var defaults = this.defaults = {
  6765. // transform incoming response data
  6766. transformResponse: [function(data) {
  6767. if (isString(data)) {
  6768. // strip json vulnerability protection prefix
  6769. data = data.replace(PROTECTION_PREFIX, '');
  6770. if (JSON_START.test(data) && JSON_END.test(data))
  6771. data = fromJson(data);
  6772. }
  6773. return data;
  6774. }],
  6775. // transform outgoing request data
  6776. transformRequest: [function(d) {
  6777. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6778. }],
  6779. // default headers
  6780. headers: {
  6781. common: {
  6782. 'Accept': 'application/json, text/plain, */*'
  6783. },
  6784. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6785. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6786. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  6787. },
  6788. xsrfCookieName: 'XSRF-TOKEN',
  6789. xsrfHeaderName: 'X-XSRF-TOKEN'
  6790. };
  6791. /**
  6792. * @ngdoc property
  6793. * @name $httpProvider#interceptors
  6794. * @description
  6795. *
  6796. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  6797. * pre-processing of request or postprocessing of responses.
  6798. *
  6799. * These service factories are ordered by request, i.e. they are applied in the same order as the
  6800. * array, on request, but reverse order, on response.
  6801. *
  6802. * {@link ng.$http#interceptors Interceptors detailed info}
  6803. **/
  6804. var interceptorFactories = this.interceptors = [];
  6805. /**
  6806. * For historical reasons, response interceptors are ordered by the order in which
  6807. * they are applied to the response. (This is the opposite of interceptorFactories)
  6808. */
  6809. var responseInterceptorFactories = this.responseInterceptors = [];
  6810. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6811. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6812. var defaultCache = $cacheFactory('$http');
  6813. /**
  6814. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6815. * The reversal is needed so that we can build up the interception chain around the
  6816. * server request.
  6817. */
  6818. var reversedInterceptors = [];
  6819. forEach(interceptorFactories, function(interceptorFactory) {
  6820. reversedInterceptors.unshift(isString(interceptorFactory)
  6821. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6822. });
  6823. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6824. var responseFn = isString(interceptorFactory)
  6825. ? $injector.get(interceptorFactory)
  6826. : $injector.invoke(interceptorFactory);
  6827. /**
  6828. * Response interceptors go before "around" interceptors (no real reason, just
  6829. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6830. * the splice.
  6831. */
  6832. reversedInterceptors.splice(index, 0, {
  6833. response: function(response) {
  6834. return responseFn($q.when(response));
  6835. },
  6836. responseError: function(response) {
  6837. return responseFn($q.reject(response));
  6838. }
  6839. });
  6840. });
  6841. /**
  6842. * @ngdoc service
  6843. * @kind function
  6844. * @name $http
  6845. * @requires ng.$httpBackend
  6846. * @requires $cacheFactory
  6847. * @requires $rootScope
  6848. * @requires $q
  6849. * @requires $injector
  6850. *
  6851. * @description
  6852. * The `$http` service is a core Angular service that facilitates communication with the remote
  6853. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6854. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6855. *
  6856. * For unit testing applications that use `$http` service, see
  6857. * {@link ngMock.$httpBackend $httpBackend mock}.
  6858. *
  6859. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6860. * $resource} service.
  6861. *
  6862. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6863. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6864. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6865. *
  6866. *
  6867. * # General usage
  6868. * The `$http` service is a function which takes a single argument — a configuration object —
  6869. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6870. * with two $http specific methods: `success` and `error`.
  6871. *
  6872. * ```js
  6873. * $http({method: 'GET', url: '/someUrl'}).
  6874. * success(function(data, status, headers, config) {
  6875. * // this callback will be called asynchronously
  6876. * // when the response is available
  6877. * }).
  6878. * error(function(data, status, headers, config) {
  6879. * // called asynchronously if an error occurs
  6880. * // or server returns response with an error status.
  6881. * });
  6882. * ```
  6883. *
  6884. * Since the returned value of calling the $http function is a `promise`, you can also use
  6885. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6886. * an object representing the response. See the API signature and type info below for more
  6887. * details.
  6888. *
  6889. * A response status code between 200 and 299 is considered a success status and
  6890. * will result in the success callback being called. Note that if the response is a redirect,
  6891. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6892. * called for such responses.
  6893. *
  6894. * # Writing Unit Tests that use $http
  6895. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6896. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6897. * request using trained responses.
  6898. *
  6899. * ```
  6900. * $httpBackend.expectGET(...);
  6901. * $http.get(...);
  6902. * $httpBackend.flush();
  6903. * ```
  6904. *
  6905. * # Shortcut methods
  6906. *
  6907. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6908. * request data must be passed in for POST/PUT requests.
  6909. *
  6910. * ```js
  6911. * $http.get('/someUrl').success(successCallback);
  6912. * $http.post('/someUrl', data).success(successCallback);
  6913. * ```
  6914. *
  6915. * Complete list of shortcut methods:
  6916. *
  6917. * - {@link ng.$http#get $http.get}
  6918. * - {@link ng.$http#head $http.head}
  6919. * - {@link ng.$http#post $http.post}
  6920. * - {@link ng.$http#put $http.put}
  6921. * - {@link ng.$http#delete $http.delete}
  6922. * - {@link ng.$http#jsonp $http.jsonp}
  6923. * - {@link ng.$http#patch $http.patch}
  6924. *
  6925. *
  6926. * # Setting HTTP Headers
  6927. *
  6928. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6929. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6930. * object, which currently contains this default configuration:
  6931. *
  6932. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6933. * - `Accept: application/json, text/plain, * / *`
  6934. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6935. * - `Content-Type: application/json`
  6936. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6937. * - `Content-Type: application/json`
  6938. *
  6939. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6940. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6941. * with the lowercased HTTP method name as the key, e.g.
  6942. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6943. *
  6944. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6945. * fashion. For example:
  6946. *
  6947. * ```
  6948. * module.run(function($http) {
  6949. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6950. * });
  6951. * ```
  6952. *
  6953. * In addition, you can supply a `headers` property in the config object passed when
  6954. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6955. *
  6956. *
  6957. * # Transforming Requests and Responses
  6958. *
  6959. * Both requests and responses can be transformed using transform functions. By default, Angular
  6960. * applies these transformations:
  6961. *
  6962. * Request transformations:
  6963. *
  6964. * - If the `data` property of the request configuration object contains an object, serialize it
  6965. * into JSON format.
  6966. *
  6967. * Response transformations:
  6968. *
  6969. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6970. * - If JSON response is detected, deserialize it using a JSON parser.
  6971. *
  6972. * To globally augment or override the default transforms, modify the
  6973. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6974. * properties. These properties are by default an array of transform functions, which allows you
  6975. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6976. * also decide to completely override any default transformations by assigning your
  6977. * transformation functions to these properties directly without the array wrapper. These defaults
  6978. * are again available on the $http factory at run-time, which may be useful if you have run-time
  6979. * services you wish to be involved in your transformations.
  6980. *
  6981. * Similarly, to locally override the request/response transforms, augment the
  6982. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6983. * into `$http`.
  6984. *
  6985. *
  6986. * # Caching
  6987. *
  6988. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6989. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6990. * When the cache is enabled, `$http` stores the response from the server in the specified
  6991. * cache. The next time the same request is made, the response is served from the cache without
  6992. * sending a request to the server.
  6993. *
  6994. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6995. * the same way that real requests are.
  6996. *
  6997. * If there are multiple GET requests for the same URL that should be cached using the same
  6998. * cache, but the cache is not populated yet, only one request to the server will be made and
  6999. * the remaining requests will be fulfilled using the response from the first request.
  7000. *
  7001. * You can change the default cache to a new object (built with
  7002. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  7003. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  7004. * their `cache` property to `true` will now use this cache object.
  7005. *
  7006. * If you set the default cache to `false` then only requests that specify their own custom
  7007. * cache object will be cached.
  7008. *
  7009. * # Interceptors
  7010. *
  7011. * Before you start creating interceptors, be sure to understand the
  7012. * {@link ng.$q $q and deferred/promise APIs}.
  7013. *
  7014. * For purposes of global error handling, authentication, or any kind of synchronous or
  7015. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  7016. * able to intercept requests before they are handed to the server and
  7017. * responses before they are handed over to the application code that
  7018. * initiated these requests. The interceptors leverage the {@link ng.$q
  7019. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  7020. *
  7021. * The interceptors are service factories that are registered with the `$httpProvider` by
  7022. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  7023. * injected with dependencies (if specified) and returns the interceptor.
  7024. *
  7025. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  7026. *
  7027. * * `request`: interceptors get called with a http `config` object. The function is free to
  7028. * modify the `config` object or create a new one. The function needs to return the `config`
  7029. * object directly, or a promise containing the `config` or a new `config` object.
  7030. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  7031. * resolved with a rejection.
  7032. * * `response`: interceptors get called with http `response` object. The function is free to
  7033. * modify the `response` object or create a new one. The function needs to return the `response`
  7034. * object directly, or as a promise containing the `response` or a new `response` object.
  7035. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  7036. * resolved with a rejection.
  7037. *
  7038. *
  7039. * ```js
  7040. * // register the interceptor as a service
  7041. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7042. * return {
  7043. * // optional method
  7044. * 'request': function(config) {
  7045. * // do something on success
  7046. * return config;
  7047. * },
  7048. *
  7049. * // optional method
  7050. * 'requestError': function(rejection) {
  7051. * // do something on error
  7052. * if (canRecover(rejection)) {
  7053. * return responseOrNewPromise
  7054. * }
  7055. * return $q.reject(rejection);
  7056. * },
  7057. *
  7058. *
  7059. *
  7060. * // optional method
  7061. * 'response': function(response) {
  7062. * // do something on success
  7063. * return response;
  7064. * },
  7065. *
  7066. * // optional method
  7067. * 'responseError': function(rejection) {
  7068. * // do something on error
  7069. * if (canRecover(rejection)) {
  7070. * return responseOrNewPromise
  7071. * }
  7072. * return $q.reject(rejection);
  7073. * }
  7074. * };
  7075. * });
  7076. *
  7077. * $httpProvider.interceptors.push('myHttpInterceptor');
  7078. *
  7079. *
  7080. * // alternatively, register the interceptor via an anonymous factory
  7081. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  7082. * return {
  7083. * 'request': function(config) {
  7084. * // same as above
  7085. * },
  7086. *
  7087. * 'response': function(response) {
  7088. * // same as above
  7089. * }
  7090. * };
  7091. * });
  7092. * ```
  7093. *
  7094. * # Response interceptors (DEPRECATED)
  7095. *
  7096. * Before you start creating interceptors, be sure to understand the
  7097. * {@link ng.$q $q and deferred/promise APIs}.
  7098. *
  7099. * For purposes of global error handling, authentication or any kind of synchronous or
  7100. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  7101. * responses for http requests before they are handed over to the application code that
  7102. * initiated these requests. The response interceptors leverage the {@link ng.$q
  7103. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  7104. *
  7105. * The interceptors are service factories that are registered with the $httpProvider by
  7106. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  7107. * injected with dependencies (if specified) and returns the interceptor — a function that
  7108. * takes a {@link ng.$q promise} and returns the original or a new promise.
  7109. *
  7110. * ```js
  7111. * // register the interceptor as a service
  7112. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7113. * return function(promise) {
  7114. * return promise.then(function(response) {
  7115. * // do something on success
  7116. * return response;
  7117. * }, function(response) {
  7118. * // do something on error
  7119. * if (canRecover(response)) {
  7120. * return responseOrNewPromise
  7121. * }
  7122. * return $q.reject(response);
  7123. * });
  7124. * }
  7125. * });
  7126. *
  7127. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  7128. *
  7129. *
  7130. * // register the interceptor via an anonymous factory
  7131. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  7132. * return function(promise) {
  7133. * // same as above
  7134. * }
  7135. * });
  7136. * ```
  7137. *
  7138. *
  7139. * # Security Considerations
  7140. *
  7141. * When designing web applications, consider security threats from:
  7142. *
  7143. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7144. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  7145. *
  7146. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  7147. * pre-configured with strategies that address these issues, but for this to work backend server
  7148. * cooperation is required.
  7149. *
  7150. * ## JSON Vulnerability Protection
  7151. *
  7152. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7153. * allows third party website to turn your JSON resource URL into
  7154. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  7155. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  7156. * Angular will automatically strip the prefix before processing it as JSON.
  7157. *
  7158. * For example if your server needs to return:
  7159. * ```js
  7160. * ['one','two']
  7161. * ```
  7162. *
  7163. * which is vulnerable to attack, your server can return:
  7164. * ```js
  7165. * )]}',
  7166. * ['one','two']
  7167. * ```
  7168. *
  7169. * Angular will strip the prefix, before processing the JSON.
  7170. *
  7171. *
  7172. * ## Cross Site Request Forgery (XSRF) Protection
  7173. *
  7174. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  7175. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  7176. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  7177. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  7178. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  7179. * the XHR came from JavaScript running on your domain. The header will not be set for
  7180. * cross-domain requests.
  7181. *
  7182. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7183. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7184. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7185. * that only JavaScript running on your domain could have sent the request. The token must be
  7186. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7187. * making up its own tokens). We recommend that the token is a digest of your site's
  7188. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  7189. * for added security.
  7190. *
  7191. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7192. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7193. * or the per-request config object.
  7194. *
  7195. *
  7196. * @param {object} config Object describing the request to be made and how it should be
  7197. * processed. The object has following properties:
  7198. *
  7199. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7200. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7201. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7202. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7203. * JSONified.
  7204. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7205. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7206. * HTTP headers to send to the server. If the return value of a function is null, the
  7207. * header will not be sent.
  7208. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7209. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7210. * - **transformRequest** –
  7211. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7212. * transform function or an array of such functions. The transform function takes the http
  7213. * request body and headers and returns its transformed (typically serialized) version.
  7214. * - **transformResponse** –
  7215. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7216. * transform function or an array of such functions. The transform function takes the http
  7217. * response body and headers and returns its transformed (typically deserialized) version.
  7218. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7219. * GET request, otherwise if a cache instance built with
  7220. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7221. * caching.
  7222. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7223. * that should abort the request when resolved.
  7224. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  7225. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  7226. * for more information.
  7227. * - **responseType** - `{string}` - see
  7228. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7229. *
  7230. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7231. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7232. * method takes two arguments a success and an error callback which will be called with a
  7233. * response object. The `success` and `error` methods take a single argument - a function that
  7234. * will be called when the request succeeds or fails respectively. The arguments passed into
  7235. * these functions are destructured representation of the response object passed into the
  7236. * `then` method. The response object has these properties:
  7237. *
  7238. * - **data** – `{string|Object}` – The response body transformed with the transform
  7239. * functions.
  7240. * - **status** – `{number}` – HTTP status code of the response.
  7241. * - **headers** – `{function([headerName])}` – Header getter function.
  7242. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7243. * - **statusText** – `{string}` – HTTP status text of the response.
  7244. *
  7245. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7246. * requests. This is primarily meant to be used for debugging purposes.
  7247. *
  7248. *
  7249. * @example
  7250. <example module="httpExample">
  7251. <file name="index.html">
  7252. <div ng-controller="FetchController">
  7253. <select ng-model="method">
  7254. <option>GET</option>
  7255. <option>JSONP</option>
  7256. </select>
  7257. <input type="text" ng-model="url" size="80"/>
  7258. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7259. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7260. <button id="samplejsonpbtn"
  7261. ng-click="updateModel('JSONP',
  7262. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7263. Sample JSONP
  7264. </button>
  7265. <button id="invalidjsonpbtn"
  7266. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7267. Invalid JSONP
  7268. </button>
  7269. <pre>http status code: {{status}}</pre>
  7270. <pre>http response data: {{data}}</pre>
  7271. </div>
  7272. </file>
  7273. <file name="script.js">
  7274. angular.module('httpExample', [])
  7275. .controller('FetchController', ['$scope', '$http', '$templateCache',
  7276. function($scope, $http, $templateCache) {
  7277. $scope.method = 'GET';
  7278. $scope.url = 'http-hello.html';
  7279. $scope.fetch = function() {
  7280. $scope.code = null;
  7281. $scope.response = null;
  7282. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7283. success(function(data, status) {
  7284. $scope.status = status;
  7285. $scope.data = data;
  7286. }).
  7287. error(function(data, status) {
  7288. $scope.data = data || "Request failed";
  7289. $scope.status = status;
  7290. });
  7291. };
  7292. $scope.updateModel = function(method, url) {
  7293. $scope.method = method;
  7294. $scope.url = url;
  7295. };
  7296. }]);
  7297. </file>
  7298. <file name="http-hello.html">
  7299. Hello, $http!
  7300. </file>
  7301. <file name="protractor.js" type="protractor">
  7302. var status = element(by.binding('status'));
  7303. var data = element(by.binding('data'));
  7304. var fetchBtn = element(by.id('fetchbtn'));
  7305. var sampleGetBtn = element(by.id('samplegetbtn'));
  7306. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7307. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7308. it('should make an xhr GET request', function() {
  7309. sampleGetBtn.click();
  7310. fetchBtn.click();
  7311. expect(status.getText()).toMatch('200');
  7312. expect(data.getText()).toMatch(/Hello, \$http!/);
  7313. });
  7314. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  7315. // it('should make a JSONP request to angularjs.org', function() {
  7316. // sampleJsonpBtn.click();
  7317. // fetchBtn.click();
  7318. // expect(status.getText()).toMatch('200');
  7319. // expect(data.getText()).toMatch(/Super Hero!/);
  7320. // });
  7321. it('should make JSONP request to invalid URL and invoke the error handler',
  7322. function() {
  7323. invalidJsonpBtn.click();
  7324. fetchBtn.click();
  7325. expect(status.getText()).toMatch('0');
  7326. expect(data.getText()).toMatch('Request failed');
  7327. });
  7328. </file>
  7329. </example>
  7330. */
  7331. function $http(requestConfig) {
  7332. var config = {
  7333. method: 'get',
  7334. transformRequest: defaults.transformRequest,
  7335. transformResponse: defaults.transformResponse
  7336. };
  7337. var headers = mergeHeaders(requestConfig);
  7338. extend(config, requestConfig);
  7339. config.headers = headers;
  7340. config.method = uppercase(config.method);
  7341. var serverRequest = function(config) {
  7342. headers = config.headers;
  7343. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7344. // strip content-type if data is undefined
  7345. if (isUndefined(reqData)) {
  7346. forEach(headers, function(value, header) {
  7347. if (lowercase(header) === 'content-type') {
  7348. delete headers[header];
  7349. }
  7350. });
  7351. }
  7352. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7353. config.withCredentials = defaults.withCredentials;
  7354. }
  7355. // send request
  7356. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7357. };
  7358. var chain = [serverRequest, undefined];
  7359. var promise = $q.when(config);
  7360. // apply interceptors
  7361. forEach(reversedInterceptors, function(interceptor) {
  7362. if (interceptor.request || interceptor.requestError) {
  7363. chain.unshift(interceptor.request, interceptor.requestError);
  7364. }
  7365. if (interceptor.response || interceptor.responseError) {
  7366. chain.push(interceptor.response, interceptor.responseError);
  7367. }
  7368. });
  7369. while(chain.length) {
  7370. var thenFn = chain.shift();
  7371. var rejectFn = chain.shift();
  7372. promise = promise.then(thenFn, rejectFn);
  7373. }
  7374. promise.success = function(fn) {
  7375. promise.then(function(response) {
  7376. fn(response.data, response.status, response.headers, config);
  7377. });
  7378. return promise;
  7379. };
  7380. promise.error = function(fn) {
  7381. promise.then(null, function(response) {
  7382. fn(response.data, response.status, response.headers, config);
  7383. });
  7384. return promise;
  7385. };
  7386. return promise;
  7387. function transformResponse(response) {
  7388. // make a copy since the response must be cacheable
  7389. var resp = extend({}, response, {
  7390. data: transformData(response.data, response.headers, config.transformResponse)
  7391. });
  7392. return (isSuccess(response.status))
  7393. ? resp
  7394. : $q.reject(resp);
  7395. }
  7396. function mergeHeaders(config) {
  7397. var defHeaders = defaults.headers,
  7398. reqHeaders = extend({}, config.headers),
  7399. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7400. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7401. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7402. defaultHeadersIteration:
  7403. for (defHeaderName in defHeaders) {
  7404. lowercaseDefHeaderName = lowercase(defHeaderName);
  7405. for (reqHeaderName in reqHeaders) {
  7406. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7407. continue defaultHeadersIteration;
  7408. }
  7409. }
  7410. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7411. }
  7412. // execute if header value is a function for merged headers
  7413. execHeaders(reqHeaders);
  7414. return reqHeaders;
  7415. function execHeaders(headers) {
  7416. var headerContent;
  7417. forEach(headers, function(headerFn, header) {
  7418. if (isFunction(headerFn)) {
  7419. headerContent = headerFn();
  7420. if (headerContent != null) {
  7421. headers[header] = headerContent;
  7422. } else {
  7423. delete headers[header];
  7424. }
  7425. }
  7426. });
  7427. }
  7428. }
  7429. }
  7430. $http.pendingRequests = [];
  7431. /**
  7432. * @ngdoc method
  7433. * @name $http#get
  7434. *
  7435. * @description
  7436. * Shortcut method to perform `GET` request.
  7437. *
  7438. * @param {string} url Relative or absolute URL specifying the destination of the request
  7439. * @param {Object=} config Optional configuration object
  7440. * @returns {HttpPromise} Future object
  7441. */
  7442. /**
  7443. * @ngdoc method
  7444. * @name $http#delete
  7445. *
  7446. * @description
  7447. * Shortcut method to perform `DELETE` request.
  7448. *
  7449. * @param {string} url Relative or absolute URL specifying the destination of the request
  7450. * @param {Object=} config Optional configuration object
  7451. * @returns {HttpPromise} Future object
  7452. */
  7453. /**
  7454. * @ngdoc method
  7455. * @name $http#head
  7456. *
  7457. * @description
  7458. * Shortcut method to perform `HEAD` request.
  7459. *
  7460. * @param {string} url Relative or absolute URL specifying the destination of the request
  7461. * @param {Object=} config Optional configuration object
  7462. * @returns {HttpPromise} Future object
  7463. */
  7464. /**
  7465. * @ngdoc method
  7466. * @name $http#jsonp
  7467. *
  7468. * @description
  7469. * Shortcut method to perform `JSONP` request.
  7470. *
  7471. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7472. * The name of the callback should be the string `JSON_CALLBACK`.
  7473. * @param {Object=} config Optional configuration object
  7474. * @returns {HttpPromise} Future object
  7475. */
  7476. createShortMethods('get', 'delete', 'head', 'jsonp');
  7477. /**
  7478. * @ngdoc method
  7479. * @name $http#post
  7480. *
  7481. * @description
  7482. * Shortcut method to perform `POST` request.
  7483. *
  7484. * @param {string} url Relative or absolute URL specifying the destination of the request
  7485. * @param {*} data Request content
  7486. * @param {Object=} config Optional configuration object
  7487. * @returns {HttpPromise} Future object
  7488. */
  7489. /**
  7490. * @ngdoc method
  7491. * @name $http#put
  7492. *
  7493. * @description
  7494. * Shortcut method to perform `PUT` request.
  7495. *
  7496. * @param {string} url Relative or absolute URL specifying the destination of the request
  7497. * @param {*} data Request content
  7498. * @param {Object=} config Optional configuration object
  7499. * @returns {HttpPromise} Future object
  7500. */
  7501. /**
  7502. * @ngdoc method
  7503. * @name $http#patch
  7504. *
  7505. * @description
  7506. * Shortcut method to perform `PATCH` request.
  7507. *
  7508. * @param {string} url Relative or absolute URL specifying the destination of the request
  7509. * @param {*} data Request content
  7510. * @param {Object=} config Optional configuration object
  7511. * @returns {HttpPromise} Future object
  7512. */
  7513. createShortMethodsWithData('post', 'put', 'patch');
  7514. /**
  7515. * @ngdoc property
  7516. * @name $http#defaults
  7517. *
  7518. * @description
  7519. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7520. * default headers, withCredentials as well as request and response transformations.
  7521. *
  7522. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7523. */
  7524. $http.defaults = defaults;
  7525. return $http;
  7526. function createShortMethods(names) {
  7527. forEach(arguments, function(name) {
  7528. $http[name] = function(url, config) {
  7529. return $http(extend(config || {}, {
  7530. method: name,
  7531. url: url
  7532. }));
  7533. };
  7534. });
  7535. }
  7536. function createShortMethodsWithData(name) {
  7537. forEach(arguments, function(name) {
  7538. $http[name] = function(url, data, config) {
  7539. return $http(extend(config || {}, {
  7540. method: name,
  7541. url: url,
  7542. data: data
  7543. }));
  7544. };
  7545. });
  7546. }
  7547. /**
  7548. * Makes the request.
  7549. *
  7550. * !!! ACCESSES CLOSURE VARS:
  7551. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7552. */
  7553. function sendReq(config, reqData, reqHeaders) {
  7554. var deferred = $q.defer(),
  7555. promise = deferred.promise,
  7556. cache,
  7557. cachedResp,
  7558. url = buildUrl(config.url, config.params);
  7559. $http.pendingRequests.push(config);
  7560. promise.then(removePendingReq, removePendingReq);
  7561. if ((config.cache || defaults.cache) && config.cache !== false &&
  7562. (config.method === 'GET' || config.method === 'JSONP')) {
  7563. cache = isObject(config.cache) ? config.cache
  7564. : isObject(defaults.cache) ? defaults.cache
  7565. : defaultCache;
  7566. }
  7567. if (cache) {
  7568. cachedResp = cache.get(url);
  7569. if (isDefined(cachedResp)) {
  7570. if (isPromiseLike(cachedResp)) {
  7571. // cached request has already been sent, but there is no response yet
  7572. cachedResp.then(removePendingReq, removePendingReq);
  7573. return cachedResp;
  7574. } else {
  7575. // serving from cache
  7576. if (isArray(cachedResp)) {
  7577. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  7578. } else {
  7579. resolvePromise(cachedResp, 200, {}, 'OK');
  7580. }
  7581. }
  7582. } else {
  7583. // put the promise for the non-transformed response into cache as a placeholder
  7584. cache.put(url, promise);
  7585. }
  7586. }
  7587. // if we won't have the response in cache, set the xsrf headers and
  7588. // send the request to the backend
  7589. if (isUndefined(cachedResp)) {
  7590. var xsrfValue = urlIsSameOrigin(config.url)
  7591. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7592. : undefined;
  7593. if (xsrfValue) {
  7594. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7595. }
  7596. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7597. config.withCredentials, config.responseType);
  7598. }
  7599. return promise;
  7600. /**
  7601. * Callback registered to $httpBackend():
  7602. * - caches the response if desired
  7603. * - resolves the raw $http promise
  7604. * - calls $apply
  7605. */
  7606. function done(status, response, headersString, statusText) {
  7607. if (cache) {
  7608. if (isSuccess(status)) {
  7609. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7610. } else {
  7611. // remove promise from the cache
  7612. cache.remove(url);
  7613. }
  7614. }
  7615. resolvePromise(response, status, headersString, statusText);
  7616. if (!$rootScope.$$phase) $rootScope.$apply();
  7617. }
  7618. /**
  7619. * Resolves the raw $http promise.
  7620. */
  7621. function resolvePromise(response, status, headers, statusText) {
  7622. // normalize internal statuses to 0
  7623. status = Math.max(status, 0);
  7624. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7625. data: response,
  7626. status: status,
  7627. headers: headersGetter(headers),
  7628. config: config,
  7629. statusText : statusText
  7630. });
  7631. }
  7632. function removePendingReq() {
  7633. var idx = indexOf($http.pendingRequests, config);
  7634. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7635. }
  7636. }
  7637. function buildUrl(url, params) {
  7638. if (!params) return url;
  7639. var parts = [];
  7640. forEachSorted(params, function(value, key) {
  7641. if (value === null || isUndefined(value)) return;
  7642. if (!isArray(value)) value = [value];
  7643. forEach(value, function(v) {
  7644. if (isObject(v)) {
  7645. if (isDate(v)){
  7646. v = v.toISOString();
  7647. } else {
  7648. v = toJson(v);
  7649. }
  7650. }
  7651. parts.push(encodeUriQuery(key) + '=' +
  7652. encodeUriQuery(v));
  7653. });
  7654. });
  7655. if(parts.length > 0) {
  7656. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7657. }
  7658. return url;
  7659. }
  7660. }];
  7661. }
  7662. function createXhr(method) {
  7663. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7664. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7665. //if it is available
  7666. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7667. !window.XMLHttpRequest)) {
  7668. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7669. } else if (window.XMLHttpRequest) {
  7670. return new window.XMLHttpRequest();
  7671. }
  7672. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7673. }
  7674. /**
  7675. * @ngdoc service
  7676. * @name $httpBackend
  7677. * @requires $window
  7678. * @requires $document
  7679. *
  7680. * @description
  7681. * HTTP backend used by the {@link ng.$http service} that delegates to
  7682. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7683. *
  7684. * You should never need to use this service directly, instead use the higher-level abstractions:
  7685. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7686. *
  7687. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7688. * $httpBackend} which can be trained with responses.
  7689. */
  7690. function $HttpBackendProvider() {
  7691. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7692. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7693. }];
  7694. }
  7695. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7696. var ABORTED = -1;
  7697. // TODO(vojta): fix the signature
  7698. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7699. var status;
  7700. $browser.$$incOutstandingRequestCount();
  7701. url = url || $browser.url();
  7702. if (lowercase(method) == 'jsonp') {
  7703. var callbackId = '_' + (callbacks.counter++).toString(36);
  7704. callbacks[callbackId] = function(data) {
  7705. callbacks[callbackId].data = data;
  7706. callbacks[callbackId].called = true;
  7707. };
  7708. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7709. callbackId, function(status, text) {
  7710. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  7711. callbacks[callbackId] = noop;
  7712. });
  7713. } else {
  7714. var xhr = createXhr(method);
  7715. xhr.open(method, url, true);
  7716. forEach(headers, function(value, key) {
  7717. if (isDefined(value)) {
  7718. xhr.setRequestHeader(key, value);
  7719. }
  7720. });
  7721. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7722. // response is in the cache. the promise api will ensure that to the app code the api is
  7723. // always async
  7724. xhr.onreadystatechange = function() {
  7725. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7726. // xhrs that are resolved while the app is in the background (see #5426).
  7727. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7728. // continuing
  7729. //
  7730. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7731. // Safari respectively.
  7732. if (xhr && xhr.readyState == 4) {
  7733. var responseHeaders = null,
  7734. response = null,
  7735. statusText = '';
  7736. if(status !== ABORTED) {
  7737. responseHeaders = xhr.getAllResponseHeaders();
  7738. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7739. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7740. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7741. }
  7742. // Accessing statusText on an aborted xhr object will
  7743. // throw an 'c00c023f error' in IE9 and lower, don't touch it.
  7744. if (!(status === ABORTED && msie < 10)) {
  7745. statusText = xhr.statusText;
  7746. }
  7747. completeRequest(callback,
  7748. status || xhr.status,
  7749. response,
  7750. responseHeaders,
  7751. statusText);
  7752. }
  7753. };
  7754. if (withCredentials) {
  7755. xhr.withCredentials = true;
  7756. }
  7757. if (responseType) {
  7758. try {
  7759. xhr.responseType = responseType;
  7760. } catch (e) {
  7761. // WebKit added support for the json responseType value on 09/03/2013
  7762. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7763. // known to throw when setting the value "json" as the response type. Other older
  7764. // browsers implementing the responseType
  7765. //
  7766. // The json response type can be ignored if not supported, because JSON payloads are
  7767. // parsed on the client-side regardless.
  7768. if (responseType !== 'json') {
  7769. throw e;
  7770. }
  7771. }
  7772. }
  7773. xhr.send(post || null);
  7774. }
  7775. if (timeout > 0) {
  7776. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7777. } else if (isPromiseLike(timeout)) {
  7778. timeout.then(timeoutRequest);
  7779. }
  7780. function timeoutRequest() {
  7781. status = ABORTED;
  7782. jsonpDone && jsonpDone();
  7783. xhr && xhr.abort();
  7784. }
  7785. function completeRequest(callback, status, response, headersString, statusText) {
  7786. // cancel timeout and subsequent timeout promise resolution
  7787. timeoutId && $browserDefer.cancel(timeoutId);
  7788. jsonpDone = xhr = null;
  7789. // fix status code when it is 0 (0 status is undocumented).
  7790. // Occurs when accessing file resources or on Android 4.1 stock browser
  7791. // while retrieving files from application cache.
  7792. if (status === 0) {
  7793. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7794. }
  7795. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7796. status = status === 1223 ? 204 : status;
  7797. statusText = statusText || '';
  7798. callback(status, response, headersString, statusText);
  7799. $browser.$$completeOutstandingRequest(noop);
  7800. }
  7801. };
  7802. function jsonpReq(url, callbackId, done) {
  7803. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7804. // - fetches local scripts via XHR and evals them
  7805. // - adds and immediately removes script elements from the document
  7806. var script = rawDocument.createElement('script'), callback = null;
  7807. script.type = "text/javascript";
  7808. script.src = url;
  7809. script.async = true;
  7810. callback = function(event) {
  7811. removeEventListenerFn(script, "load", callback);
  7812. removeEventListenerFn(script, "error", callback);
  7813. rawDocument.body.removeChild(script);
  7814. script = null;
  7815. var status = -1;
  7816. var text = "unknown";
  7817. if (event) {
  7818. if (event.type === "load" && !callbacks[callbackId].called) {
  7819. event = { type: "error" };
  7820. }
  7821. text = event.type;
  7822. status = event.type === "error" ? 404 : 200;
  7823. }
  7824. if (done) {
  7825. done(status, text);
  7826. }
  7827. };
  7828. addEventListenerFn(script, "load", callback);
  7829. addEventListenerFn(script, "error", callback);
  7830. if (msie <= 8) {
  7831. script.onreadystatechange = function() {
  7832. if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) {
  7833. script.onreadystatechange = null;
  7834. callback({
  7835. type: 'load'
  7836. });
  7837. }
  7838. };
  7839. }
  7840. rawDocument.body.appendChild(script);
  7841. return callback;
  7842. }
  7843. }
  7844. var $interpolateMinErr = minErr('$interpolate');
  7845. /**
  7846. * @ngdoc provider
  7847. * @name $interpolateProvider
  7848. * @kind function
  7849. *
  7850. * @description
  7851. *
  7852. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7853. *
  7854. * @example
  7855. <example module="customInterpolationApp">
  7856. <file name="index.html">
  7857. <script>
  7858. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7859. customInterpolationApp.config(function($interpolateProvider) {
  7860. $interpolateProvider.startSymbol('//');
  7861. $interpolateProvider.endSymbol('//');
  7862. });
  7863. customInterpolationApp.controller('DemoController', function() {
  7864. this.label = "This binding is brought you by // interpolation symbols.";
  7865. });
  7866. </script>
  7867. <div ng-app="App" ng-controller="DemoController as demo">
  7868. //demo.label//
  7869. </div>
  7870. </file>
  7871. <file name="protractor.js" type="protractor">
  7872. it('should interpolate binding with custom symbols', function() {
  7873. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7874. });
  7875. </file>
  7876. </example>
  7877. */
  7878. function $InterpolateProvider() {
  7879. var startSymbol = '{{';
  7880. var endSymbol = '}}';
  7881. /**
  7882. * @ngdoc method
  7883. * @name $interpolateProvider#startSymbol
  7884. * @description
  7885. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7886. *
  7887. * @param {string=} value new value to set the starting symbol to.
  7888. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7889. */
  7890. this.startSymbol = function(value){
  7891. if (value) {
  7892. startSymbol = value;
  7893. return this;
  7894. } else {
  7895. return startSymbol;
  7896. }
  7897. };
  7898. /**
  7899. * @ngdoc method
  7900. * @name $interpolateProvider#endSymbol
  7901. * @description
  7902. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7903. *
  7904. * @param {string=} value new value to set the ending symbol to.
  7905. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7906. */
  7907. this.endSymbol = function(value){
  7908. if (value) {
  7909. endSymbol = value;
  7910. return this;
  7911. } else {
  7912. return endSymbol;
  7913. }
  7914. };
  7915. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7916. var startSymbolLength = startSymbol.length,
  7917. endSymbolLength = endSymbol.length;
  7918. /**
  7919. * @ngdoc service
  7920. * @name $interpolate
  7921. * @kind function
  7922. *
  7923. * @requires $parse
  7924. * @requires $sce
  7925. *
  7926. * @description
  7927. *
  7928. * Compiles a string with markup into an interpolation function. This service is used by the
  7929. * HTML {@link ng.$compile $compile} service for data binding. See
  7930. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7931. * interpolation markup.
  7932. *
  7933. *
  7934. * ```js
  7935. * var $interpolate = ...; // injected
  7936. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7937. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7938. * ```
  7939. *
  7940. *
  7941. * @param {string} text The text with markup to interpolate.
  7942. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7943. * embedded expression in order to return an interpolation function. Strings with no
  7944. * embedded expression will return null for the interpolation function.
  7945. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7946. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7947. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7948. * provides Strict Contextual Escaping for details.
  7949. * @returns {function(context)} an interpolation function which is used to compute the
  7950. * interpolated string. The function has these parameters:
  7951. *
  7952. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7953. * against.
  7954. *
  7955. */
  7956. function $interpolate(text, mustHaveExpression, trustedContext) {
  7957. var startIndex,
  7958. endIndex,
  7959. index = 0,
  7960. parts = [],
  7961. length = text.length,
  7962. hasInterpolation = false,
  7963. fn,
  7964. exp,
  7965. concat = [];
  7966. while(index < length) {
  7967. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7968. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7969. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7970. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7971. fn.exp = exp;
  7972. index = endIndex + endSymbolLength;
  7973. hasInterpolation = true;
  7974. } else {
  7975. // we did not find anything, so we have to add the remainder to the parts array
  7976. (index != length) && parts.push(text.substring(index));
  7977. index = length;
  7978. }
  7979. }
  7980. if (!(length = parts.length)) {
  7981. // we added, nothing, must have been an empty string.
  7982. parts.push('');
  7983. length = 1;
  7984. }
  7985. // Concatenating expressions makes it hard to reason about whether some combination of
  7986. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7987. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7988. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7989. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7990. // the load when auditing for XSS issues.
  7991. if (trustedContext && parts.length > 1) {
  7992. throw $interpolateMinErr('noconcat',
  7993. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7994. "interpolations that concatenate multiple expressions when a trusted value is " +
  7995. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7996. }
  7997. if (!mustHaveExpression || hasInterpolation) {
  7998. concat.length = length;
  7999. fn = function(context) {
  8000. try {
  8001. for(var i = 0, ii = length, part; i<ii; i++) {
  8002. if (typeof (part = parts[i]) == 'function') {
  8003. part = part(context);
  8004. if (trustedContext) {
  8005. part = $sce.getTrusted(trustedContext, part);
  8006. } else {
  8007. part = $sce.valueOf(part);
  8008. }
  8009. if (part == null) { // null || undefined
  8010. part = '';
  8011. } else {
  8012. switch (typeof part) {
  8013. case 'string':
  8014. {
  8015. break;
  8016. }
  8017. case 'number':
  8018. {
  8019. part = '' + part;
  8020. break;
  8021. }
  8022. default:
  8023. {
  8024. part = toJson(part);
  8025. }
  8026. }
  8027. }
  8028. }
  8029. concat[i] = part;
  8030. }
  8031. return concat.join('');
  8032. }
  8033. catch(err) {
  8034. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  8035. err.toString());
  8036. $exceptionHandler(newErr);
  8037. }
  8038. };
  8039. fn.exp = text;
  8040. fn.parts = parts;
  8041. return fn;
  8042. }
  8043. }
  8044. /**
  8045. * @ngdoc method
  8046. * @name $interpolate#startSymbol
  8047. * @description
  8048. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  8049. *
  8050. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  8051. * the symbol.
  8052. *
  8053. * @returns {string} start symbol.
  8054. */
  8055. $interpolate.startSymbol = function() {
  8056. return startSymbol;
  8057. };
  8058. /**
  8059. * @ngdoc method
  8060. * @name $interpolate#endSymbol
  8061. * @description
  8062. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8063. *
  8064. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  8065. * the symbol.
  8066. *
  8067. * @returns {string} end symbol.
  8068. */
  8069. $interpolate.endSymbol = function() {
  8070. return endSymbol;
  8071. };
  8072. return $interpolate;
  8073. }];
  8074. }
  8075. function $IntervalProvider() {
  8076. this.$get = ['$rootScope', '$window', '$q',
  8077. function($rootScope, $window, $q) {
  8078. var intervals = {};
  8079. /**
  8080. * @ngdoc service
  8081. * @name $interval
  8082. *
  8083. * @description
  8084. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  8085. * milliseconds.
  8086. *
  8087. * The return value of registering an interval function is a promise. This promise will be
  8088. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  8089. * run indefinitely if `count` is not defined. The value of the notification will be the
  8090. * number of iterations that have run.
  8091. * To cancel an interval, call `$interval.cancel(promise)`.
  8092. *
  8093. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  8094. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  8095. * time.
  8096. *
  8097. * <div class="alert alert-warning">
  8098. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  8099. * with them. In particular they are not automatically destroyed when a controller's scope or a
  8100. * directive's element are destroyed.
  8101. * You should take this into consideration and make sure to always cancel the interval at the
  8102. * appropriate moment. See the example below for more details on how and when to do this.
  8103. * </div>
  8104. *
  8105. * @param {function()} fn A function that should be called repeatedly.
  8106. * @param {number} delay Number of milliseconds between each function call.
  8107. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  8108. * indefinitely.
  8109. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  8110. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  8111. * @returns {promise} A promise which will be notified on each iteration.
  8112. *
  8113. * @example
  8114. * <example module="intervalExample">
  8115. * <file name="index.html">
  8116. * <script>
  8117. * angular.module('intervalExample', [])
  8118. * .controller('ExampleController', ['$scope', '$interval',
  8119. * function($scope, $interval) {
  8120. * $scope.format = 'M/d/yy h:mm:ss a';
  8121. * $scope.blood_1 = 100;
  8122. * $scope.blood_2 = 120;
  8123. *
  8124. * var stop;
  8125. * $scope.fight = function() {
  8126. * // Don't start a new fight if we are already fighting
  8127. * if ( angular.isDefined(stop) ) return;
  8128. *
  8129. * stop = $interval(function() {
  8130. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  8131. * $scope.blood_1 = $scope.blood_1 - 3;
  8132. * $scope.blood_2 = $scope.blood_2 - 4;
  8133. * } else {
  8134. * $scope.stopFight();
  8135. * }
  8136. * }, 100);
  8137. * };
  8138. *
  8139. * $scope.stopFight = function() {
  8140. * if (angular.isDefined(stop)) {
  8141. * $interval.cancel(stop);
  8142. * stop = undefined;
  8143. * }
  8144. * };
  8145. *
  8146. * $scope.resetFight = function() {
  8147. * $scope.blood_1 = 100;
  8148. * $scope.blood_2 = 120;
  8149. * };
  8150. *
  8151. * $scope.$on('$destroy', function() {
  8152. * // Make sure that the interval is destroyed too
  8153. * $scope.stopFight();
  8154. * });
  8155. * }])
  8156. * // Register the 'myCurrentTime' directive factory method.
  8157. * // We inject $interval and dateFilter service since the factory method is DI.
  8158. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  8159. * function($interval, dateFilter) {
  8160. * // return the directive link function. (compile function not needed)
  8161. * return function(scope, element, attrs) {
  8162. * var format, // date format
  8163. * stopTime; // so that we can cancel the time updates
  8164. *
  8165. * // used to update the UI
  8166. * function updateTime() {
  8167. * element.text(dateFilter(new Date(), format));
  8168. * }
  8169. *
  8170. * // watch the expression, and update the UI on change.
  8171. * scope.$watch(attrs.myCurrentTime, function(value) {
  8172. * format = value;
  8173. * updateTime();
  8174. * });
  8175. *
  8176. * stopTime = $interval(updateTime, 1000);
  8177. *
  8178. * // listen on DOM destroy (removal) event, and cancel the next UI update
  8179. * // to prevent updating time after the DOM element was removed.
  8180. * element.bind('$destroy', function() {
  8181. * $interval.cancel(stopTime);
  8182. * });
  8183. * }
  8184. * }]);
  8185. * </script>
  8186. *
  8187. * <div>
  8188. * <div ng-controller="ExampleController">
  8189. * Date format: <input ng-model="format"> <hr/>
  8190. * Current time is: <span my-current-time="format"></span>
  8191. * <hr/>
  8192. * Blood 1 : <font color='red'>{{blood_1}}</font>
  8193. * Blood 2 : <font color='red'>{{blood_2}}</font>
  8194. * <button type="button" data-ng-click="fight()">Fight</button>
  8195. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  8196. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  8197. * </div>
  8198. * </div>
  8199. *
  8200. * </file>
  8201. * </example>
  8202. */
  8203. function interval(fn, delay, count, invokeApply) {
  8204. var setInterval = $window.setInterval,
  8205. clearInterval = $window.clearInterval,
  8206. deferred = $q.defer(),
  8207. promise = deferred.promise,
  8208. iteration = 0,
  8209. skipApply = (isDefined(invokeApply) && !invokeApply);
  8210. count = isDefined(count) ? count : 0;
  8211. promise.then(null, null, fn);
  8212. promise.$$intervalId = setInterval(function tick() {
  8213. deferred.notify(iteration++);
  8214. if (count > 0 && iteration >= count) {
  8215. deferred.resolve(iteration);
  8216. clearInterval(promise.$$intervalId);
  8217. delete intervals[promise.$$intervalId];
  8218. }
  8219. if (!skipApply) $rootScope.$apply();
  8220. }, delay);
  8221. intervals[promise.$$intervalId] = deferred;
  8222. return promise;
  8223. }
  8224. /**
  8225. * @ngdoc method
  8226. * @name $interval#cancel
  8227. *
  8228. * @description
  8229. * Cancels a task associated with the `promise`.
  8230. *
  8231. * @param {promise} promise returned by the `$interval` function.
  8232. * @returns {boolean} Returns `true` if the task was successfully canceled.
  8233. */
  8234. interval.cancel = function(promise) {
  8235. if (promise && promise.$$intervalId in intervals) {
  8236. intervals[promise.$$intervalId].reject('canceled');
  8237. $window.clearInterval(promise.$$intervalId);
  8238. delete intervals[promise.$$intervalId];
  8239. return true;
  8240. }
  8241. return false;
  8242. };
  8243. return interval;
  8244. }];
  8245. }
  8246. /**
  8247. * @ngdoc service
  8248. * @name $locale
  8249. *
  8250. * @description
  8251. * $locale service provides localization rules for various Angular components. As of right now the
  8252. * only public api is:
  8253. *
  8254. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8255. */
  8256. function $LocaleProvider(){
  8257. this.$get = function() {
  8258. return {
  8259. id: 'en-us',
  8260. NUMBER_FORMATS: {
  8261. DECIMAL_SEP: '.',
  8262. GROUP_SEP: ',',
  8263. PATTERNS: [
  8264. { // Decimal Pattern
  8265. minInt: 1,
  8266. minFrac: 0,
  8267. maxFrac: 3,
  8268. posPre: '',
  8269. posSuf: '',
  8270. negPre: '-',
  8271. negSuf: '',
  8272. gSize: 3,
  8273. lgSize: 3
  8274. },{ //Currency Pattern
  8275. minInt: 1,
  8276. minFrac: 2,
  8277. maxFrac: 2,
  8278. posPre: '\u00A4',
  8279. posSuf: '',
  8280. negPre: '(\u00A4',
  8281. negSuf: ')',
  8282. gSize: 3,
  8283. lgSize: 3
  8284. }
  8285. ],
  8286. CURRENCY_SYM: '$'
  8287. },
  8288. DATETIME_FORMATS: {
  8289. MONTH:
  8290. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8291. .split(','),
  8292. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8293. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8294. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8295. AMPMS: ['AM','PM'],
  8296. medium: 'MMM d, y h:mm:ss a',
  8297. short: 'M/d/yy h:mm a',
  8298. fullDate: 'EEEE, MMMM d, y',
  8299. longDate: 'MMMM d, y',
  8300. mediumDate: 'MMM d, y',
  8301. shortDate: 'M/d/yy',
  8302. mediumTime: 'h:mm:ss a',
  8303. shortTime: 'h:mm a'
  8304. },
  8305. pluralCat: function(num) {
  8306. if (num === 1) {
  8307. return 'one';
  8308. }
  8309. return 'other';
  8310. }
  8311. };
  8312. };
  8313. }
  8314. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8315. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8316. var $locationMinErr = minErr('$location');
  8317. /**
  8318. * Encode path using encodeUriSegment, ignoring forward slashes
  8319. *
  8320. * @param {string} path Path to encode
  8321. * @returns {string}
  8322. */
  8323. function encodePath(path) {
  8324. var segments = path.split('/'),
  8325. i = segments.length;
  8326. while (i--) {
  8327. segments[i] = encodeUriSegment(segments[i]);
  8328. }
  8329. return segments.join('/');
  8330. }
  8331. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8332. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8333. locationObj.$$protocol = parsedUrl.protocol;
  8334. locationObj.$$host = parsedUrl.hostname;
  8335. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8336. }
  8337. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8338. var prefixed = (relativeUrl.charAt(0) !== '/');
  8339. if (prefixed) {
  8340. relativeUrl = '/' + relativeUrl;
  8341. }
  8342. var match = urlResolve(relativeUrl, appBase);
  8343. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8344. match.pathname.substring(1) : match.pathname);
  8345. locationObj.$$search = parseKeyValue(match.search);
  8346. locationObj.$$hash = decodeURIComponent(match.hash);
  8347. // make sure path starts with '/';
  8348. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8349. locationObj.$$path = '/' + locationObj.$$path;
  8350. }
  8351. }
  8352. /**
  8353. *
  8354. * @param {string} begin
  8355. * @param {string} whole
  8356. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8357. * expected string.
  8358. */
  8359. function beginsWith(begin, whole) {
  8360. if (whole.indexOf(begin) === 0) {
  8361. return whole.substr(begin.length);
  8362. }
  8363. }
  8364. function stripHash(url) {
  8365. var index = url.indexOf('#');
  8366. return index == -1 ? url : url.substr(0, index);
  8367. }
  8368. function stripFile(url) {
  8369. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8370. }
  8371. /* return the server only (scheme://host:port) */
  8372. function serverBase(url) {
  8373. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8374. }
  8375. /**
  8376. * LocationHtml5Url represents an url
  8377. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8378. *
  8379. * @constructor
  8380. * @param {string} appBase application base URL
  8381. * @param {string} basePrefix url path prefix
  8382. */
  8383. function LocationHtml5Url(appBase, basePrefix) {
  8384. this.$$html5 = true;
  8385. basePrefix = basePrefix || '';
  8386. var appBaseNoFile = stripFile(appBase);
  8387. parseAbsoluteUrl(appBase, this, appBase);
  8388. /**
  8389. * Parse given html5 (regular) url string into properties
  8390. * @param {string} newAbsoluteUrl HTML5 url
  8391. * @private
  8392. */
  8393. this.$$parse = function(url) {
  8394. var pathUrl = beginsWith(appBaseNoFile, url);
  8395. if (!isString(pathUrl)) {
  8396. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8397. appBaseNoFile);
  8398. }
  8399. parseAppUrl(pathUrl, this, appBase);
  8400. if (!this.$$path) {
  8401. this.$$path = '/';
  8402. }
  8403. this.$$compose();
  8404. };
  8405. /**
  8406. * Compose url and update `absUrl` property
  8407. * @private
  8408. */
  8409. this.$$compose = function() {
  8410. var search = toKeyValue(this.$$search),
  8411. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8412. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8413. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8414. };
  8415. this.$$parseLinkUrl = function(url, relHref) {
  8416. var appUrl, prevAppUrl;
  8417. var rewrittenUrl;
  8418. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8419. prevAppUrl = appUrl;
  8420. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8421. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8422. } else {
  8423. rewrittenUrl = appBase + prevAppUrl;
  8424. }
  8425. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8426. rewrittenUrl = appBaseNoFile + appUrl;
  8427. } else if (appBaseNoFile == url + '/') {
  8428. rewrittenUrl = appBaseNoFile;
  8429. }
  8430. if (rewrittenUrl) {
  8431. this.$$parse(rewrittenUrl);
  8432. }
  8433. return !!rewrittenUrl;
  8434. };
  8435. }
  8436. /**
  8437. * LocationHashbangUrl represents url
  8438. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8439. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8440. *
  8441. * @constructor
  8442. * @param {string} appBase application base URL
  8443. * @param {string} hashPrefix hashbang prefix
  8444. */
  8445. function LocationHashbangUrl(appBase, hashPrefix) {
  8446. var appBaseNoFile = stripFile(appBase);
  8447. parseAbsoluteUrl(appBase, this, appBase);
  8448. /**
  8449. * Parse given hashbang url into properties
  8450. * @param {string} url Hashbang url
  8451. * @private
  8452. */
  8453. this.$$parse = function(url) {
  8454. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8455. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8456. ? beginsWith(hashPrefix, withoutBaseUrl)
  8457. : (this.$$html5)
  8458. ? withoutBaseUrl
  8459. : '';
  8460. if (!isString(withoutHashUrl)) {
  8461. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8462. hashPrefix);
  8463. }
  8464. parseAppUrl(withoutHashUrl, this, appBase);
  8465. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8466. this.$$compose();
  8467. /*
  8468. * In Windows, on an anchor node on documents loaded from
  8469. * the filesystem, the browser will return a pathname
  8470. * prefixed with the drive name ('/C:/path') when a
  8471. * pathname without a drive is set:
  8472. * * a.setAttribute('href', '/foo')
  8473. * * a.pathname === '/C:/foo' //true
  8474. *
  8475. * Inside of Angular, we're always using pathnames that
  8476. * do not include drive names for routing.
  8477. */
  8478. function removeWindowsDriveName (path, url, base) {
  8479. /*
  8480. Matches paths for file protocol on windows,
  8481. such as /C:/foo/bar, and captures only /foo/bar.
  8482. */
  8483. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  8484. var firstPathSegmentMatch;
  8485. //Get the relative path from the input URL.
  8486. if (url.indexOf(base) === 0) {
  8487. url = url.replace(base, '');
  8488. }
  8489. // The input URL intentionally contains a first path segment that ends with a colon.
  8490. if (windowsFilePathExp.exec(url)) {
  8491. return path;
  8492. }
  8493. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8494. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8495. }
  8496. };
  8497. /**
  8498. * Compose hashbang url and update `absUrl` property
  8499. * @private
  8500. */
  8501. this.$$compose = function() {
  8502. var search = toKeyValue(this.$$search),
  8503. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8504. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8505. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8506. };
  8507. this.$$parseLinkUrl = function(url, relHref) {
  8508. if(stripHash(appBase) == stripHash(url)) {
  8509. this.$$parse(url);
  8510. return true;
  8511. }
  8512. return false;
  8513. };
  8514. }
  8515. /**
  8516. * LocationHashbangUrl represents url
  8517. * This object is exposed as $location service when html5 history api is enabled but the browser
  8518. * does not support it.
  8519. *
  8520. * @constructor
  8521. * @param {string} appBase application base URL
  8522. * @param {string} hashPrefix hashbang prefix
  8523. */
  8524. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8525. this.$$html5 = true;
  8526. LocationHashbangUrl.apply(this, arguments);
  8527. var appBaseNoFile = stripFile(appBase);
  8528. this.$$parseLinkUrl = function(url, relHref) {
  8529. var rewrittenUrl;
  8530. var appUrl;
  8531. if ( appBase == stripHash(url) ) {
  8532. rewrittenUrl = url;
  8533. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8534. rewrittenUrl = appBase + hashPrefix + appUrl;
  8535. } else if ( appBaseNoFile === url + '/') {
  8536. rewrittenUrl = appBaseNoFile;
  8537. }
  8538. if (rewrittenUrl) {
  8539. this.$$parse(rewrittenUrl);
  8540. }
  8541. return !!rewrittenUrl;
  8542. };
  8543. this.$$compose = function() {
  8544. var search = toKeyValue(this.$$search),
  8545. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8546. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8547. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  8548. this.$$absUrl = appBase + hashPrefix + this.$$url;
  8549. };
  8550. }
  8551. LocationHashbangInHtml5Url.prototype =
  8552. LocationHashbangUrl.prototype =
  8553. LocationHtml5Url.prototype = {
  8554. /**
  8555. * Are we in html5 mode?
  8556. * @private
  8557. */
  8558. $$html5: false,
  8559. /**
  8560. * Has any change been replacing ?
  8561. * @private
  8562. */
  8563. $$replace: false,
  8564. /**
  8565. * @ngdoc method
  8566. * @name $location#absUrl
  8567. *
  8568. * @description
  8569. * This method is getter only.
  8570. *
  8571. * Return full url representation with all segments encoded according to rules specified in
  8572. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8573. *
  8574. * @return {string} full url
  8575. */
  8576. absUrl: locationGetter('$$absUrl'),
  8577. /**
  8578. * @ngdoc method
  8579. * @name $location#url
  8580. *
  8581. * @description
  8582. * This method is getter / setter.
  8583. *
  8584. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8585. *
  8586. * Change path, search and hash, when called with parameter and return `$location`.
  8587. *
  8588. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8589. * @return {string} url
  8590. */
  8591. url: function(url) {
  8592. if (isUndefined(url))
  8593. return this.$$url;
  8594. var match = PATH_MATCH.exec(url);
  8595. if (match[1]) this.path(decodeURIComponent(match[1]));
  8596. if (match[2] || match[1]) this.search(match[3] || '');
  8597. this.hash(match[5] || '');
  8598. return this;
  8599. },
  8600. /**
  8601. * @ngdoc method
  8602. * @name $location#protocol
  8603. *
  8604. * @description
  8605. * This method is getter only.
  8606. *
  8607. * Return protocol of current url.
  8608. *
  8609. * @return {string} protocol of current url
  8610. */
  8611. protocol: locationGetter('$$protocol'),
  8612. /**
  8613. * @ngdoc method
  8614. * @name $location#host
  8615. *
  8616. * @description
  8617. * This method is getter only.
  8618. *
  8619. * Return host of current url.
  8620. *
  8621. * @return {string} host of current url.
  8622. */
  8623. host: locationGetter('$$host'),
  8624. /**
  8625. * @ngdoc method
  8626. * @name $location#port
  8627. *
  8628. * @description
  8629. * This method is getter only.
  8630. *
  8631. * Return port of current url.
  8632. *
  8633. * @return {Number} port
  8634. */
  8635. port: locationGetter('$$port'),
  8636. /**
  8637. * @ngdoc method
  8638. * @name $location#path
  8639. *
  8640. * @description
  8641. * This method is getter / setter.
  8642. *
  8643. * Return path of current url when called without any parameter.
  8644. *
  8645. * Change path when called with parameter and return `$location`.
  8646. *
  8647. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8648. * if it is missing.
  8649. *
  8650. * @param {(string|number)=} path New path
  8651. * @return {string} path
  8652. */
  8653. path: locationGetterSetter('$$path', function(path) {
  8654. path = path !== null ? path.toString() : '';
  8655. return path.charAt(0) == '/' ? path : '/' + path;
  8656. }),
  8657. /**
  8658. * @ngdoc method
  8659. * @name $location#search
  8660. *
  8661. * @description
  8662. * This method is getter / setter.
  8663. *
  8664. * Return search part (as object) of current url when called without any parameter.
  8665. *
  8666. * Change search part when called with parameter and return `$location`.
  8667. *
  8668. *
  8669. * ```js
  8670. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  8671. * var searchObject = $location.search();
  8672. * // => {foo: 'bar', baz: 'xoxo'}
  8673. *
  8674. *
  8675. * // set foo to 'yipee'
  8676. * $location.search('foo', 'yipee');
  8677. * // => $location
  8678. * ```
  8679. *
  8680. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8681. * hash object.
  8682. *
  8683. * When called with a single argument the method acts as a setter, setting the `search` component
  8684. * of `$location` to the specified value.
  8685. *
  8686. * If the argument is a hash object containing an array of values, these values will be encoded
  8687. * as duplicate search parameters in the url.
  8688. *
  8689. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  8690. * will override only a single search property.
  8691. *
  8692. * If `paramValue` is an array, it will override the property of the `search` component of
  8693. * `$location` specified via the first argument.
  8694. *
  8695. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  8696. *
  8697. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  8698. * value nor trailing equal sign.
  8699. *
  8700. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  8701. * one or more arguments returns `$location` object itself.
  8702. */
  8703. search: function(search, paramValue) {
  8704. switch (arguments.length) {
  8705. case 0:
  8706. return this.$$search;
  8707. case 1:
  8708. if (isString(search) || isNumber(search)) {
  8709. search = search.toString();
  8710. this.$$search = parseKeyValue(search);
  8711. } else if (isObject(search)) {
  8712. // remove object undefined or null properties
  8713. forEach(search, function(value, key) {
  8714. if (value == null) delete search[key];
  8715. });
  8716. this.$$search = search;
  8717. } else {
  8718. throw $locationMinErr('isrcharg',
  8719. 'The first argument of the `$location#search()` call must be a string or an object.');
  8720. }
  8721. break;
  8722. default:
  8723. if (isUndefined(paramValue) || paramValue === null) {
  8724. delete this.$$search[search];
  8725. } else {
  8726. this.$$search[search] = paramValue;
  8727. }
  8728. }
  8729. this.$$compose();
  8730. return this;
  8731. },
  8732. /**
  8733. * @ngdoc method
  8734. * @name $location#hash
  8735. *
  8736. * @description
  8737. * This method is getter / setter.
  8738. *
  8739. * Return hash fragment when called without any parameter.
  8740. *
  8741. * Change hash fragment when called with parameter and return `$location`.
  8742. *
  8743. * @param {(string|number)=} hash New hash fragment
  8744. * @return {string} hash
  8745. */
  8746. hash: locationGetterSetter('$$hash', function(hash) {
  8747. return hash !== null ? hash.toString() : '';
  8748. }),
  8749. /**
  8750. * @ngdoc method
  8751. * @name $location#replace
  8752. *
  8753. * @description
  8754. * If called, all changes to $location during current `$digest` will be replacing current history
  8755. * record, instead of adding new one.
  8756. */
  8757. replace: function() {
  8758. this.$$replace = true;
  8759. return this;
  8760. }
  8761. };
  8762. function locationGetter(property) {
  8763. return function() {
  8764. return this[property];
  8765. };
  8766. }
  8767. function locationGetterSetter(property, preprocess) {
  8768. return function(value) {
  8769. if (isUndefined(value))
  8770. return this[property];
  8771. this[property] = preprocess(value);
  8772. this.$$compose();
  8773. return this;
  8774. };
  8775. }
  8776. /**
  8777. * @ngdoc service
  8778. * @name $location
  8779. *
  8780. * @requires $rootElement
  8781. *
  8782. * @description
  8783. * The $location service parses the URL in the browser address bar (based on the
  8784. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8785. * available to your application. Changes to the URL in the address bar are reflected into
  8786. * $location service and changes to $location are reflected into the browser address bar.
  8787. *
  8788. * **The $location service:**
  8789. *
  8790. * - Exposes the current URL in the browser address bar, so you can
  8791. * - Watch and observe the URL.
  8792. * - Change the URL.
  8793. * - Synchronizes the URL with the browser when the user
  8794. * - Changes the address bar.
  8795. * - Clicks the back or forward button (or clicks a History link).
  8796. * - Clicks on a link.
  8797. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8798. *
  8799. * For more information see {@link guide/$location Developer Guide: Using $location}
  8800. */
  8801. /**
  8802. * @ngdoc provider
  8803. * @name $locationProvider
  8804. * @description
  8805. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8806. */
  8807. function $LocationProvider(){
  8808. var hashPrefix = '',
  8809. html5Mode = false;
  8810. /**
  8811. * @ngdoc method
  8812. * @name $locationProvider#hashPrefix
  8813. * @description
  8814. * @param {string=} prefix Prefix for hash part (containing path and search)
  8815. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8816. */
  8817. this.hashPrefix = function(prefix) {
  8818. if (isDefined(prefix)) {
  8819. hashPrefix = prefix;
  8820. return this;
  8821. } else {
  8822. return hashPrefix;
  8823. }
  8824. };
  8825. /**
  8826. * @ngdoc method
  8827. * @name $locationProvider#html5Mode
  8828. * @description
  8829. * @param {boolean=} mode Use HTML5 strategy if available.
  8830. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8831. */
  8832. this.html5Mode = function(mode) {
  8833. if (isDefined(mode)) {
  8834. html5Mode = mode;
  8835. return this;
  8836. } else {
  8837. return html5Mode;
  8838. }
  8839. };
  8840. /**
  8841. * @ngdoc event
  8842. * @name $location#$locationChangeStart
  8843. * @eventType broadcast on root scope
  8844. * @description
  8845. * Broadcasted before a URL will change. This change can be prevented by calling
  8846. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8847. * details about event object. Upon successful change
  8848. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8849. *
  8850. * @param {Object} angularEvent Synthetic event object.
  8851. * @param {string} newUrl New URL
  8852. * @param {string=} oldUrl URL that was before it was changed.
  8853. */
  8854. /**
  8855. * @ngdoc event
  8856. * @name $location#$locationChangeSuccess
  8857. * @eventType broadcast on root scope
  8858. * @description
  8859. * Broadcasted after a URL was changed.
  8860. *
  8861. * @param {Object} angularEvent Synthetic event object.
  8862. * @param {string} newUrl New URL
  8863. * @param {string=} oldUrl URL that was before it was changed.
  8864. */
  8865. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8866. function( $rootScope, $browser, $sniffer, $rootElement) {
  8867. var $location,
  8868. LocationMode,
  8869. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8870. initialUrl = $browser.url(),
  8871. appBase;
  8872. if (html5Mode) {
  8873. appBase = serverBase(initialUrl) + (baseHref || '/');
  8874. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8875. } else {
  8876. appBase = stripHash(initialUrl);
  8877. LocationMode = LocationHashbangUrl;
  8878. }
  8879. $location = new LocationMode(appBase, '#' + hashPrefix);
  8880. $location.$$parseLinkUrl(initialUrl, initialUrl);
  8881. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  8882. $rootElement.on('click', function(event) {
  8883. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8884. // currently we open nice url link and redirect then
  8885. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8886. var elm = jqLite(event.target);
  8887. // traverse the DOM up to find first A tag
  8888. while (lowercase(elm[0].nodeName) !== 'a') {
  8889. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8890. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8891. }
  8892. var absHref = elm.prop('href');
  8893. // get the actual href attribute - see
  8894. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  8895. var relHref = elm.attr('href') || elm.attr('xlink:href');
  8896. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8897. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8898. // an animation.
  8899. absHref = urlResolve(absHref.animVal).href;
  8900. }
  8901. // Ignore when url is started with javascript: or mailto:
  8902. if (IGNORE_URI_REGEXP.test(absHref)) return;
  8903. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  8904. if ($location.$$parseLinkUrl(absHref, relHref)) {
  8905. // We do a preventDefault for all urls that are part of the angular application,
  8906. // in html5mode and also without, so that we are able to abort navigation without
  8907. // getting double entries in the location history.
  8908. event.preventDefault();
  8909. // update location manually
  8910. if ($location.absUrl() != $browser.url()) {
  8911. $rootScope.$apply();
  8912. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8913. window.angular['ff-684208-preventDefault'] = true;
  8914. }
  8915. }
  8916. }
  8917. });
  8918. // rewrite hashbang url <> html5 url
  8919. if ($location.absUrl() != initialUrl) {
  8920. $browser.url($location.absUrl(), true);
  8921. }
  8922. // update $location when $browser url changes
  8923. $browser.onUrlChange(function(newUrl) {
  8924. if ($location.absUrl() != newUrl) {
  8925. $rootScope.$evalAsync(function() {
  8926. var oldUrl = $location.absUrl();
  8927. $location.$$parse(newUrl);
  8928. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8929. oldUrl).defaultPrevented) {
  8930. $location.$$parse(oldUrl);
  8931. $browser.url(oldUrl);
  8932. } else {
  8933. afterLocationChange(oldUrl);
  8934. }
  8935. });
  8936. if (!$rootScope.$$phase) $rootScope.$digest();
  8937. }
  8938. });
  8939. // update browser
  8940. var changeCounter = 0;
  8941. $rootScope.$watch(function $locationWatch() {
  8942. var oldUrl = $browser.url();
  8943. var currentReplace = $location.$$replace;
  8944. if (!changeCounter || oldUrl != $location.absUrl()) {
  8945. changeCounter++;
  8946. $rootScope.$evalAsync(function() {
  8947. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8948. defaultPrevented) {
  8949. $location.$$parse(oldUrl);
  8950. } else {
  8951. $browser.url($location.absUrl(), currentReplace);
  8952. afterLocationChange(oldUrl);
  8953. }
  8954. });
  8955. }
  8956. $location.$$replace = false;
  8957. return changeCounter;
  8958. });
  8959. return $location;
  8960. function afterLocationChange(oldUrl) {
  8961. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8962. }
  8963. }];
  8964. }
  8965. /**
  8966. * @ngdoc service
  8967. * @name $log
  8968. * @requires $window
  8969. *
  8970. * @description
  8971. * Simple service for logging. Default implementation safely writes the message
  8972. * into the browser's console (if present).
  8973. *
  8974. * The main purpose of this service is to simplify debugging and troubleshooting.
  8975. *
  8976. * The default is to log `debug` messages. You can use
  8977. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8978. *
  8979. * @example
  8980. <example module="logExample">
  8981. <file name="script.js">
  8982. angular.module('logExample', [])
  8983. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  8984. $scope.$log = $log;
  8985. $scope.message = 'Hello World!';
  8986. }]);
  8987. </file>
  8988. <file name="index.html">
  8989. <div ng-controller="LogController">
  8990. <p>Reload this page with open console, enter text and hit the log button...</p>
  8991. Message:
  8992. <input type="text" ng-model="message"/>
  8993. <button ng-click="$log.log(message)">log</button>
  8994. <button ng-click="$log.warn(message)">warn</button>
  8995. <button ng-click="$log.info(message)">info</button>
  8996. <button ng-click="$log.error(message)">error</button>
  8997. </div>
  8998. </file>
  8999. </example>
  9000. */
  9001. /**
  9002. * @ngdoc provider
  9003. * @name $logProvider
  9004. * @description
  9005. * Use the `$logProvider` to configure how the application logs messages
  9006. */
  9007. function $LogProvider(){
  9008. var debug = true,
  9009. self = this;
  9010. /**
  9011. * @ngdoc method
  9012. * @name $logProvider#debugEnabled
  9013. * @description
  9014. * @param {boolean=} flag enable or disable debug level messages
  9015. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9016. */
  9017. this.debugEnabled = function(flag) {
  9018. if (isDefined(flag)) {
  9019. debug = flag;
  9020. return this;
  9021. } else {
  9022. return debug;
  9023. }
  9024. };
  9025. this.$get = ['$window', function($window){
  9026. return {
  9027. /**
  9028. * @ngdoc method
  9029. * @name $log#log
  9030. *
  9031. * @description
  9032. * Write a log message
  9033. */
  9034. log: consoleLog('log'),
  9035. /**
  9036. * @ngdoc method
  9037. * @name $log#info
  9038. *
  9039. * @description
  9040. * Write an information message
  9041. */
  9042. info: consoleLog('info'),
  9043. /**
  9044. * @ngdoc method
  9045. * @name $log#warn
  9046. *
  9047. * @description
  9048. * Write a warning message
  9049. */
  9050. warn: consoleLog('warn'),
  9051. /**
  9052. * @ngdoc method
  9053. * @name $log#error
  9054. *
  9055. * @description
  9056. * Write an error message
  9057. */
  9058. error: consoleLog('error'),
  9059. /**
  9060. * @ngdoc method
  9061. * @name $log#debug
  9062. *
  9063. * @description
  9064. * Write a debug message
  9065. */
  9066. debug: (function () {
  9067. var fn = consoleLog('debug');
  9068. return function() {
  9069. if (debug) {
  9070. fn.apply(self, arguments);
  9071. }
  9072. };
  9073. }())
  9074. };
  9075. function formatError(arg) {
  9076. if (arg instanceof Error) {
  9077. if (arg.stack) {
  9078. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  9079. ? 'Error: ' + arg.message + '\n' + arg.stack
  9080. : arg.stack;
  9081. } else if (arg.sourceURL) {
  9082. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  9083. }
  9084. }
  9085. return arg;
  9086. }
  9087. function consoleLog(type) {
  9088. var console = $window.console || {},
  9089. logFn = console[type] || console.log || noop,
  9090. hasApply = false;
  9091. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  9092. // The reason behind this is that console.log has type "object" in IE8...
  9093. try {
  9094. hasApply = !!logFn.apply;
  9095. } catch (e) {}
  9096. if (hasApply) {
  9097. return function() {
  9098. var args = [];
  9099. forEach(arguments, function(arg) {
  9100. args.push(formatError(arg));
  9101. });
  9102. return logFn.apply(console, args);
  9103. };
  9104. }
  9105. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  9106. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  9107. return function(arg1, arg2) {
  9108. logFn(arg1, arg2 == null ? '' : arg2);
  9109. };
  9110. }
  9111. }];
  9112. }
  9113. var $parseMinErr = minErr('$parse');
  9114. var promiseWarningCache = {};
  9115. var promiseWarning;
  9116. // Sandboxing Angular Expressions
  9117. // ------------------------------
  9118. // Angular expressions are generally considered safe because these expressions only have direct
  9119. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  9120. // obtaining a reference to native JS functions such as the Function constructor.
  9121. //
  9122. // As an example, consider the following Angular expression:
  9123. //
  9124. // {}.toString.constructor('alert("evil JS code")')
  9125. //
  9126. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  9127. // against the expression language, but not to prevent exploits that were enabled by exposing
  9128. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  9129. // practice and therefore we are not even trying to protect against interaction with an object
  9130. // explicitly exposed in this way.
  9131. //
  9132. // In general, it is not possible to access a Window object from an angular expression unless a
  9133. // window or some DOM object that has a reference to window is published onto a Scope.
  9134. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  9135. // native objects.
  9136. //
  9137. // See https://docs.angularjs.org/guide/security
  9138. function ensureSafeMemberName(name, fullExpression) {
  9139. if (name === "__defineGetter__" || name === "__defineSetter__"
  9140. || name === "__lookupGetter__" || name === "__lookupSetter__"
  9141. || name === "__proto__") {
  9142. throw $parseMinErr('isecfld',
  9143. 'Attempting to access a disallowed field in Angular expressions! '
  9144. +'Expression: {0}', fullExpression);
  9145. }
  9146. return name;
  9147. }
  9148. function ensureSafeObject(obj, fullExpression) {
  9149. // nifty check if obj is Function that is fast and works across iframes and other contexts
  9150. if (obj) {
  9151. if (obj.constructor === obj) {
  9152. throw $parseMinErr('isecfn',
  9153. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9154. fullExpression);
  9155. } else if (// isWindow(obj)
  9156. obj.document && obj.location && obj.alert && obj.setInterval) {
  9157. throw $parseMinErr('isecwindow',
  9158. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  9159. fullExpression);
  9160. } else if (// isElement(obj)
  9161. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  9162. throw $parseMinErr('isecdom',
  9163. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  9164. fullExpression);
  9165. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  9166. obj === Object) {
  9167. throw $parseMinErr('isecobj',
  9168. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  9169. fullExpression);
  9170. }
  9171. }
  9172. return obj;
  9173. }
  9174. var CALL = Function.prototype.call;
  9175. var APPLY = Function.prototype.apply;
  9176. var BIND = Function.prototype.bind;
  9177. function ensureSafeFunction(obj, fullExpression) {
  9178. if (obj) {
  9179. if (obj.constructor === obj) {
  9180. throw $parseMinErr('isecfn',
  9181. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9182. fullExpression);
  9183. } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
  9184. throw $parseMinErr('isecff',
  9185. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  9186. fullExpression);
  9187. }
  9188. }
  9189. }
  9190. var OPERATORS = {
  9191. /* jshint bitwise : false */
  9192. 'null':function(){return null;},
  9193. 'true':function(){return true;},
  9194. 'false':function(){return false;},
  9195. undefined:noop,
  9196. '+':function(self, locals, a,b){
  9197. a=a(self, locals); b=b(self, locals);
  9198. if (isDefined(a)) {
  9199. if (isDefined(b)) {
  9200. return a + b;
  9201. }
  9202. return a;
  9203. }
  9204. return isDefined(b)?b:undefined;},
  9205. '-':function(self, locals, a,b){
  9206. a=a(self, locals); b=b(self, locals);
  9207. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  9208. },
  9209. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  9210. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  9211. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  9212. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  9213. '=':noop,
  9214. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  9215. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  9216. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  9217. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  9218. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  9219. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  9220. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  9221. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  9222. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  9223. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  9224. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  9225. // '|':function(self, locals, a,b){return a|b;},
  9226. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  9227. '!':function(self, locals, a){return !a(self, locals);}
  9228. };
  9229. /* jshint bitwise: true */
  9230. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  9231. /////////////////////////////////////////
  9232. /**
  9233. * @constructor
  9234. */
  9235. var Lexer = function (options) {
  9236. this.options = options;
  9237. };
  9238. Lexer.prototype = {
  9239. constructor: Lexer,
  9240. lex: function (text) {
  9241. this.text = text;
  9242. this.index = 0;
  9243. this.ch = undefined;
  9244. this.lastCh = ':'; // can start regexp
  9245. this.tokens = [];
  9246. while (this.index < this.text.length) {
  9247. this.ch = this.text.charAt(this.index);
  9248. if (this.is('"\'')) {
  9249. this.readString(this.ch);
  9250. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  9251. this.readNumber();
  9252. } else if (this.isIdent(this.ch)) {
  9253. this.readIdent();
  9254. } else if (this.is('(){}[].,;:?')) {
  9255. this.tokens.push({
  9256. index: this.index,
  9257. text: this.ch
  9258. });
  9259. this.index++;
  9260. } else if (this.isWhitespace(this.ch)) {
  9261. this.index++;
  9262. continue;
  9263. } else {
  9264. var ch2 = this.ch + this.peek();
  9265. var ch3 = ch2 + this.peek(2);
  9266. var fn = OPERATORS[this.ch];
  9267. var fn2 = OPERATORS[ch2];
  9268. var fn3 = OPERATORS[ch3];
  9269. if (fn3) {
  9270. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  9271. this.index += 3;
  9272. } else if (fn2) {
  9273. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  9274. this.index += 2;
  9275. } else if (fn) {
  9276. this.tokens.push({
  9277. index: this.index,
  9278. text: this.ch,
  9279. fn: fn
  9280. });
  9281. this.index += 1;
  9282. } else {
  9283. this.throwError('Unexpected next character ', this.index, this.index + 1);
  9284. }
  9285. }
  9286. this.lastCh = this.ch;
  9287. }
  9288. return this.tokens;
  9289. },
  9290. is: function(chars) {
  9291. return chars.indexOf(this.ch) !== -1;
  9292. },
  9293. was: function(chars) {
  9294. return chars.indexOf(this.lastCh) !== -1;
  9295. },
  9296. peek: function(i) {
  9297. var num = i || 1;
  9298. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  9299. },
  9300. isNumber: function(ch) {
  9301. return ('0' <= ch && ch <= '9');
  9302. },
  9303. isWhitespace: function(ch) {
  9304. // IE treats non-breaking space as \u00A0
  9305. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9306. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9307. },
  9308. isIdent: function(ch) {
  9309. return ('a' <= ch && ch <= 'z' ||
  9310. 'A' <= ch && ch <= 'Z' ||
  9311. '_' === ch || ch === '$');
  9312. },
  9313. isExpOperator: function(ch) {
  9314. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9315. },
  9316. throwError: function(error, start, end) {
  9317. end = end || this.index;
  9318. var colStr = (isDefined(start)
  9319. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9320. : ' ' + end);
  9321. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9322. error, colStr, this.text);
  9323. },
  9324. readNumber: function() {
  9325. var number = '';
  9326. var start = this.index;
  9327. while (this.index < this.text.length) {
  9328. var ch = lowercase(this.text.charAt(this.index));
  9329. if (ch == '.' || this.isNumber(ch)) {
  9330. number += ch;
  9331. } else {
  9332. var peekCh = this.peek();
  9333. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9334. number += ch;
  9335. } else if (this.isExpOperator(ch) &&
  9336. peekCh && this.isNumber(peekCh) &&
  9337. number.charAt(number.length - 1) == 'e') {
  9338. number += ch;
  9339. } else if (this.isExpOperator(ch) &&
  9340. (!peekCh || !this.isNumber(peekCh)) &&
  9341. number.charAt(number.length - 1) == 'e') {
  9342. this.throwError('Invalid exponent');
  9343. } else {
  9344. break;
  9345. }
  9346. }
  9347. this.index++;
  9348. }
  9349. number = 1 * number;
  9350. this.tokens.push({
  9351. index: start,
  9352. text: number,
  9353. literal: true,
  9354. constant: true,
  9355. fn: function() { return number; }
  9356. });
  9357. },
  9358. readIdent: function() {
  9359. var parser = this;
  9360. var ident = '';
  9361. var start = this.index;
  9362. var lastDot, peekIndex, methodName, ch;
  9363. while (this.index < this.text.length) {
  9364. ch = this.text.charAt(this.index);
  9365. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9366. if (ch === '.') lastDot = this.index;
  9367. ident += ch;
  9368. } else {
  9369. break;
  9370. }
  9371. this.index++;
  9372. }
  9373. //check if this is not a method invocation and if it is back out to last dot
  9374. if (lastDot) {
  9375. peekIndex = this.index;
  9376. while (peekIndex < this.text.length) {
  9377. ch = this.text.charAt(peekIndex);
  9378. if (ch === '(') {
  9379. methodName = ident.substr(lastDot - start + 1);
  9380. ident = ident.substr(0, lastDot - start);
  9381. this.index = peekIndex;
  9382. break;
  9383. }
  9384. if (this.isWhitespace(ch)) {
  9385. peekIndex++;
  9386. } else {
  9387. break;
  9388. }
  9389. }
  9390. }
  9391. var token = {
  9392. index: start,
  9393. text: ident
  9394. };
  9395. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9396. if (OPERATORS.hasOwnProperty(ident)) {
  9397. token.fn = OPERATORS[ident];
  9398. token.literal = true;
  9399. token.constant = true;
  9400. } else {
  9401. var getter = getterFn(ident, this.options, this.text);
  9402. token.fn = extend(function(self, locals) {
  9403. return (getter(self, locals));
  9404. }, {
  9405. assign: function(self, value) {
  9406. return setter(self, ident, value, parser.text, parser.options);
  9407. }
  9408. });
  9409. }
  9410. this.tokens.push(token);
  9411. if (methodName) {
  9412. this.tokens.push({
  9413. index:lastDot,
  9414. text: '.'
  9415. });
  9416. this.tokens.push({
  9417. index: lastDot + 1,
  9418. text: methodName
  9419. });
  9420. }
  9421. },
  9422. readString: function(quote) {
  9423. var start = this.index;
  9424. this.index++;
  9425. var string = '';
  9426. var rawString = quote;
  9427. var escape = false;
  9428. while (this.index < this.text.length) {
  9429. var ch = this.text.charAt(this.index);
  9430. rawString += ch;
  9431. if (escape) {
  9432. if (ch === 'u') {
  9433. var hex = this.text.substring(this.index + 1, this.index + 5);
  9434. if (!hex.match(/[\da-f]{4}/i))
  9435. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9436. this.index += 4;
  9437. string += String.fromCharCode(parseInt(hex, 16));
  9438. } else {
  9439. var rep = ESCAPE[ch];
  9440. string = string + (rep || ch);
  9441. }
  9442. escape = false;
  9443. } else if (ch === '\\') {
  9444. escape = true;
  9445. } else if (ch === quote) {
  9446. this.index++;
  9447. this.tokens.push({
  9448. index: start,
  9449. text: rawString,
  9450. string: string,
  9451. literal: true,
  9452. constant: true,
  9453. fn: function() { return string; }
  9454. });
  9455. return;
  9456. } else {
  9457. string += ch;
  9458. }
  9459. this.index++;
  9460. }
  9461. this.throwError('Unterminated quote', start);
  9462. }
  9463. };
  9464. /**
  9465. * @constructor
  9466. */
  9467. var Parser = function (lexer, $filter, options) {
  9468. this.lexer = lexer;
  9469. this.$filter = $filter;
  9470. this.options = options;
  9471. };
  9472. Parser.ZERO = extend(function () {
  9473. return 0;
  9474. }, {
  9475. constant: true
  9476. });
  9477. Parser.prototype = {
  9478. constructor: Parser,
  9479. parse: function (text) {
  9480. this.text = text;
  9481. this.tokens = this.lexer.lex(text);
  9482. var value = this.statements();
  9483. if (this.tokens.length !== 0) {
  9484. this.throwError('is an unexpected token', this.tokens[0]);
  9485. }
  9486. value.literal = !!value.literal;
  9487. value.constant = !!value.constant;
  9488. return value;
  9489. },
  9490. primary: function () {
  9491. var primary;
  9492. if (this.expect('(')) {
  9493. primary = this.filterChain();
  9494. this.consume(')');
  9495. } else if (this.expect('[')) {
  9496. primary = this.arrayDeclaration();
  9497. } else if (this.expect('{')) {
  9498. primary = this.object();
  9499. } else {
  9500. var token = this.expect();
  9501. primary = token.fn;
  9502. if (!primary) {
  9503. this.throwError('not a primary expression', token);
  9504. }
  9505. primary.literal = !!token.literal;
  9506. primary.constant = !!token.constant;
  9507. }
  9508. var next, context;
  9509. while ((next = this.expect('(', '[', '.'))) {
  9510. if (next.text === '(') {
  9511. primary = this.functionCall(primary, context);
  9512. context = null;
  9513. } else if (next.text === '[') {
  9514. context = primary;
  9515. primary = this.objectIndex(primary);
  9516. } else if (next.text === '.') {
  9517. context = primary;
  9518. primary = this.fieldAccess(primary);
  9519. } else {
  9520. this.throwError('IMPOSSIBLE');
  9521. }
  9522. }
  9523. return primary;
  9524. },
  9525. throwError: function(msg, token) {
  9526. throw $parseMinErr('syntax',
  9527. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9528. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9529. },
  9530. peekToken: function() {
  9531. if (this.tokens.length === 0)
  9532. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9533. return this.tokens[0];
  9534. },
  9535. peek: function(e1, e2, e3, e4) {
  9536. if (this.tokens.length > 0) {
  9537. var token = this.tokens[0];
  9538. var t = token.text;
  9539. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9540. (!e1 && !e2 && !e3 && !e4)) {
  9541. return token;
  9542. }
  9543. }
  9544. return false;
  9545. },
  9546. expect: function(e1, e2, e3, e4){
  9547. var token = this.peek(e1, e2, e3, e4);
  9548. if (token) {
  9549. this.tokens.shift();
  9550. return token;
  9551. }
  9552. return false;
  9553. },
  9554. consume: function(e1){
  9555. if (!this.expect(e1)) {
  9556. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9557. }
  9558. },
  9559. unaryFn: function(fn, right) {
  9560. return extend(function(self, locals) {
  9561. return fn(self, locals, right);
  9562. }, {
  9563. constant:right.constant
  9564. });
  9565. },
  9566. ternaryFn: function(left, middle, right){
  9567. return extend(function(self, locals){
  9568. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9569. }, {
  9570. constant: left.constant && middle.constant && right.constant
  9571. });
  9572. },
  9573. binaryFn: function(left, fn, right) {
  9574. return extend(function(self, locals) {
  9575. return fn(self, locals, left, right);
  9576. }, {
  9577. constant:left.constant && right.constant
  9578. });
  9579. },
  9580. statements: function() {
  9581. var statements = [];
  9582. while (true) {
  9583. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9584. statements.push(this.filterChain());
  9585. if (!this.expect(';')) {
  9586. // optimize for the common case where there is only one statement.
  9587. // TODO(size): maybe we should not support multiple statements?
  9588. return (statements.length === 1)
  9589. ? statements[0]
  9590. : function(self, locals) {
  9591. var value;
  9592. for (var i = 0; i < statements.length; i++) {
  9593. var statement = statements[i];
  9594. if (statement) {
  9595. value = statement(self, locals);
  9596. }
  9597. }
  9598. return value;
  9599. };
  9600. }
  9601. }
  9602. },
  9603. filterChain: function() {
  9604. var left = this.expression();
  9605. var token;
  9606. while (true) {
  9607. if ((token = this.expect('|'))) {
  9608. left = this.binaryFn(left, token.fn, this.filter());
  9609. } else {
  9610. return left;
  9611. }
  9612. }
  9613. },
  9614. filter: function() {
  9615. var token = this.expect();
  9616. var fn = this.$filter(token.text);
  9617. var argsFn = [];
  9618. while (true) {
  9619. if ((token = this.expect(':'))) {
  9620. argsFn.push(this.expression());
  9621. } else {
  9622. var fnInvoke = function(self, locals, input) {
  9623. var args = [input];
  9624. for (var i = 0; i < argsFn.length; i++) {
  9625. args.push(argsFn[i](self, locals));
  9626. }
  9627. return fn.apply(self, args);
  9628. };
  9629. return function() {
  9630. return fnInvoke;
  9631. };
  9632. }
  9633. }
  9634. },
  9635. expression: function() {
  9636. return this.assignment();
  9637. },
  9638. assignment: function() {
  9639. var left = this.ternary();
  9640. var right;
  9641. var token;
  9642. if ((token = this.expect('='))) {
  9643. if (!left.assign) {
  9644. this.throwError('implies assignment but [' +
  9645. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9646. }
  9647. right = this.ternary();
  9648. return function(scope, locals) {
  9649. return left.assign(scope, right(scope, locals), locals);
  9650. };
  9651. }
  9652. return left;
  9653. },
  9654. ternary: function() {
  9655. var left = this.logicalOR();
  9656. var middle;
  9657. var token;
  9658. if ((token = this.expect('?'))) {
  9659. middle = this.assignment();
  9660. if ((token = this.expect(':'))) {
  9661. return this.ternaryFn(left, middle, this.assignment());
  9662. } else {
  9663. this.throwError('expected :', token);
  9664. }
  9665. } else {
  9666. return left;
  9667. }
  9668. },
  9669. logicalOR: function() {
  9670. var left = this.logicalAND();
  9671. var token;
  9672. while (true) {
  9673. if ((token = this.expect('||'))) {
  9674. left = this.binaryFn(left, token.fn, this.logicalAND());
  9675. } else {
  9676. return left;
  9677. }
  9678. }
  9679. },
  9680. logicalAND: function() {
  9681. var left = this.equality();
  9682. var token;
  9683. if ((token = this.expect('&&'))) {
  9684. left = this.binaryFn(left, token.fn, this.logicalAND());
  9685. }
  9686. return left;
  9687. },
  9688. equality: function() {
  9689. var left = this.relational();
  9690. var token;
  9691. if ((token = this.expect('==','!=','===','!=='))) {
  9692. left = this.binaryFn(left, token.fn, this.equality());
  9693. }
  9694. return left;
  9695. },
  9696. relational: function() {
  9697. var left = this.additive();
  9698. var token;
  9699. if ((token = this.expect('<', '>', '<=', '>='))) {
  9700. left = this.binaryFn(left, token.fn, this.relational());
  9701. }
  9702. return left;
  9703. },
  9704. additive: function() {
  9705. var left = this.multiplicative();
  9706. var token;
  9707. while ((token = this.expect('+','-'))) {
  9708. left = this.binaryFn(left, token.fn, this.multiplicative());
  9709. }
  9710. return left;
  9711. },
  9712. multiplicative: function() {
  9713. var left = this.unary();
  9714. var token;
  9715. while ((token = this.expect('*','/','%'))) {
  9716. left = this.binaryFn(left, token.fn, this.unary());
  9717. }
  9718. return left;
  9719. },
  9720. unary: function() {
  9721. var token;
  9722. if (this.expect('+')) {
  9723. return this.primary();
  9724. } else if ((token = this.expect('-'))) {
  9725. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9726. } else if ((token = this.expect('!'))) {
  9727. return this.unaryFn(token.fn, this.unary());
  9728. } else {
  9729. return this.primary();
  9730. }
  9731. },
  9732. fieldAccess: function(object) {
  9733. var parser = this;
  9734. var field = this.expect().text;
  9735. var getter = getterFn(field, this.options, this.text);
  9736. return extend(function(scope, locals, self) {
  9737. return getter(self || object(scope, locals));
  9738. }, {
  9739. assign: function(scope, value, locals) {
  9740. var o = object(scope, locals);
  9741. if (!o) object.assign(scope, o = {});
  9742. return setter(o, field, value, parser.text, parser.options);
  9743. }
  9744. });
  9745. },
  9746. objectIndex: function(obj) {
  9747. var parser = this;
  9748. var indexFn = this.expression();
  9749. this.consume(']');
  9750. return extend(function(self, locals) {
  9751. var o = obj(self, locals),
  9752. i = indexFn(self, locals),
  9753. v, p;
  9754. ensureSafeMemberName(i, parser.text);
  9755. if (!o) return undefined;
  9756. v = ensureSafeObject(o[i], parser.text);
  9757. if (v && v.then && parser.options.unwrapPromises) {
  9758. p = v;
  9759. if (!('$$v' in v)) {
  9760. p.$$v = undefined;
  9761. p.then(function(val) { p.$$v = val; });
  9762. }
  9763. v = v.$$v;
  9764. }
  9765. return v;
  9766. }, {
  9767. assign: function(self, value, locals) {
  9768. var key = ensureSafeMemberName(indexFn(self, locals), parser.text);
  9769. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9770. var o = ensureSafeObject(obj(self, locals), parser.text);
  9771. if (!o) obj.assign(self, o = {});
  9772. return o[key] = value;
  9773. }
  9774. });
  9775. },
  9776. functionCall: function(fn, contextGetter) {
  9777. var argsFn = [];
  9778. if (this.peekToken().text !== ')') {
  9779. do {
  9780. argsFn.push(this.expression());
  9781. } while (this.expect(','));
  9782. }
  9783. this.consume(')');
  9784. var parser = this;
  9785. return function(scope, locals) {
  9786. var args = [];
  9787. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9788. for (var i = 0; i < argsFn.length; i++) {
  9789. args.push(ensureSafeObject(argsFn[i](scope, locals), parser.text));
  9790. }
  9791. var fnPtr = fn(scope, locals, context) || noop;
  9792. ensureSafeObject(context, parser.text);
  9793. ensureSafeFunction(fnPtr, parser.text);
  9794. // IE stupidity! (IE doesn't have apply for some native functions)
  9795. var v = fnPtr.apply
  9796. ? fnPtr.apply(context, args)
  9797. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9798. return ensureSafeObject(v, parser.text);
  9799. };
  9800. },
  9801. // This is used with json array declaration
  9802. arrayDeclaration: function () {
  9803. var elementFns = [];
  9804. var allConstant = true;
  9805. if (this.peekToken().text !== ']') {
  9806. do {
  9807. if (this.peek(']')) {
  9808. // Support trailing commas per ES5.1.
  9809. break;
  9810. }
  9811. var elementFn = this.expression();
  9812. elementFns.push(elementFn);
  9813. if (!elementFn.constant) {
  9814. allConstant = false;
  9815. }
  9816. } while (this.expect(','));
  9817. }
  9818. this.consume(']');
  9819. return extend(function(self, locals) {
  9820. var array = [];
  9821. for (var i = 0; i < elementFns.length; i++) {
  9822. array.push(elementFns[i](self, locals));
  9823. }
  9824. return array;
  9825. }, {
  9826. literal: true,
  9827. constant: allConstant
  9828. });
  9829. },
  9830. object: function () {
  9831. var keyValues = [];
  9832. var allConstant = true;
  9833. if (this.peekToken().text !== '}') {
  9834. do {
  9835. if (this.peek('}')) {
  9836. // Support trailing commas per ES5.1.
  9837. break;
  9838. }
  9839. var token = this.expect(),
  9840. key = token.string || token.text;
  9841. this.consume(':');
  9842. var value = this.expression();
  9843. keyValues.push({key: key, value: value});
  9844. if (!value.constant) {
  9845. allConstant = false;
  9846. }
  9847. } while (this.expect(','));
  9848. }
  9849. this.consume('}');
  9850. return extend(function(self, locals) {
  9851. var object = {};
  9852. for (var i = 0; i < keyValues.length; i++) {
  9853. var keyValue = keyValues[i];
  9854. object[keyValue.key] = keyValue.value(self, locals);
  9855. }
  9856. return object;
  9857. }, {
  9858. literal: true,
  9859. constant: allConstant
  9860. });
  9861. }
  9862. };
  9863. //////////////////////////////////////////////////
  9864. // Parser helper functions
  9865. //////////////////////////////////////////////////
  9866. function setter(obj, path, setValue, fullExp, options) {
  9867. ensureSafeObject(obj, fullExp);
  9868. //needed?
  9869. options = options || {};
  9870. var element = path.split('.'), key;
  9871. for (var i = 0; element.length > 1; i++) {
  9872. key = ensureSafeMemberName(element.shift(), fullExp);
  9873. var propertyObj = ensureSafeObject(obj[key], fullExp);
  9874. if (!propertyObj) {
  9875. propertyObj = {};
  9876. obj[key] = propertyObj;
  9877. }
  9878. obj = propertyObj;
  9879. if (obj.then && options.unwrapPromises) {
  9880. promiseWarning(fullExp);
  9881. if (!("$$v" in obj)) {
  9882. (function(promise) {
  9883. promise.then(function(val) { promise.$$v = val; }); }
  9884. )(obj);
  9885. }
  9886. if (obj.$$v === undefined) {
  9887. obj.$$v = {};
  9888. }
  9889. obj = obj.$$v;
  9890. }
  9891. }
  9892. key = ensureSafeMemberName(element.shift(), fullExp);
  9893. ensureSafeObject(obj[key], fullExp);
  9894. obj[key] = setValue;
  9895. return setValue;
  9896. }
  9897. var getterFnCacheDefault = {};
  9898. var getterFnCacheExpensive = {};
  9899. function isPossiblyDangerousMemberName(name) {
  9900. return name == 'constructor';
  9901. }
  9902. /**
  9903. * Implementation of the "Black Hole" variant from:
  9904. * - http://jsperf.com/angularjs-parse-getter/4
  9905. * - http://jsperf.com/path-evaluation-simplified/7
  9906. */
  9907. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9908. ensureSafeMemberName(key0, fullExp);
  9909. ensureSafeMemberName(key1, fullExp);
  9910. ensureSafeMemberName(key2, fullExp);
  9911. ensureSafeMemberName(key3, fullExp);
  9912. ensureSafeMemberName(key4, fullExp);
  9913. var eso = function(o) {
  9914. return ensureSafeObject(o, fullExp);
  9915. };
  9916. var expensiveChecks = options.expensiveChecks;
  9917. var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
  9918. var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
  9919. var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
  9920. var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
  9921. var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
  9922. return !options.unwrapPromises
  9923. ? function cspSafeGetter(scope, locals) {
  9924. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9925. if (pathVal == null) return pathVal;
  9926. pathVal = eso0(pathVal[key0]);
  9927. if (!key1) return pathVal;
  9928. if (pathVal == null) return undefined;
  9929. pathVal = eso1(pathVal[key1]);
  9930. if (!key2) return pathVal;
  9931. if (pathVal == null) return undefined;
  9932. pathVal = eso2(pathVal[key2]);
  9933. if (!key3) return pathVal;
  9934. if (pathVal == null) return undefined;
  9935. pathVal = eso3(pathVal[key3]);
  9936. if (!key4) return pathVal;
  9937. if (pathVal == null) return undefined;
  9938. pathVal = eso4(pathVal[key4]);
  9939. return pathVal;
  9940. }
  9941. : function cspSafePromiseEnabledGetter(scope, locals) {
  9942. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9943. promise;
  9944. if (pathVal == null) return pathVal;
  9945. pathVal = eso0(pathVal[key0]);
  9946. if (pathVal && pathVal.then) {
  9947. promiseWarning(fullExp);
  9948. if (!("$$v" in pathVal)) {
  9949. promise = pathVal;
  9950. promise.$$v = undefined;
  9951. promise.then(function(val) { promise.$$v = eso0(val); });
  9952. }
  9953. pathVal = eso0(pathVal.$$v);
  9954. }
  9955. if (!key1) return pathVal;
  9956. if (pathVal == null) return undefined;
  9957. pathVal = eso1(pathVal[key1]);
  9958. if (pathVal && pathVal.then) {
  9959. promiseWarning(fullExp);
  9960. if (!("$$v" in pathVal)) {
  9961. promise = pathVal;
  9962. promise.$$v = undefined;
  9963. promise.then(function(val) { promise.$$v = eso1(val); });
  9964. }
  9965. pathVal = eso1(pathVal.$$v);
  9966. }
  9967. if (!key2) return pathVal;
  9968. if (pathVal == null) return undefined;
  9969. pathVal = eso2(pathVal[key2]);
  9970. if (pathVal && pathVal.then) {
  9971. promiseWarning(fullExp);
  9972. if (!("$$v" in pathVal)) {
  9973. promise = pathVal;
  9974. promise.$$v = undefined;
  9975. promise.then(function(val) { promise.$$v = eso2(val); });
  9976. }
  9977. pathVal = eso2(pathVal.$$v);
  9978. }
  9979. if (!key3) return pathVal;
  9980. if (pathVal == null) return undefined;
  9981. pathVal = eso3(pathVal[key3]);
  9982. if (pathVal && pathVal.then) {
  9983. promiseWarning(fullExp);
  9984. if (!("$$v" in pathVal)) {
  9985. promise = pathVal;
  9986. promise.$$v = undefined;
  9987. promise.then(function(val) { promise.$$v = eso3(val); });
  9988. }
  9989. pathVal = eso3(pathVal.$$v);
  9990. }
  9991. if (!key4) return pathVal;
  9992. if (pathVal == null) return undefined;
  9993. pathVal = eso4(pathVal[key4]);
  9994. if (pathVal && pathVal.then) {
  9995. promiseWarning(fullExp);
  9996. if (!("$$v" in pathVal)) {
  9997. promise = pathVal;
  9998. promise.$$v = undefined;
  9999. promise.then(function(val) { promise.$$v = eso4(val); });
  10000. }
  10001. pathVal = eso4(pathVal.$$v);
  10002. }
  10003. return pathVal;
  10004. };
  10005. }
  10006. function getterFnWithExtraArgs(fn, fullExpression) {
  10007. return function(s, l) {
  10008. return fn(s, l, promiseWarning, ensureSafeObject, fullExpression);
  10009. };
  10010. }
  10011. function getterFn(path, options, fullExp) {
  10012. var expensiveChecks = options.expensiveChecks;
  10013. var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
  10014. // Check whether the cache has this getter already.
  10015. // We can use hasOwnProperty directly on the cache because we ensure,
  10016. // see below, that the cache never stores a path called 'hasOwnProperty'
  10017. if (getterFnCache.hasOwnProperty(path)) {
  10018. return getterFnCache[path];
  10019. }
  10020. var pathKeys = path.split('.'),
  10021. pathKeysLength = pathKeys.length,
  10022. fn;
  10023. // http://jsperf.com/angularjs-parse-getter/6
  10024. if (options.csp) {
  10025. if (pathKeysLength < 6) {
  10026. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  10027. options);
  10028. } else {
  10029. fn = function(scope, locals) {
  10030. var i = 0, val;
  10031. do {
  10032. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  10033. pathKeys[i++], fullExp, options)(scope, locals);
  10034. locals = undefined; // clear after first iteration
  10035. scope = val;
  10036. } while (i < pathKeysLength);
  10037. return val;
  10038. };
  10039. }
  10040. } else {
  10041. var code = 'var p;\n';
  10042. if (expensiveChecks) {
  10043. code += 's = eso(s, fe);\nl = eso(l, fe);\n';
  10044. }
  10045. var needsEnsureSafeObject = expensiveChecks;
  10046. forEach(pathKeys, function(key, index) {
  10047. ensureSafeMemberName(key, fullExp);
  10048. var lookupJs = (index
  10049. // we simply dereference 's' on any .dot notation
  10050. ? 's'
  10051. // but if we are first then we check locals first, and if so read it first
  10052. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '["' + key + '"]';
  10053. var wrapWithEso = expensiveChecks || isPossiblyDangerousMemberName(key);
  10054. if (wrapWithEso) {
  10055. lookupJs = 'eso(' + lookupJs + ', fe)';
  10056. needsEnsureSafeObject = true;
  10057. }
  10058. code += 'if(s == null) return undefined;\n' +
  10059. 's=' + lookupJs + ';\n';
  10060. if (options.unwrapPromises) {
  10061. code += 'if (s && s.then) {\n' +
  10062. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  10063. ' if (!("$$v" in s)) {\n' +
  10064. ' p=s;\n' +
  10065. ' p.$$v = undefined;\n' +
  10066. ' p.then(function(v) {p.$$v=' + (wrapWithEso ? 'eso(v)' : 'v') + ';});\n' +
  10067. '}\n' +
  10068. ' s=' + (wrapWithEso ? 'eso(s.$$v)' : 's.$$v') + '\n' +
  10069. '}\n';
  10070. }
  10071. });
  10072. code += 'return s;';
  10073. /* jshint -W054 */
  10074. // s=scope, l=locals, pw=promiseWarning, eso=ensureSafeObject, fe=fullExpression
  10075. var evaledFnGetter = new Function('s', 'l', 'pw', 'eso', 'fe', code);
  10076. /* jshint +W054 */
  10077. evaledFnGetter.toString = valueFn(code);
  10078. if (needsEnsureSafeObject || options.unwrapPromises) {
  10079. evaledFnGetter = getterFnWithExtraArgs(evaledFnGetter, fullExp);
  10080. }
  10081. fn = evaledFnGetter;
  10082. }
  10083. // Only cache the value if it's not going to mess up the cache object
  10084. // This is more performant that using Object.prototype.hasOwnProperty.call
  10085. if (path !== 'hasOwnProperty') {
  10086. getterFnCache[path] = fn;
  10087. }
  10088. return fn;
  10089. }
  10090. ///////////////////////////////////
  10091. /**
  10092. * @ngdoc service
  10093. * @name $parse
  10094. * @kind function
  10095. *
  10096. * @description
  10097. *
  10098. * Converts Angular {@link guide/expression expression} into a function.
  10099. *
  10100. * ```js
  10101. * var getter = $parse('user.name');
  10102. * var setter = getter.assign;
  10103. * var context = {user:{name:'angular'}};
  10104. * var locals = {user:{name:'local'}};
  10105. *
  10106. * expect(getter(context)).toEqual('angular');
  10107. * setter(context, 'newValue');
  10108. * expect(context.user.name).toEqual('newValue');
  10109. * expect(getter(context, locals)).toEqual('local');
  10110. * ```
  10111. *
  10112. *
  10113. * @param {string} expression String expression to compile.
  10114. * @returns {function(context, locals)} a function which represents the compiled expression:
  10115. *
  10116. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  10117. * are evaluated against (typically a scope object).
  10118. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  10119. * `context`.
  10120. *
  10121. * The returned function also has the following properties:
  10122. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  10123. * literal.
  10124. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  10125. * constant literals.
  10126. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  10127. * set to a function to change its value on the given context.
  10128. *
  10129. */
  10130. /**
  10131. * @ngdoc provider
  10132. * @name $parseProvider
  10133. * @kind function
  10134. *
  10135. * @description
  10136. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  10137. * service.
  10138. */
  10139. function $ParseProvider() {
  10140. var cacheDefault = {};
  10141. var cacheExpensive = {};
  10142. var $parseOptions = {
  10143. csp: false,
  10144. unwrapPromises: false,
  10145. logPromiseWarnings: true,
  10146. expensiveChecks: false
  10147. };
  10148. /**
  10149. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10150. *
  10151. * @ngdoc method
  10152. * @name $parseProvider#unwrapPromises
  10153. * @description
  10154. *
  10155. * **This feature is deprecated, see deprecation notes below for more info**
  10156. *
  10157. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  10158. * found at any part of the expression. In other words, if set to true, the expression will always
  10159. * result in a non-promise value.
  10160. *
  10161. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  10162. * the fulfillment value is used in place of the promise while evaluating the expression.
  10163. *
  10164. * **Deprecation notice**
  10165. *
  10166. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  10167. * dichotomy between data access in templates (accessed as raw values) and controller code
  10168. * (accessed as promises).
  10169. *
  10170. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  10171. * the model access there.
  10172. *
  10173. * Other downsides of automatic promise unwrapping:
  10174. *
  10175. * - when building components it's often desirable to receive the raw promises
  10176. * - adds complexity and slows down expression evaluation
  10177. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  10178. * generated
  10179. * - makes IDE auto-completion and tool support hard
  10180. *
  10181. * **Warning Logs**
  10182. *
  10183. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  10184. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  10185. * `$parseProvider.logPromiseWarnings(false)` api.
  10186. *
  10187. *
  10188. * @param {boolean=} value New value.
  10189. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10190. * setter.
  10191. */
  10192. this.unwrapPromises = function(value) {
  10193. if (isDefined(value)) {
  10194. $parseOptions.unwrapPromises = !!value;
  10195. return this;
  10196. } else {
  10197. return $parseOptions.unwrapPromises;
  10198. }
  10199. };
  10200. /**
  10201. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10202. *
  10203. * @ngdoc method
  10204. * @name $parseProvider#logPromiseWarnings
  10205. * @description
  10206. *
  10207. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  10208. *
  10209. * The default is set to `true`.
  10210. *
  10211. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  10212. *
  10213. * @param {boolean=} value New value.
  10214. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10215. * setter.
  10216. */
  10217. this.logPromiseWarnings = function(value) {
  10218. if (isDefined(value)) {
  10219. $parseOptions.logPromiseWarnings = value;
  10220. return this;
  10221. } else {
  10222. return $parseOptions.logPromiseWarnings;
  10223. }
  10224. };
  10225. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  10226. $parseOptions.csp = $sniffer.csp;
  10227. var $parseOptionsExpensive = {
  10228. csp: $parseOptions.csp,
  10229. unwrapPromises: $parseOptions.unwrapPromises,
  10230. logPromiseWarnings: $parseOptions.logPromiseWarnings,
  10231. expensiveChecks: true
  10232. };
  10233. promiseWarning = function promiseWarningFn(fullExp) {
  10234. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  10235. promiseWarningCache[fullExp] = true;
  10236. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  10237. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  10238. };
  10239. return function(exp, expensiveChecks) {
  10240. var parsedExpression;
  10241. switch (typeof exp) {
  10242. case 'string':
  10243. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  10244. if (cache.hasOwnProperty(exp)) {
  10245. return cache[exp];
  10246. }
  10247. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  10248. var lexer = new Lexer(parseOptions);
  10249. var parser = new Parser(lexer, $filter, parseOptions);
  10250. parsedExpression = parser.parse(exp);
  10251. if (exp !== 'hasOwnProperty') {
  10252. // Only cache the value if it's not going to mess up the cache object
  10253. // This is more performant that using Object.prototype.hasOwnProperty.call
  10254. cache[exp] = parsedExpression;
  10255. }
  10256. return parsedExpression;
  10257. case 'function':
  10258. return exp;
  10259. default:
  10260. return noop;
  10261. }
  10262. };
  10263. }];
  10264. }
  10265. /**
  10266. * @ngdoc service
  10267. * @name $q
  10268. * @requires $rootScope
  10269. *
  10270. * @description
  10271. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  10272. * when they are done processing.
  10273. *
  10274. * This is an implementation of promises/deferred objects inspired by
  10275. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  10276. *
  10277. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  10278. * interface for interacting with an object that represents the result of an action that is
  10279. * performed asynchronously, and may or may not be finished at any given point in time.
  10280. *
  10281. * From the perspective of dealing with error handling, deferred and promise APIs are to
  10282. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  10283. *
  10284. * ```js
  10285. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  10286. * // are available in the current lexical scope (they could have been injected or passed in).
  10287. *
  10288. * function asyncGreet(name) {
  10289. * var deferred = $q.defer();
  10290. *
  10291. * setTimeout(function() {
  10292. * deferred.notify('About to greet ' + name + '.');
  10293. *
  10294. * if (okToGreet(name)) {
  10295. * deferred.resolve('Hello, ' + name + '!');
  10296. * } else {
  10297. * deferred.reject('Greeting ' + name + ' is not allowed.');
  10298. * }
  10299. * }, 1000);
  10300. *
  10301. * return deferred.promise;
  10302. * }
  10303. *
  10304. * var promise = asyncGreet('Robin Hood');
  10305. * promise.then(function(greeting) {
  10306. * alert('Success: ' + greeting);
  10307. * }, function(reason) {
  10308. * alert('Failed: ' + reason);
  10309. * }, function(update) {
  10310. * alert('Got notification: ' + update);
  10311. * });
  10312. * ```
  10313. *
  10314. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10315. * comes in the way of guarantees that promise and deferred APIs make, see
  10316. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10317. *
  10318. * Additionally the promise api allows for composition that is very hard to do with the
  10319. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10320. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10321. * section on serial or parallel joining of promises.
  10322. *
  10323. *
  10324. * # The Deferred API
  10325. *
  10326. * A new instance of deferred is constructed by calling `$q.defer()`.
  10327. *
  10328. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10329. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10330. * of the task.
  10331. *
  10332. * **Methods**
  10333. *
  10334. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10335. * constructed via `$q.reject`, the promise will be rejected instead.
  10336. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10337. * resolving it with a rejection constructed via `$q.reject`.
  10338. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10339. * multiple times before the promise is either resolved or rejected.
  10340. *
  10341. * **Properties**
  10342. *
  10343. * - promise – `{Promise}` – promise object associated with this deferred.
  10344. *
  10345. *
  10346. * # The Promise API
  10347. *
  10348. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10349. * calling `deferred.promise`.
  10350. *
  10351. * The purpose of the promise object is to allow for interested parties to get access to the result
  10352. * of the deferred task when it completes.
  10353. *
  10354. * **Methods**
  10355. *
  10356. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10357. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10358. * as soon as the result is available. The callbacks are called with a single argument: the result
  10359. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10360. * provide a progress indication, before the promise is resolved or rejected.
  10361. *
  10362. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10363. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10364. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10365. * method.
  10366. *
  10367. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10368. *
  10369. * Because `catch` is a reserved word in JavaScript and reserved keywords are not supported as
  10370. * property names by ES3, you'll need to invoke the method like `promise['catch'](callback)` or
  10371. * `promise.then(null, errorCallback)` to make your code IE8 and Android 2.x compatible.
  10372. *
  10373. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10374. * but to do so without modifying the final value. This is useful to release resources or do some
  10375. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10376. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10377. * more information.
  10378. *
  10379. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10380. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10381. * make your code IE8 and Android 2.x compatible.
  10382. *
  10383. * # Chaining promises
  10384. *
  10385. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10386. * possible to create a chain of promises:
  10387. *
  10388. * ```js
  10389. * promiseB = promiseA.then(function(result) {
  10390. * return result + 1;
  10391. * });
  10392. *
  10393. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10394. * // will be the result of promiseA incremented by 1
  10395. * ```
  10396. *
  10397. * It is possible to create chains of any length and since a promise can be resolved with another
  10398. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10399. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10400. * $http's response interceptors.
  10401. *
  10402. *
  10403. * # Differences between Kris Kowal's Q and $q
  10404. *
  10405. * There are two main differences:
  10406. *
  10407. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10408. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10409. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10410. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10411. * all the important functionality needed for common async tasks.
  10412. *
  10413. * # Testing
  10414. *
  10415. * ```js
  10416. * it('should simulate promise', inject(function($q, $rootScope) {
  10417. * var deferred = $q.defer();
  10418. * var promise = deferred.promise;
  10419. * var resolvedValue;
  10420. *
  10421. * promise.then(function(value) { resolvedValue = value; });
  10422. * expect(resolvedValue).toBeUndefined();
  10423. *
  10424. * // Simulate resolving of promise
  10425. * deferred.resolve(123);
  10426. * // Note that the 'then' function does not get called synchronously.
  10427. * // This is because we want the promise API to always be async, whether or not
  10428. * // it got called synchronously or asynchronously.
  10429. * expect(resolvedValue).toBeUndefined();
  10430. *
  10431. * // Propagate promise resolution to 'then' functions using $apply().
  10432. * $rootScope.$apply();
  10433. * expect(resolvedValue).toEqual(123);
  10434. * }));
  10435. * ```
  10436. */
  10437. function $QProvider() {
  10438. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10439. return qFactory(function(callback) {
  10440. $rootScope.$evalAsync(callback);
  10441. }, $exceptionHandler);
  10442. }];
  10443. }
  10444. /**
  10445. * Constructs a promise manager.
  10446. *
  10447. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10448. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10449. * debugging purposes.
  10450. * @returns {object} Promise manager.
  10451. */
  10452. function qFactory(nextTick, exceptionHandler) {
  10453. /**
  10454. * @ngdoc method
  10455. * @name $q#defer
  10456. * @kind function
  10457. *
  10458. * @description
  10459. * Creates a `Deferred` object which represents a task which will finish in the future.
  10460. *
  10461. * @returns {Deferred} Returns a new instance of deferred.
  10462. */
  10463. var defer = function() {
  10464. var pending = [],
  10465. value, deferred;
  10466. deferred = {
  10467. resolve: function(val) {
  10468. if (pending) {
  10469. var callbacks = pending;
  10470. pending = undefined;
  10471. value = ref(val);
  10472. if (callbacks.length) {
  10473. nextTick(function() {
  10474. var callback;
  10475. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10476. callback = callbacks[i];
  10477. value.then(callback[0], callback[1], callback[2]);
  10478. }
  10479. });
  10480. }
  10481. }
  10482. },
  10483. reject: function(reason) {
  10484. deferred.resolve(createInternalRejectedPromise(reason));
  10485. },
  10486. notify: function(progress) {
  10487. if (pending) {
  10488. var callbacks = pending;
  10489. if (pending.length) {
  10490. nextTick(function() {
  10491. var callback;
  10492. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10493. callback = callbacks[i];
  10494. callback[2](progress);
  10495. }
  10496. });
  10497. }
  10498. }
  10499. },
  10500. promise: {
  10501. then: function(callback, errback, progressback) {
  10502. var result = defer();
  10503. var wrappedCallback = function(value) {
  10504. try {
  10505. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10506. } catch(e) {
  10507. result.reject(e);
  10508. exceptionHandler(e);
  10509. }
  10510. };
  10511. var wrappedErrback = function(reason) {
  10512. try {
  10513. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10514. } catch(e) {
  10515. result.reject(e);
  10516. exceptionHandler(e);
  10517. }
  10518. };
  10519. var wrappedProgressback = function(progress) {
  10520. try {
  10521. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10522. } catch(e) {
  10523. exceptionHandler(e);
  10524. }
  10525. };
  10526. if (pending) {
  10527. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10528. } else {
  10529. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10530. }
  10531. return result.promise;
  10532. },
  10533. "catch": function(callback) {
  10534. return this.then(null, callback);
  10535. },
  10536. "finally": function(callback) {
  10537. function makePromise(value, resolved) {
  10538. var result = defer();
  10539. if (resolved) {
  10540. result.resolve(value);
  10541. } else {
  10542. result.reject(value);
  10543. }
  10544. return result.promise;
  10545. }
  10546. function handleCallback(value, isResolved) {
  10547. var callbackOutput = null;
  10548. try {
  10549. callbackOutput = (callback ||defaultCallback)();
  10550. } catch(e) {
  10551. return makePromise(e, false);
  10552. }
  10553. if (isPromiseLike(callbackOutput)) {
  10554. return callbackOutput.then(function() {
  10555. return makePromise(value, isResolved);
  10556. }, function(error) {
  10557. return makePromise(error, false);
  10558. });
  10559. } else {
  10560. return makePromise(value, isResolved);
  10561. }
  10562. }
  10563. return this.then(function(value) {
  10564. return handleCallback(value, true);
  10565. }, function(error) {
  10566. return handleCallback(error, false);
  10567. });
  10568. }
  10569. }
  10570. };
  10571. return deferred;
  10572. };
  10573. var ref = function(value) {
  10574. if (isPromiseLike(value)) return value;
  10575. return {
  10576. then: function(callback) {
  10577. var result = defer();
  10578. nextTick(function() {
  10579. result.resolve(callback(value));
  10580. });
  10581. return result.promise;
  10582. }
  10583. };
  10584. };
  10585. /**
  10586. * @ngdoc method
  10587. * @name $q#reject
  10588. * @kind function
  10589. *
  10590. * @description
  10591. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10592. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10593. * a promise chain, you don't need to worry about it.
  10594. *
  10595. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10596. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10597. * a promise error callback and you want to forward the error to the promise derived from the
  10598. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10599. * `reject`.
  10600. *
  10601. * ```js
  10602. * promiseB = promiseA.then(function(result) {
  10603. * // success: do something and resolve promiseB
  10604. * // with the old or a new result
  10605. * return result;
  10606. * }, function(reason) {
  10607. * // error: handle the error if possible and
  10608. * // resolve promiseB with newPromiseOrValue,
  10609. * // otherwise forward the rejection to promiseB
  10610. * if (canHandle(reason)) {
  10611. * // handle the error and recover
  10612. * return newPromiseOrValue;
  10613. * }
  10614. * return $q.reject(reason);
  10615. * });
  10616. * ```
  10617. *
  10618. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10619. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10620. */
  10621. var reject = function(reason) {
  10622. var result = defer();
  10623. result.reject(reason);
  10624. return result.promise;
  10625. };
  10626. var createInternalRejectedPromise = function(reason) {
  10627. return {
  10628. then: function(callback, errback) {
  10629. var result = defer();
  10630. nextTick(function() {
  10631. try {
  10632. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10633. } catch(e) {
  10634. result.reject(e);
  10635. exceptionHandler(e);
  10636. }
  10637. });
  10638. return result.promise;
  10639. }
  10640. };
  10641. };
  10642. /**
  10643. * @ngdoc method
  10644. * @name $q#when
  10645. * @kind function
  10646. *
  10647. * @description
  10648. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10649. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10650. * the promise comes from a source that can't be trusted.
  10651. *
  10652. * @param {*} value Value or a promise
  10653. * @returns {Promise} Returns a promise of the passed value or promise
  10654. */
  10655. var when = function(value, callback, errback, progressback) {
  10656. var result = defer(),
  10657. done;
  10658. var wrappedCallback = function(value) {
  10659. try {
  10660. return (isFunction(callback) ? callback : defaultCallback)(value);
  10661. } catch (e) {
  10662. exceptionHandler(e);
  10663. return reject(e);
  10664. }
  10665. };
  10666. var wrappedErrback = function(reason) {
  10667. try {
  10668. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10669. } catch (e) {
  10670. exceptionHandler(e);
  10671. return reject(e);
  10672. }
  10673. };
  10674. var wrappedProgressback = function(progress) {
  10675. try {
  10676. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10677. } catch (e) {
  10678. exceptionHandler(e);
  10679. }
  10680. };
  10681. nextTick(function() {
  10682. ref(value).then(function(value) {
  10683. if (done) return;
  10684. done = true;
  10685. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10686. }, function(reason) {
  10687. if (done) return;
  10688. done = true;
  10689. result.resolve(wrappedErrback(reason));
  10690. }, function(progress) {
  10691. if (done) return;
  10692. result.notify(wrappedProgressback(progress));
  10693. });
  10694. });
  10695. return result.promise;
  10696. };
  10697. function defaultCallback(value) {
  10698. return value;
  10699. }
  10700. function defaultErrback(reason) {
  10701. return reject(reason);
  10702. }
  10703. /**
  10704. * @ngdoc method
  10705. * @name $q#all
  10706. * @kind function
  10707. *
  10708. * @description
  10709. * Combines multiple promises into a single promise that is resolved when all of the input
  10710. * promises are resolved.
  10711. *
  10712. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10713. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10714. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10715. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10716. * with the same rejection value.
  10717. */
  10718. function all(promises) {
  10719. var deferred = defer(),
  10720. counter = 0,
  10721. results = isArray(promises) ? [] : {};
  10722. forEach(promises, function(promise, key) {
  10723. counter++;
  10724. ref(promise).then(function(value) {
  10725. if (results.hasOwnProperty(key)) return;
  10726. results[key] = value;
  10727. if (!(--counter)) deferred.resolve(results);
  10728. }, function(reason) {
  10729. if (results.hasOwnProperty(key)) return;
  10730. deferred.reject(reason);
  10731. });
  10732. });
  10733. if (counter === 0) {
  10734. deferred.resolve(results);
  10735. }
  10736. return deferred.promise;
  10737. }
  10738. return {
  10739. defer: defer,
  10740. reject: reject,
  10741. when: when,
  10742. all: all
  10743. };
  10744. }
  10745. function $$RAFProvider(){ //rAF
  10746. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10747. var requestAnimationFrame = $window.requestAnimationFrame ||
  10748. $window.webkitRequestAnimationFrame ||
  10749. $window.mozRequestAnimationFrame;
  10750. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10751. $window.webkitCancelAnimationFrame ||
  10752. $window.mozCancelAnimationFrame ||
  10753. $window.webkitCancelRequestAnimationFrame;
  10754. var rafSupported = !!requestAnimationFrame;
  10755. var raf = rafSupported
  10756. ? function(fn) {
  10757. var id = requestAnimationFrame(fn);
  10758. return function() {
  10759. cancelAnimationFrame(id);
  10760. };
  10761. }
  10762. : function(fn) {
  10763. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10764. return function() {
  10765. $timeout.cancel(timer);
  10766. };
  10767. };
  10768. raf.supported = rafSupported;
  10769. return raf;
  10770. }];
  10771. }
  10772. /**
  10773. * DESIGN NOTES
  10774. *
  10775. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10776. *
  10777. * The typical use of scope is to watch the expressions, which most of the time return the same
  10778. * value as last time so we optimize the operation.
  10779. *
  10780. * Closures construction is expensive in terms of speed as well as memory:
  10781. * - No closures, instead use prototypical inheritance for API
  10782. * - Internal state needs to be stored on scope directly, which means that private state is
  10783. * exposed as $$____ properties
  10784. *
  10785. * Loop operations are optimized by using while(count--) { ... }
  10786. * - this means that in order to keep the same order of execution as addition we have to add
  10787. * items to the array at the beginning (unshift) instead of at the end (push)
  10788. *
  10789. * Child scopes are created and removed often
  10790. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10791. *
  10792. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10793. * implemented in the same way as watch. Watch requires return of initialization function which
  10794. * are expensive to construct.
  10795. */
  10796. /**
  10797. * @ngdoc provider
  10798. * @name $rootScopeProvider
  10799. * @description
  10800. *
  10801. * Provider for the $rootScope service.
  10802. */
  10803. /**
  10804. * @ngdoc method
  10805. * @name $rootScopeProvider#digestTtl
  10806. * @description
  10807. *
  10808. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10809. * assuming that the model is unstable.
  10810. *
  10811. * The current default is 10 iterations.
  10812. *
  10813. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10814. * several digest iterations. However if an application needs more than the default 10 digest
  10815. * iterations for its model to stabilize then you should investigate what is causing the model to
  10816. * continuously change during the digest.
  10817. *
  10818. * Increasing the TTL could have performance implications, so you should not change it without
  10819. * proper justification.
  10820. *
  10821. * @param {number} limit The number of digest iterations.
  10822. */
  10823. /**
  10824. * @ngdoc service
  10825. * @name $rootScope
  10826. * @description
  10827. *
  10828. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10829. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10830. * between the model and the view, via a mechanism for watching the model for changes.
  10831. * They also provide an event emission/broadcast and subscription facility. See the
  10832. * {@link guide/scope developer guide on scopes}.
  10833. */
  10834. function $RootScopeProvider(){
  10835. var TTL = 10;
  10836. var $rootScopeMinErr = minErr('$rootScope');
  10837. var lastDirtyWatch = null;
  10838. this.digestTtl = function(value) {
  10839. if (arguments.length) {
  10840. TTL = value;
  10841. }
  10842. return TTL;
  10843. };
  10844. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10845. function( $injector, $exceptionHandler, $parse, $browser) {
  10846. /**
  10847. * @ngdoc type
  10848. * @name $rootScope.Scope
  10849. *
  10850. * @description
  10851. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10852. * {@link auto.$injector $injector}. Child scopes are created using the
  10853. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10854. * compiled HTML template is executed.)
  10855. *
  10856. * Here is a simple scope snippet to show how you can interact with the scope.
  10857. * ```html
  10858. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10859. * ```
  10860. *
  10861. * # Inheritance
  10862. * A scope can inherit from a parent scope, as in this example:
  10863. * ```js
  10864. var parent = $rootScope;
  10865. var child = parent.$new();
  10866. parent.salutation = "Hello";
  10867. child.name = "World";
  10868. expect(child.salutation).toEqual('Hello');
  10869. child.salutation = "Welcome";
  10870. expect(child.salutation).toEqual('Welcome');
  10871. expect(parent.salutation).toEqual('Hello');
  10872. * ```
  10873. *
  10874. *
  10875. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10876. * provided for the current scope. Defaults to {@link ng}.
  10877. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10878. * append/override services provided by `providers`. This is handy
  10879. * when unit-testing and having the need to override a default
  10880. * service.
  10881. * @returns {Object} Newly created scope.
  10882. *
  10883. */
  10884. function Scope() {
  10885. this.$id = nextUid();
  10886. this.$$phase = this.$parent = this.$$watchers =
  10887. this.$$nextSibling = this.$$prevSibling =
  10888. this.$$childHead = this.$$childTail = null;
  10889. this['this'] = this.$root = this;
  10890. this.$$destroyed = false;
  10891. this.$$asyncQueue = [];
  10892. this.$$postDigestQueue = [];
  10893. this.$$listeners = {};
  10894. this.$$listenerCount = {};
  10895. this.$$isolateBindings = {};
  10896. }
  10897. /**
  10898. * @ngdoc property
  10899. * @name $rootScope.Scope#$id
  10900. *
  10901. * @description
  10902. * Unique scope ID (monotonically increasing) useful for debugging.
  10903. */
  10904. /**
  10905. * @ngdoc property
  10906. * @name $rootScope.Scope#$parent
  10907. *
  10908. * @description
  10909. * Reference to the parent scope.
  10910. */
  10911. /**
  10912. * @ngdoc property
  10913. * @name $rootScope.Scope#$root
  10914. *
  10915. * @description
  10916. * Reference to the root scope.
  10917. */
  10918. Scope.prototype = {
  10919. constructor: Scope,
  10920. /**
  10921. * @ngdoc method
  10922. * @name $rootScope.Scope#$new
  10923. * @kind function
  10924. *
  10925. * @description
  10926. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10927. *
  10928. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  10929. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10930. *
  10931. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10932. * desired for the scope and its child scopes to be permanently detached from the parent and
  10933. * thus stop participating in model change detection and listener notification by invoking.
  10934. *
  10935. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10936. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10937. * When creating widgets, it is useful for the widget to not accidentally read parent
  10938. * state.
  10939. *
  10940. * @returns {Object} The newly created child scope.
  10941. *
  10942. */
  10943. $new: function(isolate) {
  10944. var ChildScope,
  10945. child;
  10946. if (isolate) {
  10947. child = new Scope();
  10948. child.$root = this.$root;
  10949. // ensure that there is just one async queue per $rootScope and its children
  10950. child.$$asyncQueue = this.$$asyncQueue;
  10951. child.$$postDigestQueue = this.$$postDigestQueue;
  10952. } else {
  10953. // Only create a child scope class if somebody asks for one,
  10954. // but cache it to allow the VM to optimize lookups.
  10955. if (!this.$$childScopeClass) {
  10956. this.$$childScopeClass = function() {
  10957. this.$$watchers = this.$$nextSibling =
  10958. this.$$childHead = this.$$childTail = null;
  10959. this.$$listeners = {};
  10960. this.$$listenerCount = {};
  10961. this.$id = nextUid();
  10962. this.$$childScopeClass = null;
  10963. };
  10964. this.$$childScopeClass.prototype = this;
  10965. }
  10966. child = new this.$$childScopeClass();
  10967. }
  10968. child['this'] = child;
  10969. child.$parent = this;
  10970. child.$$prevSibling = this.$$childTail;
  10971. if (this.$$childHead) {
  10972. this.$$childTail.$$nextSibling = child;
  10973. this.$$childTail = child;
  10974. } else {
  10975. this.$$childHead = this.$$childTail = child;
  10976. }
  10977. return child;
  10978. },
  10979. /**
  10980. * @ngdoc method
  10981. * @name $rootScope.Scope#$watch
  10982. * @kind function
  10983. *
  10984. * @description
  10985. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10986. *
  10987. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  10988. * $digest()} and should return the value that will be watched. (Since
  10989. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  10990. * `watchExpression` can execute multiple times per
  10991. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  10992. * - The `listener` is called only when the value from the current `watchExpression` and the
  10993. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10994. * see below). Inequality is determined according to reference inequality,
  10995. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  10996. * via the `!==` Javascript operator, unless `objectEquality == true`
  10997. * (see next point)
  10998. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  10999. * according to the {@link angular.equals} function. To save the value of the object for
  11000. * later comparison, the {@link angular.copy} function is used. This therefore means that
  11001. * watching complex objects will have adverse memory and performance implications.
  11002. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  11003. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  11004. * iteration limit is 10 to prevent an infinite loop deadlock.
  11005. *
  11006. *
  11007. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  11008. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  11009. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  11010. * change is detected, be prepared for multiple calls to your listener.)
  11011. *
  11012. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  11013. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  11014. * watcher. In rare cases, this is undesirable because the listener is called when the result
  11015. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  11016. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  11017. * listener was called due to initialization.
  11018. *
  11019. * The example below contains an illustration of using a function as your $watch listener
  11020. *
  11021. *
  11022. * # Example
  11023. * ```js
  11024. // let's assume that scope was dependency injected as the $rootScope
  11025. var scope = $rootScope;
  11026. scope.name = 'misko';
  11027. scope.counter = 0;
  11028. expect(scope.counter).toEqual(0);
  11029. scope.$watch('name', function(newValue, oldValue) {
  11030. scope.counter = scope.counter + 1;
  11031. });
  11032. expect(scope.counter).toEqual(0);
  11033. scope.$digest();
  11034. // the listener is always called during the first $digest loop after it was registered
  11035. expect(scope.counter).toEqual(1);
  11036. scope.$digest();
  11037. // but now it will not be called unless the value changes
  11038. expect(scope.counter).toEqual(1);
  11039. scope.name = 'adam';
  11040. scope.$digest();
  11041. expect(scope.counter).toEqual(2);
  11042. // Using a listener function
  11043. var food;
  11044. scope.foodCounter = 0;
  11045. expect(scope.foodCounter).toEqual(0);
  11046. scope.$watch(
  11047. // This is the listener function
  11048. function() { return food; },
  11049. // This is the change handler
  11050. function(newValue, oldValue) {
  11051. if ( newValue !== oldValue ) {
  11052. // Only increment the counter if the value changed
  11053. scope.foodCounter = scope.foodCounter + 1;
  11054. }
  11055. }
  11056. );
  11057. // No digest has been run so the counter will be zero
  11058. expect(scope.foodCounter).toEqual(0);
  11059. // Run the digest but since food has not changed count will still be zero
  11060. scope.$digest();
  11061. expect(scope.foodCounter).toEqual(0);
  11062. // Update food and run digest. Now the counter will increment
  11063. food = 'cheeseburger';
  11064. scope.$digest();
  11065. expect(scope.foodCounter).toEqual(1);
  11066. * ```
  11067. *
  11068. *
  11069. *
  11070. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  11071. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  11072. * a call to the `listener`.
  11073. *
  11074. * - `string`: Evaluated as {@link guide/expression expression}
  11075. * - `function(scope)`: called with current `scope` as a parameter.
  11076. * @param {(function()|string)=} listener Callback called whenever the return value of
  11077. * the `watchExpression` changes.
  11078. *
  11079. * - `string`: Evaluated as {@link guide/expression expression}
  11080. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  11081. * parameters.
  11082. *
  11083. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  11084. * comparing for reference equality.
  11085. * @returns {function()} Returns a deregistration function for this listener.
  11086. */
  11087. $watch: function(watchExp, listener, objectEquality) {
  11088. var scope = this,
  11089. get = compileToFn(watchExp, 'watch'),
  11090. array = scope.$$watchers,
  11091. watcher = {
  11092. fn: listener,
  11093. last: initWatchVal,
  11094. get: get,
  11095. exp: watchExp,
  11096. eq: !!objectEquality
  11097. };
  11098. lastDirtyWatch = null;
  11099. // in the case user pass string, we need to compile it, do we really need this ?
  11100. if (!isFunction(listener)) {
  11101. var listenFn = compileToFn(listener || noop, 'listener');
  11102. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  11103. }
  11104. if (typeof watchExp == 'string' && get.constant) {
  11105. var originalFn = watcher.fn;
  11106. watcher.fn = function(newVal, oldVal, scope) {
  11107. originalFn.call(this, newVal, oldVal, scope);
  11108. arrayRemove(array, watcher);
  11109. };
  11110. }
  11111. if (!array) {
  11112. array = scope.$$watchers = [];
  11113. }
  11114. // we use unshift since we use a while loop in $digest for speed.
  11115. // the while loop reads in reverse order.
  11116. array.unshift(watcher);
  11117. return function deregisterWatch() {
  11118. arrayRemove(array, watcher);
  11119. lastDirtyWatch = null;
  11120. };
  11121. },
  11122. /**
  11123. * @ngdoc method
  11124. * @name $rootScope.Scope#$watchCollection
  11125. * @kind function
  11126. *
  11127. * @description
  11128. * Shallow watches the properties of an object and fires whenever any of the properties change
  11129. * (for arrays, this implies watching the array items; for object maps, this implies watching
  11130. * the properties). If a change is detected, the `listener` callback is fired.
  11131. *
  11132. * - The `obj` collection is observed via standard $watch operation and is examined on every
  11133. * call to $digest() to see if any items have been added, removed, or moved.
  11134. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  11135. * adding, removing, and moving items belonging to an object or array.
  11136. *
  11137. *
  11138. * # Example
  11139. * ```js
  11140. $scope.names = ['igor', 'matias', 'misko', 'james'];
  11141. $scope.dataCount = 4;
  11142. $scope.$watchCollection('names', function(newNames, oldNames) {
  11143. $scope.dataCount = newNames.length;
  11144. });
  11145. expect($scope.dataCount).toEqual(4);
  11146. $scope.$digest();
  11147. //still at 4 ... no changes
  11148. expect($scope.dataCount).toEqual(4);
  11149. $scope.names.pop();
  11150. $scope.$digest();
  11151. //now there's been a change
  11152. expect($scope.dataCount).toEqual(3);
  11153. * ```
  11154. *
  11155. *
  11156. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  11157. * expression value should evaluate to an object or an array which is observed on each
  11158. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  11159. * collection will trigger a call to the `listener`.
  11160. *
  11161. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  11162. * when a change is detected.
  11163. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  11164. * - The `oldCollection` object is a copy of the former collection data.
  11165. * Due to performance considerations, the`oldCollection` value is computed only if the
  11166. * `listener` function declares two or more arguments.
  11167. * - The `scope` argument refers to the current scope.
  11168. *
  11169. * @returns {function()} Returns a de-registration function for this listener. When the
  11170. * de-registration function is executed, the internal watch operation is terminated.
  11171. */
  11172. $watchCollection: function(obj, listener) {
  11173. var self = this;
  11174. // the current value, updated on each dirty-check run
  11175. var newValue;
  11176. // a shallow copy of the newValue from the last dirty-check run,
  11177. // updated to match newValue during dirty-check run
  11178. var oldValue;
  11179. // a shallow copy of the newValue from when the last change happened
  11180. var veryOldValue;
  11181. // only track veryOldValue if the listener is asking for it
  11182. var trackVeryOldValue = (listener.length > 1);
  11183. var changeDetected = 0;
  11184. var objGetter = $parse(obj);
  11185. var internalArray = [];
  11186. var internalObject = {};
  11187. var initRun = true;
  11188. var oldLength = 0;
  11189. function $watchCollectionWatch() {
  11190. newValue = objGetter(self);
  11191. var newLength, key, bothNaN;
  11192. if (!isObject(newValue)) { // if primitive
  11193. if (oldValue !== newValue) {
  11194. oldValue = newValue;
  11195. changeDetected++;
  11196. }
  11197. } else if (isArrayLike(newValue)) {
  11198. if (oldValue !== internalArray) {
  11199. // we are transitioning from something which was not an array into array.
  11200. oldValue = internalArray;
  11201. oldLength = oldValue.length = 0;
  11202. changeDetected++;
  11203. }
  11204. newLength = newValue.length;
  11205. if (oldLength !== newLength) {
  11206. // if lengths do not match we need to trigger change notification
  11207. changeDetected++;
  11208. oldValue.length = oldLength = newLength;
  11209. }
  11210. // copy the items to oldValue and look for changes.
  11211. for (var i = 0; i < newLength; i++) {
  11212. bothNaN = (oldValue[i] !== oldValue[i]) &&
  11213. (newValue[i] !== newValue[i]);
  11214. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  11215. changeDetected++;
  11216. oldValue[i] = newValue[i];
  11217. }
  11218. }
  11219. } else {
  11220. if (oldValue !== internalObject) {
  11221. // we are transitioning from something which was not an object into object.
  11222. oldValue = internalObject = {};
  11223. oldLength = 0;
  11224. changeDetected++;
  11225. }
  11226. // copy the items to oldValue and look for changes.
  11227. newLength = 0;
  11228. for (key in newValue) {
  11229. if (newValue.hasOwnProperty(key)) {
  11230. newLength++;
  11231. if (oldValue.hasOwnProperty(key)) {
  11232. bothNaN = (oldValue[key] !== oldValue[key]) &&
  11233. (newValue[key] !== newValue[key]);
  11234. if (!bothNaN && (oldValue[key] !== newValue[key])) {
  11235. changeDetected++;
  11236. oldValue[key] = newValue[key];
  11237. }
  11238. } else {
  11239. oldLength++;
  11240. oldValue[key] = newValue[key];
  11241. changeDetected++;
  11242. }
  11243. }
  11244. }
  11245. if (oldLength > newLength) {
  11246. // we used to have more keys, need to find them and destroy them.
  11247. changeDetected++;
  11248. for(key in oldValue) {
  11249. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  11250. oldLength--;
  11251. delete oldValue[key];
  11252. }
  11253. }
  11254. }
  11255. }
  11256. return changeDetected;
  11257. }
  11258. function $watchCollectionAction() {
  11259. if (initRun) {
  11260. initRun = false;
  11261. listener(newValue, newValue, self);
  11262. } else {
  11263. listener(newValue, veryOldValue, self);
  11264. }
  11265. // make a copy for the next time a collection is changed
  11266. if (trackVeryOldValue) {
  11267. if (!isObject(newValue)) {
  11268. //primitive
  11269. veryOldValue = newValue;
  11270. } else if (isArrayLike(newValue)) {
  11271. veryOldValue = new Array(newValue.length);
  11272. for (var i = 0; i < newValue.length; i++) {
  11273. veryOldValue[i] = newValue[i];
  11274. }
  11275. } else { // if object
  11276. veryOldValue = {};
  11277. for (var key in newValue) {
  11278. if (hasOwnProperty.call(newValue, key)) {
  11279. veryOldValue[key] = newValue[key];
  11280. }
  11281. }
  11282. }
  11283. }
  11284. }
  11285. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  11286. },
  11287. /**
  11288. * @ngdoc method
  11289. * @name $rootScope.Scope#$digest
  11290. * @kind function
  11291. *
  11292. * @description
  11293. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  11294. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  11295. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  11296. * until no more listeners are firing. This means that it is possible to get into an infinite
  11297. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  11298. * iterations exceeds 10.
  11299. *
  11300. * Usually, you don't call `$digest()` directly in
  11301. * {@link ng.directive:ngController controllers} or in
  11302. * {@link ng.$compileProvider#directive directives}.
  11303. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  11304. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  11305. *
  11306. * If you want to be notified whenever `$digest()` is called,
  11307. * you can register a `watchExpression` function with
  11308. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  11309. *
  11310. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  11311. *
  11312. * # Example
  11313. * ```js
  11314. var scope = ...;
  11315. scope.name = 'misko';
  11316. scope.counter = 0;
  11317. expect(scope.counter).toEqual(0);
  11318. scope.$watch('name', function(newValue, oldValue) {
  11319. scope.counter = scope.counter + 1;
  11320. });
  11321. expect(scope.counter).toEqual(0);
  11322. scope.$digest();
  11323. // the listener is always called during the first $digest loop after it was registered
  11324. expect(scope.counter).toEqual(1);
  11325. scope.$digest();
  11326. // but now it will not be called unless the value changes
  11327. expect(scope.counter).toEqual(1);
  11328. scope.name = 'adam';
  11329. scope.$digest();
  11330. expect(scope.counter).toEqual(2);
  11331. * ```
  11332. *
  11333. */
  11334. $digest: function() {
  11335. var watch, value, last,
  11336. watchers,
  11337. asyncQueue = this.$$asyncQueue,
  11338. postDigestQueue = this.$$postDigestQueue,
  11339. length,
  11340. dirty, ttl = TTL,
  11341. next, current, target = this,
  11342. watchLog = [],
  11343. logIdx, logMsg, asyncTask;
  11344. beginPhase('$digest');
  11345. // Check for changes to browser url that happened in sync before the call to $digest
  11346. $browser.$$checkUrlChange();
  11347. lastDirtyWatch = null;
  11348. do { // "while dirty" loop
  11349. dirty = false;
  11350. current = target;
  11351. while(asyncQueue.length) {
  11352. try {
  11353. asyncTask = asyncQueue.shift();
  11354. asyncTask.scope.$eval(asyncTask.expression);
  11355. } catch (e) {
  11356. clearPhase();
  11357. $exceptionHandler(e);
  11358. }
  11359. lastDirtyWatch = null;
  11360. }
  11361. traverseScopesLoop:
  11362. do { // "traverse the scopes" loop
  11363. if ((watchers = current.$$watchers)) {
  11364. // process our watches
  11365. length = watchers.length;
  11366. while (length--) {
  11367. try {
  11368. watch = watchers[length];
  11369. // Most common watches are on primitives, in which case we can short
  11370. // circuit it with === operator, only when === fails do we use .equals
  11371. if (watch) {
  11372. if ((value = watch.get(current)) !== (last = watch.last) &&
  11373. !(watch.eq
  11374. ? equals(value, last)
  11375. : (typeof value === 'number' && typeof last === 'number'
  11376. && isNaN(value) && isNaN(last)))) {
  11377. dirty = true;
  11378. lastDirtyWatch = watch;
  11379. watch.last = watch.eq ? copy(value, null) : value;
  11380. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11381. if (ttl < 5) {
  11382. logIdx = 4 - ttl;
  11383. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11384. logMsg = (isFunction(watch.exp))
  11385. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11386. : watch.exp;
  11387. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11388. watchLog[logIdx].push(logMsg);
  11389. }
  11390. } else if (watch === lastDirtyWatch) {
  11391. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11392. // have already been tested.
  11393. dirty = false;
  11394. break traverseScopesLoop;
  11395. }
  11396. }
  11397. } catch (e) {
  11398. clearPhase();
  11399. $exceptionHandler(e);
  11400. }
  11401. }
  11402. }
  11403. // Insanity Warning: scope depth-first traversal
  11404. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11405. // this piece should be kept in sync with the traversal in $broadcast
  11406. if (!(next = (current.$$childHead ||
  11407. (current !== target && current.$$nextSibling)))) {
  11408. while(current !== target && !(next = current.$$nextSibling)) {
  11409. current = current.$parent;
  11410. }
  11411. }
  11412. } while ((current = next));
  11413. // `break traverseScopesLoop;` takes us to here
  11414. if((dirty || asyncQueue.length) && !(ttl--)) {
  11415. clearPhase();
  11416. throw $rootScopeMinErr('infdig',
  11417. '{0} $digest() iterations reached. Aborting!\n' +
  11418. 'Watchers fired in the last 5 iterations: {1}',
  11419. TTL, toJson(watchLog));
  11420. }
  11421. } while (dirty || asyncQueue.length);
  11422. clearPhase();
  11423. while(postDigestQueue.length) {
  11424. try {
  11425. postDigestQueue.shift()();
  11426. } catch (e) {
  11427. $exceptionHandler(e);
  11428. }
  11429. }
  11430. },
  11431. /**
  11432. * @ngdoc event
  11433. * @name $rootScope.Scope#$destroy
  11434. * @eventType broadcast on scope being destroyed
  11435. *
  11436. * @description
  11437. * Broadcasted when a scope and its children are being destroyed.
  11438. *
  11439. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11440. * clean up DOM bindings before an element is removed from the DOM.
  11441. */
  11442. /**
  11443. * @ngdoc method
  11444. * @name $rootScope.Scope#$destroy
  11445. * @kind function
  11446. *
  11447. * @description
  11448. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11449. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11450. * propagate to the current scope and its children. Removal also implies that the current
  11451. * scope is eligible for garbage collection.
  11452. *
  11453. * The `$destroy()` is usually used by directives such as
  11454. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11455. * unrolling of the loop.
  11456. *
  11457. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11458. * Application code can register a `$destroy` event handler that will give it a chance to
  11459. * perform any necessary cleanup.
  11460. *
  11461. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11462. * clean up DOM bindings before an element is removed from the DOM.
  11463. */
  11464. $destroy: function() {
  11465. // we can't destroy the root scope or a scope that has been already destroyed
  11466. if (this.$$destroyed) return;
  11467. var parent = this.$parent;
  11468. this.$broadcast('$destroy');
  11469. this.$$destroyed = true;
  11470. if (this === $rootScope) return;
  11471. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11472. // sever all the references to parent scopes (after this cleanup, the current scope should
  11473. // not be retained by any of our references and should be eligible for garbage collection)
  11474. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11475. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11476. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11477. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11478. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11479. // and inline caches.
  11480. //
  11481. // see:
  11482. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11483. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11484. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11485. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11486. this.$$childTail = this.$root = null;
  11487. // don't reset these to null in case some async task tries to register a listener/watch/task
  11488. this.$$listeners = {};
  11489. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11490. // prevent NPEs since these methods have references to properties we nulled out
  11491. this.$destroy = this.$digest = this.$apply = noop;
  11492. this.$on = this.$watch = function() { return noop; };
  11493. },
  11494. /**
  11495. * @ngdoc method
  11496. * @name $rootScope.Scope#$eval
  11497. * @kind function
  11498. *
  11499. * @description
  11500. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11501. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11502. * expressions.
  11503. *
  11504. * # Example
  11505. * ```js
  11506. var scope = ng.$rootScope.Scope();
  11507. scope.a = 1;
  11508. scope.b = 2;
  11509. expect(scope.$eval('a+b')).toEqual(3);
  11510. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11511. * ```
  11512. *
  11513. * @param {(string|function())=} expression An angular expression to be executed.
  11514. *
  11515. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11516. * - `function(scope)`: execute the function with the current `scope` parameter.
  11517. *
  11518. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11519. * @returns {*} The result of evaluating the expression.
  11520. */
  11521. $eval: function(expr, locals) {
  11522. return $parse(expr)(this, locals);
  11523. },
  11524. /**
  11525. * @ngdoc method
  11526. * @name $rootScope.Scope#$evalAsync
  11527. * @kind function
  11528. *
  11529. * @description
  11530. * Executes the expression on the current scope at a later point in time.
  11531. *
  11532. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11533. * that:
  11534. *
  11535. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11536. * rendering).
  11537. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11538. * `expression` execution.
  11539. *
  11540. * Any exceptions from the execution of the expression are forwarded to the
  11541. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11542. *
  11543. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11544. * will be scheduled. However, it is encouraged to always call code that changes the model
  11545. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11546. *
  11547. * @param {(string|function())=} expression An angular expression to be executed.
  11548. *
  11549. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11550. * - `function(scope)`: execute the function with the current `scope` parameter.
  11551. *
  11552. */
  11553. $evalAsync: function(expr) {
  11554. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11555. // task also schedule async auto-flush
  11556. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11557. $browser.defer(function() {
  11558. if ($rootScope.$$asyncQueue.length) {
  11559. $rootScope.$digest();
  11560. }
  11561. });
  11562. }
  11563. this.$$asyncQueue.push({scope: this, expression: expr});
  11564. },
  11565. $$postDigest : function(fn) {
  11566. this.$$postDigestQueue.push(fn);
  11567. },
  11568. /**
  11569. * @ngdoc method
  11570. * @name $rootScope.Scope#$apply
  11571. * @kind function
  11572. *
  11573. * @description
  11574. * `$apply()` is used to execute an expression in angular from outside of the angular
  11575. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11576. * Because we are calling into the angular framework we need to perform proper scope life
  11577. * cycle of {@link ng.$exceptionHandler exception handling},
  11578. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11579. *
  11580. * ## Life cycle
  11581. *
  11582. * # Pseudo-Code of `$apply()`
  11583. * ```js
  11584. function $apply(expr) {
  11585. try {
  11586. return $eval(expr);
  11587. } catch (e) {
  11588. $exceptionHandler(e);
  11589. } finally {
  11590. $root.$digest();
  11591. }
  11592. }
  11593. * ```
  11594. *
  11595. *
  11596. * Scope's `$apply()` method transitions through the following stages:
  11597. *
  11598. * 1. The {@link guide/expression expression} is executed using the
  11599. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11600. * 2. Any exceptions from the execution of the expression are forwarded to the
  11601. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11602. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11603. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11604. *
  11605. *
  11606. * @param {(string|function())=} exp An angular expression to be executed.
  11607. *
  11608. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11609. * - `function(scope)`: execute the function with current `scope` parameter.
  11610. *
  11611. * @returns {*} The result of evaluating the expression.
  11612. */
  11613. $apply: function(expr) {
  11614. try {
  11615. beginPhase('$apply');
  11616. return this.$eval(expr);
  11617. } catch (e) {
  11618. $exceptionHandler(e);
  11619. } finally {
  11620. clearPhase();
  11621. try {
  11622. $rootScope.$digest();
  11623. } catch (e) {
  11624. $exceptionHandler(e);
  11625. throw e;
  11626. }
  11627. }
  11628. },
  11629. /**
  11630. * @ngdoc method
  11631. * @name $rootScope.Scope#$on
  11632. * @kind function
  11633. *
  11634. * @description
  11635. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11636. * discussion of event life cycle.
  11637. *
  11638. * The event listener function format is: `function(event, args...)`. The `event` object
  11639. * passed into the listener has the following attributes:
  11640. *
  11641. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11642. * `$broadcast`-ed.
  11643. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11644. * - `name` - `{string}`: name of the event.
  11645. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11646. * further event propagation (available only for events that were `$emit`-ed).
  11647. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11648. * to true.
  11649. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11650. *
  11651. * @param {string} name Event name to listen on.
  11652. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11653. * @returns {function()} Returns a deregistration function for this listener.
  11654. */
  11655. $on: function(name, listener) {
  11656. var namedListeners = this.$$listeners[name];
  11657. if (!namedListeners) {
  11658. this.$$listeners[name] = namedListeners = [];
  11659. }
  11660. namedListeners.push(listener);
  11661. var current = this;
  11662. do {
  11663. if (!current.$$listenerCount[name]) {
  11664. current.$$listenerCount[name] = 0;
  11665. }
  11666. current.$$listenerCount[name]++;
  11667. } while ((current = current.$parent));
  11668. var self = this;
  11669. return function() {
  11670. var indexOfListener = indexOf(namedListeners, listener);
  11671. if (indexOfListener !== -1) {
  11672. namedListeners[indexOfListener] = null;
  11673. decrementListenerCount(self, 1, name);
  11674. }
  11675. };
  11676. },
  11677. /**
  11678. * @ngdoc method
  11679. * @name $rootScope.Scope#$emit
  11680. * @kind function
  11681. *
  11682. * @description
  11683. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11684. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11685. *
  11686. * The event life cycle starts at the scope on which `$emit` was called. All
  11687. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11688. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11689. * registered listeners along the way. The event will stop propagating if one of the listeners
  11690. * cancels it.
  11691. *
  11692. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11693. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11694. *
  11695. * @param {string} name Event name to emit.
  11696. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11697. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11698. */
  11699. $emit: function(name, args) {
  11700. var empty = [],
  11701. namedListeners,
  11702. scope = this,
  11703. stopPropagation = false,
  11704. event = {
  11705. name: name,
  11706. targetScope: scope,
  11707. stopPropagation: function() {stopPropagation = true;},
  11708. preventDefault: function() {
  11709. event.defaultPrevented = true;
  11710. },
  11711. defaultPrevented: false
  11712. },
  11713. listenerArgs = concat([event], arguments, 1),
  11714. i, length;
  11715. do {
  11716. namedListeners = scope.$$listeners[name] || empty;
  11717. event.currentScope = scope;
  11718. for (i=0, length=namedListeners.length; i<length; i++) {
  11719. // if listeners were deregistered, defragment the array
  11720. if (!namedListeners[i]) {
  11721. namedListeners.splice(i, 1);
  11722. i--;
  11723. length--;
  11724. continue;
  11725. }
  11726. try {
  11727. //allow all listeners attached to the current scope to run
  11728. namedListeners[i].apply(null, listenerArgs);
  11729. } catch (e) {
  11730. $exceptionHandler(e);
  11731. }
  11732. }
  11733. //if any listener on the current scope stops propagation, prevent bubbling
  11734. if (stopPropagation) return event;
  11735. //traverse upwards
  11736. scope = scope.$parent;
  11737. } while (scope);
  11738. return event;
  11739. },
  11740. /**
  11741. * @ngdoc method
  11742. * @name $rootScope.Scope#$broadcast
  11743. * @kind function
  11744. *
  11745. * @description
  11746. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11747. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11748. *
  11749. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11750. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11751. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11752. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11753. *
  11754. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11755. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11756. *
  11757. * @param {string} name Event name to broadcast.
  11758. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11759. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11760. */
  11761. $broadcast: function(name, args) {
  11762. var target = this,
  11763. current = target,
  11764. next = target,
  11765. event = {
  11766. name: name,
  11767. targetScope: target,
  11768. preventDefault: function() {
  11769. event.defaultPrevented = true;
  11770. },
  11771. defaultPrevented: false
  11772. },
  11773. listenerArgs = concat([event], arguments, 1),
  11774. listeners, i, length;
  11775. //down while you can, then up and next sibling or up and next sibling until back at root
  11776. while ((current = next)) {
  11777. event.currentScope = current;
  11778. listeners = current.$$listeners[name] || [];
  11779. for (i=0, length = listeners.length; i<length; i++) {
  11780. // if listeners were deregistered, defragment the array
  11781. if (!listeners[i]) {
  11782. listeners.splice(i, 1);
  11783. i--;
  11784. length--;
  11785. continue;
  11786. }
  11787. try {
  11788. listeners[i].apply(null, listenerArgs);
  11789. } catch(e) {
  11790. $exceptionHandler(e);
  11791. }
  11792. }
  11793. // Insanity Warning: scope depth-first traversal
  11794. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11795. // this piece should be kept in sync with the traversal in $digest
  11796. // (though it differs due to having the extra check for $$listenerCount)
  11797. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11798. (current !== target && current.$$nextSibling)))) {
  11799. while(current !== target && !(next = current.$$nextSibling)) {
  11800. current = current.$parent;
  11801. }
  11802. }
  11803. }
  11804. return event;
  11805. }
  11806. };
  11807. var $rootScope = new Scope();
  11808. return $rootScope;
  11809. function beginPhase(phase) {
  11810. if ($rootScope.$$phase) {
  11811. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11812. }
  11813. $rootScope.$$phase = phase;
  11814. }
  11815. function clearPhase() {
  11816. $rootScope.$$phase = null;
  11817. }
  11818. function compileToFn(exp, name) {
  11819. var fn = $parse(exp);
  11820. assertArgFn(fn, name);
  11821. return fn;
  11822. }
  11823. function decrementListenerCount(current, count, name) {
  11824. do {
  11825. current.$$listenerCount[name] -= count;
  11826. if (current.$$listenerCount[name] === 0) {
  11827. delete current.$$listenerCount[name];
  11828. }
  11829. } while ((current = current.$parent));
  11830. }
  11831. /**
  11832. * function used as an initial value for watchers.
  11833. * because it's unique we can easily tell it apart from other values
  11834. */
  11835. function initWatchVal() {}
  11836. }];
  11837. }
  11838. /**
  11839. * @description
  11840. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11841. */
  11842. function $$SanitizeUriProvider() {
  11843. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11844. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file):|data:image\/)/;
  11845. /**
  11846. * @description
  11847. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11848. * urls during a[href] sanitization.
  11849. *
  11850. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11851. *
  11852. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11853. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11854. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11855. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11856. *
  11857. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11858. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11859. * chaining otherwise.
  11860. */
  11861. this.aHrefSanitizationWhitelist = function(regexp) {
  11862. if (isDefined(regexp)) {
  11863. aHrefSanitizationWhitelist = regexp;
  11864. return this;
  11865. }
  11866. return aHrefSanitizationWhitelist;
  11867. };
  11868. /**
  11869. * @description
  11870. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11871. * urls during img[src] 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 img[src] via data-binding is first normalized and turned into
  11876. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  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.imgSrcSanitizationWhitelist = function(regexp) {
  11885. if (isDefined(regexp)) {
  11886. imgSrcSanitizationWhitelist = regexp;
  11887. return this;
  11888. }
  11889. return imgSrcSanitizationWhitelist;
  11890. };
  11891. this.$get = function() {
  11892. return function sanitizeUri(uri, isImage) {
  11893. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11894. var normalizedVal;
  11895. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11896. if (!msie || msie >= 8 ) {
  11897. normalizedVal = urlResolve(uri).href;
  11898. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11899. return 'unsafe:'+normalizedVal;
  11900. }
  11901. }
  11902. return uri;
  11903. };
  11904. };
  11905. }
  11906. var $sceMinErr = minErr('$sce');
  11907. var SCE_CONTEXTS = {
  11908. HTML: 'html',
  11909. CSS: 'css',
  11910. URL: 'url',
  11911. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11912. // url. (e.g. ng-include, script src, templateUrl)
  11913. RESOURCE_URL: 'resourceUrl',
  11914. JS: 'js'
  11915. };
  11916. // Helper functions follow.
  11917. // Copied from:
  11918. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11919. // Prereq: s is a string.
  11920. function escapeForRegexp(s) {
  11921. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11922. replace(/\x08/g, '\\x08');
  11923. }
  11924. function adjustMatcher(matcher) {
  11925. if (matcher === 'self') {
  11926. return matcher;
  11927. } else if (isString(matcher)) {
  11928. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11929. // '*' matches any character except those from the set ':/.?&'.
  11930. // '**' matches any character (like .* in a RegExp).
  11931. // More than 2 *'s raises an error as it's ill defined.
  11932. if (matcher.indexOf('***') > -1) {
  11933. throw $sceMinErr('iwcard',
  11934. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11935. }
  11936. matcher = escapeForRegexp(matcher).
  11937. replace('\\*\\*', '.*').
  11938. replace('\\*', '[^:/.?&;]*');
  11939. return new RegExp('^' + matcher + '$');
  11940. } else if (isRegExp(matcher)) {
  11941. // The only other type of matcher allowed is a Regexp.
  11942. // Match entire URL / disallow partial matches.
  11943. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11944. return new RegExp('^' + matcher.source + '$');
  11945. } else {
  11946. throw $sceMinErr('imatcher',
  11947. 'Matchers may only be "self", string patterns or RegExp objects');
  11948. }
  11949. }
  11950. function adjustMatchers(matchers) {
  11951. var adjustedMatchers = [];
  11952. if (isDefined(matchers)) {
  11953. forEach(matchers, function(matcher) {
  11954. adjustedMatchers.push(adjustMatcher(matcher));
  11955. });
  11956. }
  11957. return adjustedMatchers;
  11958. }
  11959. /**
  11960. * @ngdoc service
  11961. * @name $sceDelegate
  11962. * @kind function
  11963. *
  11964. * @description
  11965. *
  11966. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11967. * Contextual Escaping (SCE)} services to AngularJS.
  11968. *
  11969. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11970. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11971. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11972. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11973. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11974. *
  11975. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11976. *
  11977. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  11978. * can override it completely to change the behavior of `$sce`, the common case would
  11979. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  11980. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  11981. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  11982. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  11983. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11984. */
  11985. /**
  11986. * @ngdoc provider
  11987. * @name $sceDelegateProvider
  11988. * @description
  11989. *
  11990. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11991. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11992. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11993. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11994. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11995. *
  11996. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11997. * Strict Contextual Escaping (SCE)}.
  11998. *
  11999. * **Example**: Consider the following case. <a name="example"></a>
  12000. *
  12001. * - your app is hosted at url `http://myapp.example.com/`
  12002. * - but some of your templates are hosted on other domains you control such as
  12003. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  12004. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  12005. *
  12006. * Here is what a secure configuration for this scenario might look like:
  12007. *
  12008. * ```
  12009. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  12010. * $sceDelegateProvider.resourceUrlWhitelist([
  12011. * // Allow same origin resource loads.
  12012. * 'self',
  12013. * // Allow loading from our assets domain. Notice the difference between * and **.
  12014. * 'http://srv*.assets.example.com/**'
  12015. * ]);
  12016. *
  12017. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  12018. * $sceDelegateProvider.resourceUrlBlacklist([
  12019. * 'http://myapp.example.com/clickThru**'
  12020. * ]);
  12021. * });
  12022. * ```
  12023. */
  12024. function $SceDelegateProvider() {
  12025. this.SCE_CONTEXTS = SCE_CONTEXTS;
  12026. // Resource URLs can also be trusted by policy.
  12027. var resourceUrlWhitelist = ['self'],
  12028. resourceUrlBlacklist = [];
  12029. /**
  12030. * @ngdoc method
  12031. * @name $sceDelegateProvider#resourceUrlWhitelist
  12032. * @kind function
  12033. *
  12034. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  12035. * provided. This must be an array or null. A snapshot of this array is used so further
  12036. * changes to the array are ignored.
  12037. *
  12038. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12039. * allowed in this array.
  12040. *
  12041. * Note: **an empty whitelist array will block all URLs**!
  12042. *
  12043. * @return {Array} the currently set whitelist array.
  12044. *
  12045. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  12046. * same origin resource requests.
  12047. *
  12048. * @description
  12049. * Sets/Gets the whitelist of trusted resource URLs.
  12050. */
  12051. this.resourceUrlWhitelist = function (value) {
  12052. if (arguments.length) {
  12053. resourceUrlWhitelist = adjustMatchers(value);
  12054. }
  12055. return resourceUrlWhitelist;
  12056. };
  12057. /**
  12058. * @ngdoc method
  12059. * @name $sceDelegateProvider#resourceUrlBlacklist
  12060. * @kind function
  12061. *
  12062. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  12063. * provided. This must be an array or null. A snapshot of this array is used so further
  12064. * changes to the array are ignored.
  12065. *
  12066. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  12067. * allowed in this array.
  12068. *
  12069. * The typical usage for the blacklist is to **block
  12070. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  12071. * these would otherwise be trusted but actually return content from the redirected domain.
  12072. *
  12073. * Finally, **the blacklist overrides the whitelist** and has the final say.
  12074. *
  12075. * @return {Array} the currently set blacklist array.
  12076. *
  12077. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  12078. * is no blacklist.)
  12079. *
  12080. * @description
  12081. * Sets/Gets the blacklist of trusted resource URLs.
  12082. */
  12083. this.resourceUrlBlacklist = function (value) {
  12084. if (arguments.length) {
  12085. resourceUrlBlacklist = adjustMatchers(value);
  12086. }
  12087. return resourceUrlBlacklist;
  12088. };
  12089. this.$get = ['$injector', function($injector) {
  12090. var htmlSanitizer = function htmlSanitizer(html) {
  12091. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12092. };
  12093. if ($injector.has('$sanitize')) {
  12094. htmlSanitizer = $injector.get('$sanitize');
  12095. }
  12096. function matchUrl(matcher, parsedUrl) {
  12097. if (matcher === 'self') {
  12098. return urlIsSameOrigin(parsedUrl);
  12099. } else {
  12100. // definitely a regex. See adjustMatchers()
  12101. return !!matcher.exec(parsedUrl.href);
  12102. }
  12103. }
  12104. function isResourceUrlAllowedByPolicy(url) {
  12105. var parsedUrl = urlResolve(url.toString());
  12106. var i, n, allowed = false;
  12107. // Ensure that at least one item from the whitelist allows this url.
  12108. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  12109. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  12110. allowed = true;
  12111. break;
  12112. }
  12113. }
  12114. if (allowed) {
  12115. // Ensure that no item from the blacklist blocked this url.
  12116. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  12117. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  12118. allowed = false;
  12119. break;
  12120. }
  12121. }
  12122. }
  12123. return allowed;
  12124. }
  12125. function generateHolderType(Base) {
  12126. var holderType = function TrustedValueHolderType(trustedValue) {
  12127. this.$$unwrapTrustedValue = function() {
  12128. return trustedValue;
  12129. };
  12130. };
  12131. if (Base) {
  12132. holderType.prototype = new Base();
  12133. }
  12134. holderType.prototype.valueOf = function sceValueOf() {
  12135. return this.$$unwrapTrustedValue();
  12136. };
  12137. holderType.prototype.toString = function sceToString() {
  12138. return this.$$unwrapTrustedValue().toString();
  12139. };
  12140. return holderType;
  12141. }
  12142. var trustedValueHolderBase = generateHolderType(),
  12143. byType = {};
  12144. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  12145. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  12146. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  12147. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  12148. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  12149. /**
  12150. * @ngdoc method
  12151. * @name $sceDelegate#trustAs
  12152. *
  12153. * @description
  12154. * Returns an object that is trusted by angular for use in specified strict
  12155. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  12156. * attribute interpolation, any dom event binding attribute interpolation
  12157. * such as for onclick, etc.) that uses the provided value.
  12158. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  12159. *
  12160. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12161. * resourceUrl, html, js and css.
  12162. * @param {*} value The value that that should be considered trusted/safe.
  12163. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12164. * where Angular expects a $sce.trustAs() return value.
  12165. */
  12166. function trustAs(type, trustedValue) {
  12167. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12168. if (!Constructor) {
  12169. throw $sceMinErr('icontext',
  12170. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  12171. type, trustedValue);
  12172. }
  12173. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  12174. return trustedValue;
  12175. }
  12176. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  12177. // mutable objects, we ensure here that the value passed in is actually a string.
  12178. if (typeof trustedValue !== 'string') {
  12179. throw $sceMinErr('itype',
  12180. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  12181. type);
  12182. }
  12183. return new Constructor(trustedValue);
  12184. }
  12185. /**
  12186. * @ngdoc method
  12187. * @name $sceDelegate#valueOf
  12188. *
  12189. * @description
  12190. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  12191. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  12192. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  12193. *
  12194. * If the passed parameter is not a value that had been returned by {@link
  12195. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  12196. *
  12197. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  12198. * call or anything else.
  12199. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  12200. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  12201. * `value` unchanged.
  12202. */
  12203. function valueOf(maybeTrusted) {
  12204. if (maybeTrusted instanceof trustedValueHolderBase) {
  12205. return maybeTrusted.$$unwrapTrustedValue();
  12206. } else {
  12207. return maybeTrusted;
  12208. }
  12209. }
  12210. /**
  12211. * @ngdoc method
  12212. * @name $sceDelegate#getTrusted
  12213. *
  12214. * @description
  12215. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  12216. * returns the originally supplied value if the queried context type is a supertype of the
  12217. * created type. If this condition isn't satisfied, throws an exception.
  12218. *
  12219. * @param {string} type The kind of context in which this value is to be used.
  12220. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  12221. * `$sceDelegate.trustAs`} call.
  12222. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  12223. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  12224. */
  12225. function getTrusted(type, maybeTrusted) {
  12226. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  12227. return maybeTrusted;
  12228. }
  12229. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12230. if (constructor && maybeTrusted instanceof constructor) {
  12231. return maybeTrusted.$$unwrapTrustedValue();
  12232. }
  12233. // If we get here, then we may only take one of two actions.
  12234. // 1. sanitize the value for the requested type, or
  12235. // 2. throw an exception.
  12236. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  12237. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  12238. return maybeTrusted;
  12239. } else {
  12240. throw $sceMinErr('insecurl',
  12241. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  12242. maybeTrusted.toString());
  12243. }
  12244. } else if (type === SCE_CONTEXTS.HTML) {
  12245. return htmlSanitizer(maybeTrusted);
  12246. }
  12247. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12248. }
  12249. return { trustAs: trustAs,
  12250. getTrusted: getTrusted,
  12251. valueOf: valueOf };
  12252. }];
  12253. }
  12254. /**
  12255. * @ngdoc provider
  12256. * @name $sceProvider
  12257. * @description
  12258. *
  12259. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  12260. * - enable/disable Strict Contextual Escaping (SCE) in a module
  12261. * - override the default implementation with a custom delegate
  12262. *
  12263. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  12264. */
  12265. /* jshint maxlen: false*/
  12266. /**
  12267. * @ngdoc service
  12268. * @name $sce
  12269. * @kind function
  12270. *
  12271. * @description
  12272. *
  12273. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  12274. *
  12275. * # Strict Contextual Escaping
  12276. *
  12277. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  12278. * contexts to result in a value that is marked as safe to use for that context. One example of
  12279. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  12280. * to these contexts as privileged or SCE contexts.
  12281. *
  12282. * As of version 1.2, Angular ships with SCE enabled by default.
  12283. *
  12284. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  12285. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  12286. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  12287. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  12288. * to the top of your HTML document.
  12289. *
  12290. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  12291. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  12292. *
  12293. * Here's an example of a binding in a privileged context:
  12294. *
  12295. * ```
  12296. * <input ng-model="userHtml">
  12297. * <div ng-bind-html="userHtml"></div>
  12298. * ```
  12299. *
  12300. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  12301. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  12302. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  12303. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  12304. * security vulnerabilities.)
  12305. *
  12306. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  12307. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  12308. *
  12309. * How would you ensure that every place that used these types of bindings was bound to a value that
  12310. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  12311. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  12312. * properties/fields and forgot to update the binding to the sanitized value?
  12313. *
  12314. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  12315. * determine that something explicitly says it's safe to use a value for binding in that
  12316. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  12317. * for those values that you can easily tell are safe - because they were received from your server,
  12318. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  12319. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  12320. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  12321. *
  12322. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  12323. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  12324. * obtain values that will be accepted by SCE / privileged contexts.
  12325. *
  12326. *
  12327. * ## How does it work?
  12328. *
  12329. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  12330. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  12331. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  12332. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  12333. *
  12334. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  12335. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  12336. * simplified):
  12337. *
  12338. * ```
  12339. * var ngBindHtmlDirective = ['$sce', function($sce) {
  12340. * return function(scope, element, attr) {
  12341. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  12342. * element.html(value || '');
  12343. * });
  12344. * };
  12345. * }];
  12346. * ```
  12347. *
  12348. * ## Impact on loading templates
  12349. *
  12350. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12351. * `templateUrl`'s specified by {@link guide/directive directives}.
  12352. *
  12353. * By default, Angular only loads templates from the same domain and protocol as the application
  12354. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12355. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12356. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12357. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12358. *
  12359. * *Please note*:
  12360. * The browser's
  12361. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12362. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12363. * policy apply in addition to this and may further restrict whether the template is successfully
  12364. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12365. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12366. * browsers.
  12367. *
  12368. * ## This feels like too much overhead for the developer?
  12369. *
  12370. * It's important to remember that SCE only applies to interpolation expressions.
  12371. *
  12372. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12373. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12374. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12375. *
  12376. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12377. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12378. *
  12379. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12380. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12381. * It blocks loading templates from other domains or loading templates over http from an https
  12382. * served document. You can change these by setting your own custom {@link
  12383. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12384. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12385. *
  12386. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12387. * application that's secure and can be audited to verify that with much more ease than bolting
  12388. * security onto an application later.
  12389. *
  12390. * <a name="contexts"></a>
  12391. * ## What trusted context types are supported?
  12392. *
  12393. * | Context | Notes |
  12394. * |---------------------|----------------|
  12395. * | `$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. |
  12396. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12397. * | `$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. |
  12398. * | `$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. |
  12399. * | `$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. |
  12400. *
  12401. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12402. *
  12403. * Each element in these arrays must be one of the following:
  12404. *
  12405. * - **'self'**
  12406. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12407. * domain** as the application document using the **same protocol**.
  12408. * - **String** (except the special value `'self'`)
  12409. * - The string is matched against the full *normalized / absolute URL* of the resource
  12410. * being tested (substring matches are not good enough.)
  12411. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12412. * match themselves.
  12413. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12414. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12415. * in a whitelist.
  12416. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12417. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12418. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12419. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  12420. * http://foo.example.com/templates/**).
  12421. * - **RegExp** (*see caveat below*)
  12422. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12423. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12424. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12425. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12426. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12427. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12428. * is highly recommended to use the string patterns and only fall back to regular expressions
  12429. * if they as a last resort.
  12430. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12431. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12432. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12433. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12434. * - If you are generating your JavaScript from some other templating engine (not
  12435. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12436. * remember to escape your regular expression (and be aware that you might need more than
  12437. * one level of escaping depending on your templating engine and the way you interpolated
  12438. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12439. * enough before coding your own. e.g. Ruby has
  12440. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12441. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12442. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12443. * Closure library's [goog.string.regExpEscape(s)](
  12444. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12445. *
  12446. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12447. *
  12448. * ## Show me an example using SCE.
  12449. *
  12450. * <example module="mySceApp" deps="angular-sanitize.js">
  12451. * <file name="index.html">
  12452. * <div ng-controller="myAppController as myCtrl">
  12453. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12454. * <b>User comments</b><br>
  12455. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12456. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12457. * exploit.
  12458. * <div class="well">
  12459. * <div ng-repeat="userComment in myCtrl.userComments">
  12460. * <b>{{userComment.name}}</b>:
  12461. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12462. * <br>
  12463. * </div>
  12464. * </div>
  12465. * </div>
  12466. * </file>
  12467. *
  12468. * <file name="script.js">
  12469. * var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12470. *
  12471. * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12472. * var self = this;
  12473. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12474. * self.userComments = userComments;
  12475. * });
  12476. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12477. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12478. * 'sanitization.&quot;">Hover over this text.</span>');
  12479. * });
  12480. * </file>
  12481. *
  12482. * <file name="test_data.json">
  12483. * [
  12484. * { "name": "Alice",
  12485. * "htmlComment":
  12486. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12487. * },
  12488. * { "name": "Bob",
  12489. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12490. * }
  12491. * ]
  12492. * </file>
  12493. *
  12494. * <file name="protractor.js" type="protractor">
  12495. * describe('SCE doc demo', function() {
  12496. * it('should sanitize untrusted values', function() {
  12497. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  12498. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12499. * });
  12500. *
  12501. * it('should NOT sanitize explicitly trusted values', function() {
  12502. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12503. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12504. * 'sanitization.&quot;">Hover over this text.</span>');
  12505. * });
  12506. * });
  12507. * </file>
  12508. * </example>
  12509. *
  12510. *
  12511. *
  12512. * ## Can I disable SCE completely?
  12513. *
  12514. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12515. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12516. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12517. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12518. * you're migrating them a module at a time.
  12519. *
  12520. * That said, here's how you can completely disable SCE:
  12521. *
  12522. * ```
  12523. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12524. * // Completely disable SCE. For demonstration purposes only!
  12525. * // Do not use in new projects.
  12526. * $sceProvider.enabled(false);
  12527. * });
  12528. * ```
  12529. *
  12530. */
  12531. /* jshint maxlen: 100 */
  12532. function $SceProvider() {
  12533. var enabled = true;
  12534. /**
  12535. * @ngdoc method
  12536. * @name $sceProvider#enabled
  12537. * @kind function
  12538. *
  12539. * @param {boolean=} value If provided, then enables/disables SCE.
  12540. * @return {boolean} true if SCE is enabled, false otherwise.
  12541. *
  12542. * @description
  12543. * Enables/disables SCE and returns the current value.
  12544. */
  12545. this.enabled = function (value) {
  12546. if (arguments.length) {
  12547. enabled = !!value;
  12548. }
  12549. return enabled;
  12550. };
  12551. /* Design notes on the default implementation for SCE.
  12552. *
  12553. * The API contract for the SCE delegate
  12554. * -------------------------------------
  12555. * The SCE delegate object must provide the following 3 methods:
  12556. *
  12557. * - trustAs(contextEnum, value)
  12558. * This method is used to tell the SCE service that the provided value is OK to use in the
  12559. * contexts specified by contextEnum. It must return an object that will be accepted by
  12560. * getTrusted() for a compatible contextEnum and return this value.
  12561. *
  12562. * - valueOf(value)
  12563. * For values that were not produced by trustAs(), return them as is. For values that were
  12564. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12565. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12566. * such a value.
  12567. *
  12568. * - getTrusted(contextEnum, value)
  12569. * This function should return the a value that is safe to use in the context specified by
  12570. * contextEnum or throw and exception otherwise.
  12571. *
  12572. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12573. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12574. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12575. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12576. * return the same object passed in if it was found in the registry under a compatible context or
  12577. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12578. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12579. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12580. *
  12581. *
  12582. * A note on the inheritance model for SCE contexts
  12583. * ------------------------------------------------
  12584. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12585. * is purely an implementation details.
  12586. *
  12587. * The contract is simply this:
  12588. *
  12589. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12590. * will also succeed.
  12591. *
  12592. * Inheritance happens to capture this in a natural way. In some future, we
  12593. * may not use inheritance anymore. That is OK because no code outside of
  12594. * sce.js and sceSpecs.js would need to be aware of this detail.
  12595. */
  12596. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12597. $parse, $sniffer, $sceDelegate) {
  12598. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12599. // the "expression(javascript expression)" syntax which is insecure.
  12600. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12601. throw $sceMinErr('iequirks',
  12602. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12603. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12604. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12605. }
  12606. var sce = shallowCopy(SCE_CONTEXTS);
  12607. /**
  12608. * @ngdoc method
  12609. * @name $sce#isEnabled
  12610. * @kind function
  12611. *
  12612. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12613. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12614. *
  12615. * @description
  12616. * Returns a boolean indicating if SCE is enabled.
  12617. */
  12618. sce.isEnabled = function () {
  12619. return enabled;
  12620. };
  12621. sce.trustAs = $sceDelegate.trustAs;
  12622. sce.getTrusted = $sceDelegate.getTrusted;
  12623. sce.valueOf = $sceDelegate.valueOf;
  12624. if (!enabled) {
  12625. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12626. sce.valueOf = identity;
  12627. }
  12628. /**
  12629. * @ngdoc method
  12630. * @name $sce#parseAs
  12631. *
  12632. * @description
  12633. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12634. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12635. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12636. * *result*)}
  12637. *
  12638. * @param {string} type The kind of SCE context in which this result will be used.
  12639. * @param {string} expression String expression to compile.
  12640. * @returns {function(context, locals)} a function which represents the compiled expression:
  12641. *
  12642. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12643. * are evaluated against (typically a scope object).
  12644. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12645. * `context`.
  12646. */
  12647. sce.parseAs = function sceParseAs(type, expr) {
  12648. var parsed = $parse(expr);
  12649. if (parsed.literal && parsed.constant) {
  12650. return parsed;
  12651. } else {
  12652. return function sceParseAsTrusted(self, locals) {
  12653. return sce.getTrusted(type, parsed(self, locals));
  12654. };
  12655. }
  12656. };
  12657. /**
  12658. * @ngdoc method
  12659. * @name $sce#trustAs
  12660. *
  12661. * @description
  12662. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12663. * returns an object that is trusted by angular for use in specified strict contextual
  12664. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12665. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12666. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12667. * escaping.
  12668. *
  12669. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12670. * resource_url, html, js and css.
  12671. * @param {*} value The value that that should be considered trusted/safe.
  12672. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12673. * where Angular expects a $sce.trustAs() return value.
  12674. */
  12675. /**
  12676. * @ngdoc method
  12677. * @name $sce#trustAsHtml
  12678. *
  12679. * @description
  12680. * Shorthand method. `$sce.trustAsHtml(value)` →
  12681. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12682. *
  12683. * @param {*} value The value to trustAs.
  12684. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12685. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12686. * only accept expressions that are either literal constants or are the
  12687. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12688. */
  12689. /**
  12690. * @ngdoc method
  12691. * @name $sce#trustAsUrl
  12692. *
  12693. * @description
  12694. * Shorthand method. `$sce.trustAsUrl(value)` →
  12695. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12696. *
  12697. * @param {*} value The value to trustAs.
  12698. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12699. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12700. * only accept expressions that are either literal constants or are the
  12701. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12702. */
  12703. /**
  12704. * @ngdoc method
  12705. * @name $sce#trustAsResourceUrl
  12706. *
  12707. * @description
  12708. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12709. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12710. *
  12711. * @param {*} value The value to trustAs.
  12712. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12713. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12714. * only accept expressions that are either literal constants or are the return
  12715. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12716. */
  12717. /**
  12718. * @ngdoc method
  12719. * @name $sce#trustAsJs
  12720. *
  12721. * @description
  12722. * Shorthand method. `$sce.trustAsJs(value)` →
  12723. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12724. *
  12725. * @param {*} value The value to trustAs.
  12726. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12727. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12728. * only accept expressions that are either literal constants or are the
  12729. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12730. */
  12731. /**
  12732. * @ngdoc method
  12733. * @name $sce#getTrusted
  12734. *
  12735. * @description
  12736. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12737. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12738. * originally supplied value if the queried context type is a supertype of the created type.
  12739. * If this condition isn't satisfied, throws an exception.
  12740. *
  12741. * @param {string} type The kind of context in which this value is to be used.
  12742. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12743. * call.
  12744. * @returns {*} The value the was originally provided to
  12745. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12746. * Otherwise, throws an exception.
  12747. */
  12748. /**
  12749. * @ngdoc method
  12750. * @name $sce#getTrustedHtml
  12751. *
  12752. * @description
  12753. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12754. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12755. *
  12756. * @param {*} value The value to pass to `$sce.getTrusted`.
  12757. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12758. */
  12759. /**
  12760. * @ngdoc method
  12761. * @name $sce#getTrustedCss
  12762. *
  12763. * @description
  12764. * Shorthand method. `$sce.getTrustedCss(value)` →
  12765. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12766. *
  12767. * @param {*} value The value to pass to `$sce.getTrusted`.
  12768. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12769. */
  12770. /**
  12771. * @ngdoc method
  12772. * @name $sce#getTrustedUrl
  12773. *
  12774. * @description
  12775. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12776. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12777. *
  12778. * @param {*} value The value to pass to `$sce.getTrusted`.
  12779. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12780. */
  12781. /**
  12782. * @ngdoc method
  12783. * @name $sce#getTrustedResourceUrl
  12784. *
  12785. * @description
  12786. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12787. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12788. *
  12789. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12790. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12791. */
  12792. /**
  12793. * @ngdoc method
  12794. * @name $sce#getTrustedJs
  12795. *
  12796. * @description
  12797. * Shorthand method. `$sce.getTrustedJs(value)` →
  12798. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12799. *
  12800. * @param {*} value The value to pass to `$sce.getTrusted`.
  12801. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12802. */
  12803. /**
  12804. * @ngdoc method
  12805. * @name $sce#parseAsHtml
  12806. *
  12807. * @description
  12808. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12809. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12810. *
  12811. * @param {string} expression String expression to compile.
  12812. * @returns {function(context, locals)} a function which represents the compiled expression:
  12813. *
  12814. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12815. * are evaluated against (typically a scope object).
  12816. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12817. * `context`.
  12818. */
  12819. /**
  12820. * @ngdoc method
  12821. * @name $sce#parseAsCss
  12822. *
  12823. * @description
  12824. * Shorthand method. `$sce.parseAsCss(value)` →
  12825. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12826. *
  12827. * @param {string} expression String expression to compile.
  12828. * @returns {function(context, locals)} a function which represents the compiled expression:
  12829. *
  12830. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12831. * are evaluated against (typically a scope object).
  12832. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12833. * `context`.
  12834. */
  12835. /**
  12836. * @ngdoc method
  12837. * @name $sce#parseAsUrl
  12838. *
  12839. * @description
  12840. * Shorthand method. `$sce.parseAsUrl(value)` →
  12841. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12842. *
  12843. * @param {string} expression String expression to compile.
  12844. * @returns {function(context, locals)} a function which represents the compiled expression:
  12845. *
  12846. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12847. * are evaluated against (typically a scope object).
  12848. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12849. * `context`.
  12850. */
  12851. /**
  12852. * @ngdoc method
  12853. * @name $sce#parseAsResourceUrl
  12854. *
  12855. * @description
  12856. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12857. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12858. *
  12859. * @param {string} expression String expression to compile.
  12860. * @returns {function(context, locals)} a function which represents the compiled expression:
  12861. *
  12862. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12863. * are evaluated against (typically a scope object).
  12864. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12865. * `context`.
  12866. */
  12867. /**
  12868. * @ngdoc method
  12869. * @name $sce#parseAsJs
  12870. *
  12871. * @description
  12872. * Shorthand method. `$sce.parseAsJs(value)` →
  12873. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12874. *
  12875. * @param {string} expression String expression to compile.
  12876. * @returns {function(context, locals)} a function which represents the compiled expression:
  12877. *
  12878. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12879. * are evaluated against (typically a scope object).
  12880. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12881. * `context`.
  12882. */
  12883. // Shorthand delegations.
  12884. var parse = sce.parseAs,
  12885. getTrusted = sce.getTrusted,
  12886. trustAs = sce.trustAs;
  12887. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12888. var lName = lowercase(name);
  12889. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12890. return parse(enumValue, expr);
  12891. };
  12892. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12893. return getTrusted(enumValue, value);
  12894. };
  12895. sce[camelCase("trust_as_" + lName)] = function (value) {
  12896. return trustAs(enumValue, value);
  12897. };
  12898. });
  12899. return sce;
  12900. }];
  12901. }
  12902. /**
  12903. * !!! This is an undocumented "private" service !!!
  12904. *
  12905. * @name $sniffer
  12906. * @requires $window
  12907. * @requires $document
  12908. *
  12909. * @property {boolean} history Does the browser support html5 history api ?
  12910. * @property {boolean} hashchange Does the browser support hashchange event ?
  12911. * @property {boolean} transitions Does the browser support CSS transition events ?
  12912. * @property {boolean} animations Does the browser support CSS animation events ?
  12913. *
  12914. * @description
  12915. * This is very simple implementation of testing browser's features.
  12916. */
  12917. function $SnifferProvider() {
  12918. this.$get = ['$window', '$document', function($window, $document) {
  12919. var eventSupport = {},
  12920. android =
  12921. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12922. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12923. document = $document[0] || {},
  12924. documentMode = document.documentMode,
  12925. vendorPrefix,
  12926. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12927. bodyStyle = document.body && document.body.style,
  12928. transitions = false,
  12929. animations = false,
  12930. match;
  12931. if (bodyStyle) {
  12932. for(var prop in bodyStyle) {
  12933. if(match = vendorRegex.exec(prop)) {
  12934. vendorPrefix = match[0];
  12935. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12936. break;
  12937. }
  12938. }
  12939. if(!vendorPrefix) {
  12940. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12941. }
  12942. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12943. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12944. if (android && (!transitions||!animations)) {
  12945. transitions = isString(document.body.style.webkitTransition);
  12946. animations = isString(document.body.style.webkitAnimation);
  12947. }
  12948. }
  12949. return {
  12950. // Android has history.pushState, but it does not update location correctly
  12951. // so let's not use the history API at all.
  12952. // http://code.google.com/p/android/issues/detail?id=17471
  12953. // https://github.com/angular/angular.js/issues/904
  12954. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12955. // so let's not use the history API also
  12956. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12957. // jshint -W018
  12958. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12959. // jshint +W018
  12960. hashchange: 'onhashchange' in $window &&
  12961. // IE8 compatible mode lies
  12962. (!documentMode || documentMode > 7),
  12963. hasEvent: function(event) {
  12964. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12965. // it. In particular the event is not fired when backspace or delete key are pressed or
  12966. // when cut operation is performed.
  12967. if (event == 'input' && msie == 9) return false;
  12968. if (isUndefined(eventSupport[event])) {
  12969. var divElm = document.createElement('div');
  12970. eventSupport[event] = 'on' + event in divElm;
  12971. }
  12972. return eventSupport[event];
  12973. },
  12974. csp: csp(),
  12975. vendorPrefix: vendorPrefix,
  12976. transitions : transitions,
  12977. animations : animations,
  12978. android: android,
  12979. msie : msie,
  12980. msieDocumentMode: documentMode
  12981. };
  12982. }];
  12983. }
  12984. function $TimeoutProvider() {
  12985. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12986. function($rootScope, $browser, $q, $exceptionHandler) {
  12987. var deferreds = {};
  12988. /**
  12989. * @ngdoc service
  12990. * @name $timeout
  12991. *
  12992. * @description
  12993. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12994. * block and delegates any exceptions to
  12995. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12996. *
  12997. * The return value of registering a timeout function is a promise, which will be resolved when
  12998. * the timeout is reached and the timeout function is executed.
  12999. *
  13000. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  13001. *
  13002. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  13003. * synchronously flush the queue of deferred functions.
  13004. *
  13005. * @param {function()} fn A function, whose execution should be delayed.
  13006. * @param {number=} [delay=0] Delay in milliseconds.
  13007. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  13008. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  13009. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  13010. * promise will be resolved with is the return value of the `fn` function.
  13011. *
  13012. */
  13013. function timeout(fn, delay, invokeApply) {
  13014. var deferred = $q.defer(),
  13015. promise = deferred.promise,
  13016. skipApply = (isDefined(invokeApply) && !invokeApply),
  13017. timeoutId;
  13018. timeoutId = $browser.defer(function() {
  13019. try {
  13020. deferred.resolve(fn());
  13021. } catch(e) {
  13022. deferred.reject(e);
  13023. $exceptionHandler(e);
  13024. }
  13025. finally {
  13026. delete deferreds[promise.$$timeoutId];
  13027. }
  13028. if (!skipApply) $rootScope.$apply();
  13029. }, delay);
  13030. promise.$$timeoutId = timeoutId;
  13031. deferreds[timeoutId] = deferred;
  13032. return promise;
  13033. }
  13034. /**
  13035. * @ngdoc method
  13036. * @name $timeout#cancel
  13037. *
  13038. * @description
  13039. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  13040. * resolved with a rejection.
  13041. *
  13042. * @param {Promise=} promise Promise returned by the `$timeout` function.
  13043. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  13044. * canceled.
  13045. */
  13046. timeout.cancel = function(promise) {
  13047. if (promise && promise.$$timeoutId in deferreds) {
  13048. deferreds[promise.$$timeoutId].reject('canceled');
  13049. delete deferreds[promise.$$timeoutId];
  13050. return $browser.defer.cancel(promise.$$timeoutId);
  13051. }
  13052. return false;
  13053. };
  13054. return timeout;
  13055. }];
  13056. }
  13057. // NOTE: The usage of window and document instead of $window and $document here is
  13058. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  13059. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  13060. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  13061. // doesn't know about mocked locations and resolves URLs to the real document - which is
  13062. // exactly the behavior needed here. There is little value is mocking these out for this
  13063. // service.
  13064. var urlParsingNode = document.createElement("a");
  13065. var originUrl = urlResolve(window.location.href, true);
  13066. /**
  13067. *
  13068. * Implementation Notes for non-IE browsers
  13069. * ----------------------------------------
  13070. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  13071. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  13072. * URL will be resolved into an absolute URL in the context of the application document.
  13073. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  13074. * properties are all populated to reflect the normalized URL. This approach has wide
  13075. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  13076. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13077. *
  13078. * Implementation Notes for IE
  13079. * ---------------------------
  13080. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  13081. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  13082. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  13083. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  13084. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  13085. * properties such as protocol, hostname, port, etc.
  13086. *
  13087. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  13088. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  13089. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  13090. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  13091. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  13092. * method and IE < 8 is unsupported.
  13093. *
  13094. * References:
  13095. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  13096. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  13097. * http://url.spec.whatwg.org/#urlutils
  13098. * https://github.com/angular/angular.js/pull/2902
  13099. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  13100. *
  13101. * @kind function
  13102. * @param {string} url The URL to be parsed.
  13103. * @description Normalizes and parses a URL.
  13104. * @returns {object} Returns the normalized URL as a dictionary.
  13105. *
  13106. * | member name | Description |
  13107. * |---------------|----------------|
  13108. * | href | A normalized version of the provided URL if it was not an absolute URL |
  13109. * | protocol | The protocol including the trailing colon |
  13110. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  13111. * | search | The search params, minus the question mark |
  13112. * | hash | The hash string, minus the hash symbol
  13113. * | hostname | The hostname
  13114. * | port | The port, without ":"
  13115. * | pathname | The pathname, beginning with "/"
  13116. *
  13117. */
  13118. function urlResolve(url, base) {
  13119. var href = url;
  13120. if (msie) {
  13121. // Normalize before parse. Refer Implementation Notes on why this is
  13122. // done in two steps on IE.
  13123. urlParsingNode.setAttribute("href", href);
  13124. href = urlParsingNode.href;
  13125. }
  13126. urlParsingNode.setAttribute('href', href);
  13127. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  13128. return {
  13129. href: urlParsingNode.href,
  13130. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  13131. host: urlParsingNode.host,
  13132. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  13133. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  13134. hostname: urlParsingNode.hostname,
  13135. port: urlParsingNode.port,
  13136. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  13137. ? urlParsingNode.pathname
  13138. : '/' + urlParsingNode.pathname
  13139. };
  13140. }
  13141. /**
  13142. * Parse a request URL and determine whether this is a same-origin request as the application document.
  13143. *
  13144. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  13145. * or a parsed URL object.
  13146. * @returns {boolean} Whether the request is for the same origin as the application document.
  13147. */
  13148. function urlIsSameOrigin(requestUrl) {
  13149. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  13150. return (parsed.protocol === originUrl.protocol &&
  13151. parsed.host === originUrl.host);
  13152. }
  13153. /**
  13154. * @ngdoc service
  13155. * @name $window
  13156. *
  13157. * @description
  13158. * A reference to the browser's `window` object. While `window`
  13159. * is globally available in JavaScript, it causes testability problems, because
  13160. * it is a global variable. In angular we always refer to it through the
  13161. * `$window` service, so it may be overridden, removed or mocked for testing.
  13162. *
  13163. * Expressions, like the one defined for the `ngClick` directive in the example
  13164. * below, are evaluated with respect to the current scope. Therefore, there is
  13165. * no risk of inadvertently coding in a dependency on a global value in such an
  13166. * expression.
  13167. *
  13168. * @example
  13169. <example module="windowExample">
  13170. <file name="index.html">
  13171. <script>
  13172. angular.module('windowExample', [])
  13173. .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
  13174. $scope.greeting = 'Hello, World!';
  13175. $scope.doGreeting = function(greeting) {
  13176. $window.alert(greeting);
  13177. };
  13178. }]);
  13179. </script>
  13180. <div ng-controller="ExampleController">
  13181. <input type="text" ng-model="greeting" />
  13182. <button ng-click="doGreeting(greeting)">ALERT</button>
  13183. </div>
  13184. </file>
  13185. <file name="protractor.js" type="protractor">
  13186. it('should display the greeting in the input box', function() {
  13187. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  13188. // If we click the button it will block the test runner
  13189. // element(':button').click();
  13190. });
  13191. </file>
  13192. </example>
  13193. */
  13194. function $WindowProvider(){
  13195. this.$get = valueFn(window);
  13196. }
  13197. /* global currencyFilter: true,
  13198. dateFilter: true,
  13199. filterFilter: true,
  13200. jsonFilter: true,
  13201. limitToFilter: true,
  13202. lowercaseFilter: true,
  13203. numberFilter: true,
  13204. orderByFilter: true,
  13205. uppercaseFilter: true,
  13206. */
  13207. /**
  13208. * @ngdoc provider
  13209. * @name $filterProvider
  13210. * @description
  13211. *
  13212. * Filters are just functions which transform input to an output. However filters need to be
  13213. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  13214. * annotated with dependencies and is responsible for creating a filter function.
  13215. *
  13216. * ```js
  13217. * // Filter registration
  13218. * function MyModule($provide, $filterProvider) {
  13219. * // create a service to demonstrate injection (not always needed)
  13220. * $provide.value('greet', function(name){
  13221. * return 'Hello ' + name + '!';
  13222. * });
  13223. *
  13224. * // register a filter factory which uses the
  13225. * // greet service to demonstrate DI.
  13226. * $filterProvider.register('greet', function(greet){
  13227. * // return the filter function which uses the greet service
  13228. * // to generate salutation
  13229. * return function(text) {
  13230. * // filters need to be forgiving so check input validity
  13231. * return text && greet(text) || text;
  13232. * };
  13233. * });
  13234. * }
  13235. * ```
  13236. *
  13237. * The filter function is registered with the `$injector` under the filter name suffix with
  13238. * `Filter`.
  13239. *
  13240. * ```js
  13241. * it('should be the same instance', inject(
  13242. * function($filterProvider) {
  13243. * $filterProvider.register('reverse', function(){
  13244. * return ...;
  13245. * });
  13246. * },
  13247. * function($filter, reverseFilter) {
  13248. * expect($filter('reverse')).toBe(reverseFilter);
  13249. * });
  13250. * ```
  13251. *
  13252. *
  13253. * For more information about how angular filters work, and how to create your own filters, see
  13254. * {@link guide/filter Filters} in the Angular Developer Guide.
  13255. */
  13256. /**
  13257. * @ngdoc service
  13258. * @name $filter
  13259. * @kind function
  13260. * @description
  13261. * Filters are used for formatting data displayed to the user.
  13262. *
  13263. * The general syntax in templates is as follows:
  13264. *
  13265. * {{ expression [| filter_name[:parameter_value] ... ] }}
  13266. *
  13267. * @param {String} name Name of the filter function to retrieve
  13268. * @return {Function} the filter function
  13269. * @example
  13270. <example name="$filter" module="filterExample">
  13271. <file name="index.html">
  13272. <div ng-controller="MainCtrl">
  13273. <h3>{{ originalText }}</h3>
  13274. <h3>{{ filteredText }}</h3>
  13275. </div>
  13276. </file>
  13277. <file name="script.js">
  13278. angular.module('filterExample', [])
  13279. .controller('MainCtrl', function($scope, $filter) {
  13280. $scope.originalText = 'hello';
  13281. $scope.filteredText = $filter('uppercase')($scope.originalText);
  13282. });
  13283. </file>
  13284. </example>
  13285. */
  13286. $FilterProvider.$inject = ['$provide'];
  13287. function $FilterProvider($provide) {
  13288. var suffix = 'Filter';
  13289. /**
  13290. * @ngdoc method
  13291. * @name $filterProvider#register
  13292. * @param {string|Object} name Name of the filter function, or an object map of filters where
  13293. * the keys are the filter names and the values are the filter factories.
  13294. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  13295. * of the registered filter instances.
  13296. */
  13297. function register(name, factory) {
  13298. if(isObject(name)) {
  13299. var filters = {};
  13300. forEach(name, function(filter, key) {
  13301. filters[key] = register(key, filter);
  13302. });
  13303. return filters;
  13304. } else {
  13305. return $provide.factory(name + suffix, factory);
  13306. }
  13307. }
  13308. this.register = register;
  13309. this.$get = ['$injector', function($injector) {
  13310. return function(name) {
  13311. return $injector.get(name + suffix);
  13312. };
  13313. }];
  13314. ////////////////////////////////////////
  13315. /* global
  13316. currencyFilter: false,
  13317. dateFilter: false,
  13318. filterFilter: false,
  13319. jsonFilter: false,
  13320. limitToFilter: false,
  13321. lowercaseFilter: false,
  13322. numberFilter: false,
  13323. orderByFilter: false,
  13324. uppercaseFilter: false,
  13325. */
  13326. register('currency', currencyFilter);
  13327. register('date', dateFilter);
  13328. register('filter', filterFilter);
  13329. register('json', jsonFilter);
  13330. register('limitTo', limitToFilter);
  13331. register('lowercase', lowercaseFilter);
  13332. register('number', numberFilter);
  13333. register('orderBy', orderByFilter);
  13334. register('uppercase', uppercaseFilter);
  13335. }
  13336. /**
  13337. * @ngdoc filter
  13338. * @name filter
  13339. * @kind function
  13340. *
  13341. * @description
  13342. * Selects a subset of items from `array` and returns it as a new array.
  13343. *
  13344. * @param {Array} array The source array.
  13345. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  13346. * `array`.
  13347. *
  13348. * Can be one of:
  13349. *
  13350. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  13351. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  13352. * will be returned. The predicate can be negated by prefixing the string with `!`.
  13353. *
  13354. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  13355. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  13356. * which have property `name` containing "M" and property `phone` containing "1". A special
  13357. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  13358. * property of the object. That's equivalent to the simple substring match with a `string`
  13359. * as described above. The predicate can be negated by prefixing the string with `!`.
  13360. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  13361. * not containing "M".
  13362. *
  13363. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  13364. * called for each element of `array`. The final result is an array of those elements that
  13365. * the predicate returned true for.
  13366. *
  13367. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  13368. * determining if the expected value (from the filter expression) and actual value (from
  13369. * the object in the array) should be considered a match.
  13370. *
  13371. * Can be one of:
  13372. *
  13373. * - `function(actual, expected)`:
  13374. * The function will be given the object value and the predicate value to compare and
  13375. * should return true if the item should be included in filtered result.
  13376. *
  13377. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13378. * this is essentially strict comparison of expected and actual.
  13379. *
  13380. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13381. * insensitive way.
  13382. *
  13383. * @example
  13384. <example>
  13385. <file name="index.html">
  13386. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13387. {name:'Mary', phone:'800-BIG-MARY'},
  13388. {name:'Mike', phone:'555-4321'},
  13389. {name:'Adam', phone:'555-5678'},
  13390. {name:'Julie', phone:'555-8765'},
  13391. {name:'Juliette', phone:'555-5678'}]"></div>
  13392. Search: <input ng-model="searchText">
  13393. <table id="searchTextResults">
  13394. <tr><th>Name</th><th>Phone</th></tr>
  13395. <tr ng-repeat="friend in friends | filter:searchText">
  13396. <td>{{friend.name}}</td>
  13397. <td>{{friend.phone}}</td>
  13398. </tr>
  13399. </table>
  13400. <hr>
  13401. Any: <input ng-model="search.$"> <br>
  13402. Name only <input ng-model="search.name"><br>
  13403. Phone only <input ng-model="search.phone"><br>
  13404. Equality <input type="checkbox" ng-model="strict"><br>
  13405. <table id="searchObjResults">
  13406. <tr><th>Name</th><th>Phone</th></tr>
  13407. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13408. <td>{{friendObj.name}}</td>
  13409. <td>{{friendObj.phone}}</td>
  13410. </tr>
  13411. </table>
  13412. </file>
  13413. <file name="protractor.js" type="protractor">
  13414. var expectFriendNames = function(expectedNames, key) {
  13415. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13416. arr.forEach(function(wd, i) {
  13417. expect(wd.getText()).toMatch(expectedNames[i]);
  13418. });
  13419. });
  13420. };
  13421. it('should search across all fields when filtering with a string', function() {
  13422. var searchText = element(by.model('searchText'));
  13423. searchText.clear();
  13424. searchText.sendKeys('m');
  13425. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13426. searchText.clear();
  13427. searchText.sendKeys('76');
  13428. expectFriendNames(['John', 'Julie'], 'friend');
  13429. });
  13430. it('should search in specific fields when filtering with a predicate object', function() {
  13431. var searchAny = element(by.model('search.$'));
  13432. searchAny.clear();
  13433. searchAny.sendKeys('i');
  13434. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13435. });
  13436. it('should use a equal comparison when comparator is true', function() {
  13437. var searchName = element(by.model('search.name'));
  13438. var strict = element(by.model('strict'));
  13439. searchName.clear();
  13440. searchName.sendKeys('Julie');
  13441. strict.click();
  13442. expectFriendNames(['Julie'], 'friendObj');
  13443. });
  13444. </file>
  13445. </example>
  13446. */
  13447. function filterFilter() {
  13448. return function(array, expression, comparator) {
  13449. if (!isArray(array)) return array;
  13450. var comparatorType = typeof(comparator),
  13451. predicates = [];
  13452. predicates.check = function(value) {
  13453. for (var j = 0; j < predicates.length; j++) {
  13454. if(!predicates[j](value)) {
  13455. return false;
  13456. }
  13457. }
  13458. return true;
  13459. };
  13460. if (comparatorType !== 'function') {
  13461. if (comparatorType === 'boolean' && comparator) {
  13462. comparator = function(obj, text) {
  13463. return angular.equals(obj, text);
  13464. };
  13465. } else {
  13466. comparator = function(obj, text) {
  13467. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13468. for (var objKey in obj) {
  13469. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13470. comparator(obj[objKey], text[objKey])) {
  13471. return true;
  13472. }
  13473. }
  13474. return false;
  13475. }
  13476. text = (''+text).toLowerCase();
  13477. return (''+obj).toLowerCase().indexOf(text) > -1;
  13478. };
  13479. }
  13480. }
  13481. var search = function(obj, text){
  13482. if (typeof text === 'string' && text.charAt(0) === '!') {
  13483. return !search(obj, text.substr(1));
  13484. }
  13485. switch (typeof obj) {
  13486. case 'boolean':
  13487. case 'number':
  13488. case 'string':
  13489. return comparator(obj, text);
  13490. case 'object':
  13491. switch (typeof text) {
  13492. case 'object':
  13493. return comparator(obj, text);
  13494. default:
  13495. for ( var objKey in obj) {
  13496. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13497. return true;
  13498. }
  13499. }
  13500. break;
  13501. }
  13502. return false;
  13503. case 'array':
  13504. for ( var i = 0; i < obj.length; i++) {
  13505. if (search(obj[i], text)) {
  13506. return true;
  13507. }
  13508. }
  13509. return false;
  13510. default:
  13511. return false;
  13512. }
  13513. };
  13514. switch (typeof expression) {
  13515. case 'boolean':
  13516. case 'number':
  13517. case 'string':
  13518. // Set up expression object and fall through
  13519. expression = {$:expression};
  13520. // jshint -W086
  13521. case 'object':
  13522. // jshint +W086
  13523. for (var key in expression) {
  13524. (function(path) {
  13525. if (typeof expression[path] === 'undefined') return;
  13526. predicates.push(function(value) {
  13527. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13528. });
  13529. })(key);
  13530. }
  13531. break;
  13532. case 'function':
  13533. predicates.push(expression);
  13534. break;
  13535. default:
  13536. return array;
  13537. }
  13538. var filtered = [];
  13539. for ( var j = 0; j < array.length; j++) {
  13540. var value = array[j];
  13541. if (predicates.check(value)) {
  13542. filtered.push(value);
  13543. }
  13544. }
  13545. return filtered;
  13546. };
  13547. }
  13548. /**
  13549. * @ngdoc filter
  13550. * @name currency
  13551. * @kind function
  13552. *
  13553. * @description
  13554. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13555. * symbol for current locale is used.
  13556. *
  13557. * @param {number} amount Input to filter.
  13558. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13559. * @returns {string} Formatted number.
  13560. *
  13561. *
  13562. * @example
  13563. <example module="currencyExample">
  13564. <file name="index.html">
  13565. <script>
  13566. angular.module('currencyExample', [])
  13567. .controller('ExampleController', ['$scope', function($scope) {
  13568. $scope.amount = 1234.56;
  13569. }]);
  13570. </script>
  13571. <div ng-controller="ExampleController">
  13572. <input type="number" ng-model="amount"> <br>
  13573. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13574. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13575. </div>
  13576. </file>
  13577. <file name="protractor.js" type="protractor">
  13578. it('should init with 1234.56', function() {
  13579. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13580. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13581. });
  13582. it('should update', function() {
  13583. if (browser.params.browser == 'safari') {
  13584. // Safari does not understand the minus key. See
  13585. // https://github.com/angular/protractor/issues/481
  13586. return;
  13587. }
  13588. element(by.model('amount')).clear();
  13589. element(by.model('amount')).sendKeys('-1234');
  13590. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13591. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13592. });
  13593. </file>
  13594. </example>
  13595. */
  13596. currencyFilter.$inject = ['$locale'];
  13597. function currencyFilter($locale) {
  13598. var formats = $locale.NUMBER_FORMATS;
  13599. return function(amount, currencySymbol){
  13600. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13601. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13602. replace(/\u00A4/g, currencySymbol);
  13603. };
  13604. }
  13605. /**
  13606. * @ngdoc filter
  13607. * @name number
  13608. * @kind function
  13609. *
  13610. * @description
  13611. * Formats a number as text.
  13612. *
  13613. * If the input is not a number an empty string is returned.
  13614. *
  13615. * @param {number|string} number Number to format.
  13616. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13617. * If this is not provided then the fraction size is computed from the current locale's number
  13618. * formatting pattern. In the case of the default locale, it will be 3.
  13619. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13620. *
  13621. * @example
  13622. <example module="numberFilterExample">
  13623. <file name="index.html">
  13624. <script>
  13625. angular.module('numberFilterExample', [])
  13626. .controller('ExampleController', ['$scope', function($scope) {
  13627. $scope.val = 1234.56789;
  13628. }]);
  13629. </script>
  13630. <div ng-controller="ExampleController">
  13631. Enter number: <input ng-model='val'><br>
  13632. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13633. No fractions: <span>{{val | number:0}}</span><br>
  13634. Negative number: <span>{{-val | number:4}}</span>
  13635. </div>
  13636. </file>
  13637. <file name="protractor.js" type="protractor">
  13638. it('should format numbers', function() {
  13639. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13640. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13641. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13642. });
  13643. it('should update', function() {
  13644. element(by.model('val')).clear();
  13645. element(by.model('val')).sendKeys('3374.333');
  13646. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13647. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13648. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13649. });
  13650. </file>
  13651. </example>
  13652. */
  13653. numberFilter.$inject = ['$locale'];
  13654. function numberFilter($locale) {
  13655. var formats = $locale.NUMBER_FORMATS;
  13656. return function(number, fractionSize) {
  13657. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13658. fractionSize);
  13659. };
  13660. }
  13661. var DECIMAL_SEP = '.';
  13662. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13663. if (number == null || !isFinite(number) || isObject(number)) return '';
  13664. var isNegative = number < 0;
  13665. number = Math.abs(number);
  13666. var numStr = number + '',
  13667. formatedText = '',
  13668. parts = [];
  13669. var hasExponent = false;
  13670. if (numStr.indexOf('e') !== -1) {
  13671. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13672. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13673. numStr = '0';
  13674. number = 0;
  13675. } else {
  13676. formatedText = numStr;
  13677. hasExponent = true;
  13678. }
  13679. }
  13680. if (!hasExponent) {
  13681. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13682. // determine fractionSize if it is not specified
  13683. if (isUndefined(fractionSize)) {
  13684. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13685. }
  13686. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  13687. // inspired by:
  13688. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  13689. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  13690. if (number === 0) {
  13691. isNegative = false;
  13692. }
  13693. var fraction = ('' + number).split(DECIMAL_SEP);
  13694. var whole = fraction[0];
  13695. fraction = fraction[1] || '';
  13696. var i, pos = 0,
  13697. lgroup = pattern.lgSize,
  13698. group = pattern.gSize;
  13699. if (whole.length >= (lgroup + group)) {
  13700. pos = whole.length - lgroup;
  13701. for (i = 0; i < pos; i++) {
  13702. if ((pos - i)%group === 0 && i !== 0) {
  13703. formatedText += groupSep;
  13704. }
  13705. formatedText += whole.charAt(i);
  13706. }
  13707. }
  13708. for (i = pos; i < whole.length; i++) {
  13709. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13710. formatedText += groupSep;
  13711. }
  13712. formatedText += whole.charAt(i);
  13713. }
  13714. // format fraction part.
  13715. while(fraction.length < fractionSize) {
  13716. fraction += '0';
  13717. }
  13718. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13719. } else {
  13720. if (fractionSize > 0 && number > -1 && number < 1) {
  13721. formatedText = number.toFixed(fractionSize);
  13722. }
  13723. }
  13724. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13725. parts.push(formatedText);
  13726. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13727. return parts.join('');
  13728. }
  13729. function padNumber(num, digits, trim) {
  13730. var neg = '';
  13731. if (num < 0) {
  13732. neg = '-';
  13733. num = -num;
  13734. }
  13735. num = '' + num;
  13736. while(num.length < digits) num = '0' + num;
  13737. if (trim)
  13738. num = num.substr(num.length - digits);
  13739. return neg + num;
  13740. }
  13741. function dateGetter(name, size, offset, trim) {
  13742. offset = offset || 0;
  13743. return function(date) {
  13744. var value = date['get' + name]();
  13745. if (offset > 0 || value > -offset)
  13746. value += offset;
  13747. if (value === 0 && offset == -12 ) value = 12;
  13748. return padNumber(value, size, trim);
  13749. };
  13750. }
  13751. function dateStrGetter(name, shortForm) {
  13752. return function(date, formats) {
  13753. var value = date['get' + name]();
  13754. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13755. return formats[get][value];
  13756. };
  13757. }
  13758. function timeZoneGetter(date) {
  13759. var zone = -1 * date.getTimezoneOffset();
  13760. var paddedZone = (zone >= 0) ? "+" : "";
  13761. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13762. padNumber(Math.abs(zone % 60), 2);
  13763. return paddedZone;
  13764. }
  13765. function ampmGetter(date, formats) {
  13766. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13767. }
  13768. var DATE_FORMATS = {
  13769. yyyy: dateGetter('FullYear', 4),
  13770. yy: dateGetter('FullYear', 2, 0, true),
  13771. y: dateGetter('FullYear', 1),
  13772. MMMM: dateStrGetter('Month'),
  13773. MMM: dateStrGetter('Month', true),
  13774. MM: dateGetter('Month', 2, 1),
  13775. M: dateGetter('Month', 1, 1),
  13776. dd: dateGetter('Date', 2),
  13777. d: dateGetter('Date', 1),
  13778. HH: dateGetter('Hours', 2),
  13779. H: dateGetter('Hours', 1),
  13780. hh: dateGetter('Hours', 2, -12),
  13781. h: dateGetter('Hours', 1, -12),
  13782. mm: dateGetter('Minutes', 2),
  13783. m: dateGetter('Minutes', 1),
  13784. ss: dateGetter('Seconds', 2),
  13785. s: dateGetter('Seconds', 1),
  13786. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13787. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13788. sss: dateGetter('Milliseconds', 3),
  13789. EEEE: dateStrGetter('Day'),
  13790. EEE: dateStrGetter('Day', true),
  13791. a: ampmGetter,
  13792. Z: timeZoneGetter
  13793. };
  13794. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13795. NUMBER_STRING = /^\-?\d+$/;
  13796. /**
  13797. * @ngdoc filter
  13798. * @name date
  13799. * @kind function
  13800. *
  13801. * @description
  13802. * Formats `date` to a string based on the requested `format`.
  13803. *
  13804. * `format` string can be composed of the following elements:
  13805. *
  13806. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13807. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13808. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13809. * * `'MMMM'`: Month in year (January-December)
  13810. * * `'MMM'`: Month in year (Jan-Dec)
  13811. * * `'MM'`: Month in year, padded (01-12)
  13812. * * `'M'`: Month in year (1-12)
  13813. * * `'dd'`: Day in month, padded (01-31)
  13814. * * `'d'`: Day in month (1-31)
  13815. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13816. * * `'EEE'`: Day in Week, (Sun-Sat)
  13817. * * `'HH'`: Hour in day, padded (00-23)
  13818. * * `'H'`: Hour in day (0-23)
  13819. * * `'hh'`: Hour in am/pm, padded (01-12)
  13820. * * `'h'`: Hour in am/pm, (1-12)
  13821. * * `'mm'`: Minute in hour, padded (00-59)
  13822. * * `'m'`: Minute in hour (0-59)
  13823. * * `'ss'`: Second in minute, padded (00-59)
  13824. * * `'s'`: Second in minute (0-59)
  13825. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13826. * * `'a'`: am/pm marker
  13827. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13828. *
  13829. * `format` string can also be one of the following predefined
  13830. * {@link guide/i18n localizable formats}:
  13831. *
  13832. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13833. * (e.g. Sep 3, 2010 12:05:08 pm)
  13834. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13835. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13836. * (e.g. Friday, September 3, 2010)
  13837. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13838. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13839. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13840. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13841. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13842. *
  13843. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  13844. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  13845. * (e.g. `"h 'o''clock'"`).
  13846. *
  13847. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13848. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  13849. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13850. * specified in the string input, the time is considered to be in the local timezone.
  13851. * @param {string=} format Formatting rules (see Description). If not specified,
  13852. * `mediumDate` is used.
  13853. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13854. *
  13855. * @example
  13856. <example>
  13857. <file name="index.html">
  13858. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13859. <span>{{1288323623006 | date:'medium'}}</span><br>
  13860. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13861. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13862. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13863. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13864. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  13865. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  13866. </file>
  13867. <file name="protractor.js" type="protractor">
  13868. it('should format date', function() {
  13869. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13870. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13871. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13872. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13873. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13874. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13875. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  13876. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  13877. });
  13878. </file>
  13879. </example>
  13880. */
  13881. dateFilter.$inject = ['$locale'];
  13882. function dateFilter($locale) {
  13883. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13884. // 1 2 3 4 5 6 7 8 9 10 11
  13885. function jsonStringToDate(string) {
  13886. var match;
  13887. if (match = string.match(R_ISO8601_STR)) {
  13888. var date = new Date(0),
  13889. tzHour = 0,
  13890. tzMin = 0,
  13891. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13892. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13893. if (match[9]) {
  13894. tzHour = int(match[9] + match[10]);
  13895. tzMin = int(match[9] + match[11]);
  13896. }
  13897. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13898. var h = int(match[4]||0) - tzHour;
  13899. var m = int(match[5]||0) - tzMin;
  13900. var s = int(match[6]||0);
  13901. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13902. timeSetter.call(date, h, m, s, ms);
  13903. return date;
  13904. }
  13905. return string;
  13906. }
  13907. return function(date, format) {
  13908. var text = '',
  13909. parts = [],
  13910. fn, match;
  13911. format = format || 'mediumDate';
  13912. format = $locale.DATETIME_FORMATS[format] || format;
  13913. if (isString(date)) {
  13914. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  13915. }
  13916. if (isNumber(date)) {
  13917. date = new Date(date);
  13918. }
  13919. if (!isDate(date)) {
  13920. return date;
  13921. }
  13922. while(format) {
  13923. match = DATE_FORMATS_SPLIT.exec(format);
  13924. if (match) {
  13925. parts = concat(parts, match, 1);
  13926. format = parts.pop();
  13927. } else {
  13928. parts.push(format);
  13929. format = null;
  13930. }
  13931. }
  13932. forEach(parts, function(value){
  13933. fn = DATE_FORMATS[value];
  13934. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13935. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13936. });
  13937. return text;
  13938. };
  13939. }
  13940. /**
  13941. * @ngdoc filter
  13942. * @name json
  13943. * @kind function
  13944. *
  13945. * @description
  13946. * Allows you to convert a JavaScript object into JSON string.
  13947. *
  13948. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13949. * the binding is automatically converted to JSON.
  13950. *
  13951. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13952. * @returns {string} JSON string.
  13953. *
  13954. *
  13955. * @example
  13956. <example>
  13957. <file name="index.html">
  13958. <pre>{{ {'name':'value'} | json }}</pre>
  13959. </file>
  13960. <file name="protractor.js" type="protractor">
  13961. it('should jsonify filtered objects', function() {
  13962. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  13963. });
  13964. </file>
  13965. </example>
  13966. *
  13967. */
  13968. function jsonFilter() {
  13969. return function(object) {
  13970. return toJson(object, true);
  13971. };
  13972. }
  13973. /**
  13974. * @ngdoc filter
  13975. * @name lowercase
  13976. * @kind function
  13977. * @description
  13978. * Converts string to lowercase.
  13979. * @see angular.lowercase
  13980. */
  13981. var lowercaseFilter = valueFn(lowercase);
  13982. /**
  13983. * @ngdoc filter
  13984. * @name uppercase
  13985. * @kind function
  13986. * @description
  13987. * Converts string to uppercase.
  13988. * @see angular.uppercase
  13989. */
  13990. var uppercaseFilter = valueFn(uppercase);
  13991. /**
  13992. * @ngdoc filter
  13993. * @name limitTo
  13994. * @kind function
  13995. *
  13996. * @description
  13997. * Creates a new array or string containing only a specified number of elements. The elements
  13998. * are taken from either the beginning or the end of the source array or string, as specified by
  13999. * the value and sign (positive or negative) of `limit`.
  14000. *
  14001. * @param {Array|string} input Source array or string to be limited.
  14002. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  14003. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  14004. * If the number is negative, `limit` number of items from the end of the source array/string
  14005. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  14006. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  14007. * had less than `limit` elements.
  14008. *
  14009. * @example
  14010. <example module="limitToExample">
  14011. <file name="index.html">
  14012. <script>
  14013. angular.module('limitToExample', [])
  14014. .controller('ExampleController', ['$scope', function($scope) {
  14015. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  14016. $scope.letters = "abcdefghi";
  14017. $scope.numLimit = 3;
  14018. $scope.letterLimit = 3;
  14019. }]);
  14020. </script>
  14021. <div ng-controller="ExampleController">
  14022. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  14023. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  14024. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  14025. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  14026. </div>
  14027. </file>
  14028. <file name="protractor.js" type="protractor">
  14029. var numLimitInput = element(by.model('numLimit'));
  14030. var letterLimitInput = element(by.model('letterLimit'));
  14031. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  14032. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  14033. it('should limit the number array to first three items', function() {
  14034. expect(numLimitInput.getAttribute('value')).toBe('3');
  14035. expect(letterLimitInput.getAttribute('value')).toBe('3');
  14036. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  14037. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  14038. });
  14039. // There is a bug in safari and protractor that doesn't like the minus key
  14040. // it('should update the output when -3 is entered', function() {
  14041. // numLimitInput.clear();
  14042. // numLimitInput.sendKeys('-3');
  14043. // letterLimitInput.clear();
  14044. // letterLimitInput.sendKeys('-3');
  14045. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  14046. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  14047. // });
  14048. it('should not exceed the maximum size of input array', function() {
  14049. numLimitInput.clear();
  14050. numLimitInput.sendKeys('100');
  14051. letterLimitInput.clear();
  14052. letterLimitInput.sendKeys('100');
  14053. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  14054. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  14055. });
  14056. </file>
  14057. </example>
  14058. */
  14059. function limitToFilter(){
  14060. return function(input, limit) {
  14061. if (!isArray(input) && !isString(input)) return input;
  14062. if (Math.abs(Number(limit)) === Infinity) {
  14063. limit = Number(limit);
  14064. } else {
  14065. limit = int(limit);
  14066. }
  14067. if (isString(input)) {
  14068. //NaN check on limit
  14069. if (limit) {
  14070. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  14071. } else {
  14072. return "";
  14073. }
  14074. }
  14075. var out = [],
  14076. i, n;
  14077. // if abs(limit) exceeds maximum length, trim it
  14078. if (limit > input.length)
  14079. limit = input.length;
  14080. else if (limit < -input.length)
  14081. limit = -input.length;
  14082. if (limit > 0) {
  14083. i = 0;
  14084. n = limit;
  14085. } else {
  14086. i = input.length + limit;
  14087. n = input.length;
  14088. }
  14089. for (; i<n; i++) {
  14090. out.push(input[i]);
  14091. }
  14092. return out;
  14093. };
  14094. }
  14095. /**
  14096. * @ngdoc filter
  14097. * @name orderBy
  14098. * @kind function
  14099. *
  14100. * @description
  14101. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  14102. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  14103. * correctly, make sure they are actually being saved as numbers and not strings.
  14104. *
  14105. * @param {Array} array The array to sort.
  14106. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  14107. * used by the comparator to determine the order of elements.
  14108. *
  14109. * Can be one of:
  14110. *
  14111. * - `function`: Getter function. The result of this function will be sorted using the
  14112. * `<`, `=`, `>` operator.
  14113. * - `string`: An Angular expression. The result of this expression is used to compare elements
  14114. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  14115. * 3 first characters of a property called `name`). The result of a constant expression
  14116. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  14117. * to sort object by the value of their `special name` property). An expression can be
  14118. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  14119. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  14120. * element itself is used to compare where sorting.
  14121. * - `Array`: An array of function or string predicates. The first predicate in the array
  14122. * is used for sorting, but when two items are equivalent, the next predicate is used.
  14123. *
  14124. * If the predicate is missing or empty then it defaults to `'+'`.
  14125. *
  14126. * @param {boolean=} reverse Reverse the order of the array.
  14127. * @returns {Array} Sorted copy of the source array.
  14128. *
  14129. * @example
  14130. <example module="orderByExample">
  14131. <file name="index.html">
  14132. <script>
  14133. angular.module('orderByExample', [])
  14134. .controller('ExampleController', ['$scope', function($scope) {
  14135. $scope.friends =
  14136. [{name:'John', phone:'555-1212', age:10},
  14137. {name:'Mary', phone:'555-9876', age:19},
  14138. {name:'Mike', phone:'555-4321', age:21},
  14139. {name:'Adam', phone:'555-5678', age:35},
  14140. {name:'Julie', phone:'555-8765', age:29}];
  14141. $scope.predicate = '-age';
  14142. }]);
  14143. </script>
  14144. <div ng-controller="ExampleController">
  14145. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  14146. <hr/>
  14147. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  14148. <table class="friend">
  14149. <tr>
  14150. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  14151. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  14152. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  14153. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  14154. </tr>
  14155. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  14156. <td>{{friend.name}}</td>
  14157. <td>{{friend.phone}}</td>
  14158. <td>{{friend.age}}</td>
  14159. </tr>
  14160. </table>
  14161. </div>
  14162. </file>
  14163. </example>
  14164. *
  14165. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  14166. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  14167. * desired parameters.
  14168. *
  14169. * Example:
  14170. *
  14171. * @example
  14172. <example module="orderByExample">
  14173. <file name="index.html">
  14174. <div ng-controller="ExampleController">
  14175. <table class="friend">
  14176. <tr>
  14177. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  14178. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  14179. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  14180. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  14181. </tr>
  14182. <tr ng-repeat="friend in friends">
  14183. <td>{{friend.name}}</td>
  14184. <td>{{friend.phone}}</td>
  14185. <td>{{friend.age}}</td>
  14186. </tr>
  14187. </table>
  14188. </div>
  14189. </file>
  14190. <file name="script.js">
  14191. angular.module('orderByExample', [])
  14192. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  14193. var orderBy = $filter('orderBy');
  14194. $scope.friends = [
  14195. { name: 'John', phone: '555-1212', age: 10 },
  14196. { name: 'Mary', phone: '555-9876', age: 19 },
  14197. { name: 'Mike', phone: '555-4321', age: 21 },
  14198. { name: 'Adam', phone: '555-5678', age: 35 },
  14199. { name: 'Julie', phone: '555-8765', age: 29 }
  14200. ];
  14201. $scope.order = function(predicate, reverse) {
  14202. $scope.friends = orderBy($scope.friends, predicate, reverse);
  14203. };
  14204. $scope.order('-age',false);
  14205. }]);
  14206. </file>
  14207. </example>
  14208. */
  14209. orderByFilter.$inject = ['$parse'];
  14210. function orderByFilter($parse){
  14211. return function(array, sortPredicate, reverseOrder) {
  14212. if (!(isArrayLike(array))) return array;
  14213. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  14214. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  14215. sortPredicate = map(sortPredicate, function(predicate){
  14216. var descending = false, get = predicate || identity;
  14217. if (isString(predicate)) {
  14218. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  14219. descending = predicate.charAt(0) == '-';
  14220. predicate = predicate.substring(1);
  14221. }
  14222. if ( predicate === '' ) {
  14223. // Effectively no predicate was passed so we compare identity
  14224. return reverseComparator(function(a,b) {
  14225. return compare(a, b);
  14226. }, descending);
  14227. }
  14228. get = $parse(predicate);
  14229. if (get.constant) {
  14230. var key = get();
  14231. return reverseComparator(function(a,b) {
  14232. return compare(a[key], b[key]);
  14233. }, descending);
  14234. }
  14235. }
  14236. return reverseComparator(function(a,b){
  14237. return compare(get(a),get(b));
  14238. }, descending);
  14239. });
  14240. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  14241. function comparator(o1, o2){
  14242. for ( var i = 0; i < sortPredicate.length; i++) {
  14243. var comp = sortPredicate[i](o1, o2);
  14244. if (comp !== 0) return comp;
  14245. }
  14246. return 0;
  14247. }
  14248. function reverseComparator(comp, descending) {
  14249. return toBoolean(descending)
  14250. ? function(a,b){return comp(b,a);}
  14251. : comp;
  14252. }
  14253. function compare(v1, v2){
  14254. var t1 = typeof v1;
  14255. var t2 = typeof v2;
  14256. if (t1 == t2) {
  14257. if (isDate(v1) && isDate(v2)) {
  14258. v1 = v1.valueOf();
  14259. v2 = v2.valueOf();
  14260. }
  14261. if (t1 == "string") {
  14262. v1 = v1.toLowerCase();
  14263. v2 = v2.toLowerCase();
  14264. }
  14265. if (v1 === v2) return 0;
  14266. return v1 < v2 ? -1 : 1;
  14267. } else {
  14268. return t1 < t2 ? -1 : 1;
  14269. }
  14270. }
  14271. };
  14272. }
  14273. function ngDirective(directive) {
  14274. if (isFunction(directive)) {
  14275. directive = {
  14276. link: directive
  14277. };
  14278. }
  14279. directive.restrict = directive.restrict || 'AC';
  14280. return valueFn(directive);
  14281. }
  14282. /**
  14283. * @ngdoc directive
  14284. * @name a
  14285. * @restrict E
  14286. *
  14287. * @description
  14288. * Modifies the default behavior of the html A tag so that the default action is prevented when
  14289. * the href attribute is empty.
  14290. *
  14291. * This change permits the easy creation of action links with the `ngClick` directive
  14292. * without changing the location or causing page reloads, e.g.:
  14293. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  14294. */
  14295. var htmlAnchorDirective = valueFn({
  14296. restrict: 'E',
  14297. compile: function(element, attr) {
  14298. if (msie <= 8) {
  14299. // turn <a href ng-click="..">link</a> into a stylable link in IE
  14300. // but only if it doesn't have name attribute, in which case it's an anchor
  14301. if (!attr.href && !attr.name) {
  14302. attr.$set('href', '');
  14303. }
  14304. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  14305. // to new attribute content if attribute is updated with value containing @ and element also
  14306. // contains value with @
  14307. // see issue #1949
  14308. element.append(document.createComment('IE fix'));
  14309. }
  14310. if (!attr.href && !attr.xlinkHref && !attr.name) {
  14311. return function(scope, element) {
  14312. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  14313. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  14314. 'xlink:href' : 'href';
  14315. element.on('click', function(event){
  14316. // if we have no href url, then don't navigate anywhere.
  14317. if (!element.attr(href)) {
  14318. event.preventDefault();
  14319. }
  14320. });
  14321. };
  14322. }
  14323. }
  14324. });
  14325. /**
  14326. * @ngdoc directive
  14327. * @name ngHref
  14328. * @restrict A
  14329. * @priority 99
  14330. *
  14331. * @description
  14332. * Using Angular markup like `{{hash}}` in an href attribute will
  14333. * make the link go to the wrong URL if the user clicks it before
  14334. * Angular has a chance to replace the `{{hash}}` markup with its
  14335. * value. Until Angular replaces the markup the link will be broken
  14336. * and will most likely return a 404 error.
  14337. *
  14338. * The `ngHref` directive solves this problem.
  14339. *
  14340. * The wrong way to write it:
  14341. * ```html
  14342. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  14343. * ```
  14344. *
  14345. * The correct way to write it:
  14346. * ```html
  14347. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  14348. * ```
  14349. *
  14350. * @element A
  14351. * @param {template} ngHref any string which can contain `{{}}` markup.
  14352. *
  14353. * @example
  14354. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  14355. * in links and their different behaviors:
  14356. <example>
  14357. <file name="index.html">
  14358. <input ng-model="value" /><br />
  14359. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  14360. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  14361. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  14362. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  14363. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  14364. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  14365. </file>
  14366. <file name="protractor.js" type="protractor">
  14367. it('should execute ng-click but not reload when href without value', function() {
  14368. element(by.id('link-1')).click();
  14369. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  14370. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  14371. });
  14372. it('should execute ng-click but not reload when href empty string', function() {
  14373. element(by.id('link-2')).click();
  14374. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  14375. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  14376. });
  14377. it('should execute ng-click and change url when ng-href specified', function() {
  14378. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  14379. element(by.id('link-3')).click();
  14380. // At this point, we navigate away from an Angular page, so we need
  14381. // to use browser.driver to get the base webdriver.
  14382. browser.wait(function() {
  14383. return browser.driver.getCurrentUrl().then(function(url) {
  14384. return url.match(/\/123$/);
  14385. });
  14386. }, 5000, 'page should navigate to /123');
  14387. });
  14388. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  14389. element(by.id('link-4')).click();
  14390. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  14391. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  14392. });
  14393. it('should execute ng-click but not reload when no href but name specified', function() {
  14394. element(by.id('link-5')).click();
  14395. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  14396. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  14397. });
  14398. it('should only change url when only ng-href', function() {
  14399. element(by.model('value')).clear();
  14400. element(by.model('value')).sendKeys('6');
  14401. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  14402. element(by.id('link-6')).click();
  14403. // At this point, we navigate away from an Angular page, so we need
  14404. // to use browser.driver to get the base webdriver.
  14405. browser.wait(function() {
  14406. return browser.driver.getCurrentUrl().then(function(url) {
  14407. return url.match(/\/6$/);
  14408. });
  14409. }, 5000, 'page should navigate to /6');
  14410. });
  14411. </file>
  14412. </example>
  14413. */
  14414. /**
  14415. * @ngdoc directive
  14416. * @name ngSrc
  14417. * @restrict A
  14418. * @priority 99
  14419. *
  14420. * @description
  14421. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  14422. * work right: The browser will fetch from the URL with the literal
  14423. * text `{{hash}}` until Angular replaces the expression inside
  14424. * `{{hash}}`. The `ngSrc` directive solves this problem.
  14425. *
  14426. * The buggy way to write it:
  14427. * ```html
  14428. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  14429. * ```
  14430. *
  14431. * The correct way to write it:
  14432. * ```html
  14433. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  14434. * ```
  14435. *
  14436. * @element IMG
  14437. * @param {template} ngSrc any string which can contain `{{}}` markup.
  14438. */
  14439. /**
  14440. * @ngdoc directive
  14441. * @name ngSrcset
  14442. * @restrict A
  14443. * @priority 99
  14444. *
  14445. * @description
  14446. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14447. * work right: The browser will fetch from the URL with the literal
  14448. * text `{{hash}}` until Angular replaces the expression inside
  14449. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14450. *
  14451. * The buggy way to write it:
  14452. * ```html
  14453. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14454. * ```
  14455. *
  14456. * The correct way to write it:
  14457. * ```html
  14458. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14459. * ```
  14460. *
  14461. * @element IMG
  14462. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14463. */
  14464. /**
  14465. * @ngdoc directive
  14466. * @name ngDisabled
  14467. * @restrict A
  14468. * @priority 100
  14469. *
  14470. * @description
  14471. *
  14472. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14473. * ```html
  14474. * <div ng-init="scope = { isDisabled: false }">
  14475. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14476. * </div>
  14477. * ```
  14478. *
  14479. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14480. * such as disabled. (Their presence means true and their absence means false.)
  14481. * If we put an Angular interpolation expression into such an attribute then the
  14482. * binding information would be lost when the browser removes the attribute.
  14483. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14484. * This complementary directive is not removed by the browser and so provides
  14485. * a permanent reliable place to store the binding information.
  14486. *
  14487. * @example
  14488. <example>
  14489. <file name="index.html">
  14490. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14491. <button ng-model="button" ng-disabled="checked">Button</button>
  14492. </file>
  14493. <file name="protractor.js" type="protractor">
  14494. it('should toggle button', function() {
  14495. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14496. element(by.model('checked')).click();
  14497. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14498. });
  14499. </file>
  14500. </example>
  14501. *
  14502. * @element INPUT
  14503. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14504. * then special attribute "disabled" will be set on the element
  14505. */
  14506. /**
  14507. * @ngdoc directive
  14508. * @name ngChecked
  14509. * @restrict A
  14510. * @priority 100
  14511. *
  14512. * @description
  14513. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14514. * such as checked. (Their presence means true and their absence means false.)
  14515. * If we put an Angular interpolation expression into such an attribute then the
  14516. * binding information would be lost when the browser removes the attribute.
  14517. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14518. * This complementary directive is not removed by the browser and so provides
  14519. * a permanent reliable place to store the binding information.
  14520. * @example
  14521. <example>
  14522. <file name="index.html">
  14523. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14524. <input id="checkSlave" type="checkbox" ng-checked="master">
  14525. </file>
  14526. <file name="protractor.js" type="protractor">
  14527. it('should check both checkBoxes', function() {
  14528. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14529. element(by.model('master')).click();
  14530. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14531. });
  14532. </file>
  14533. </example>
  14534. *
  14535. * @element INPUT
  14536. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14537. * then special attribute "checked" will be set on the element
  14538. */
  14539. /**
  14540. * @ngdoc directive
  14541. * @name ngReadonly
  14542. * @restrict A
  14543. * @priority 100
  14544. *
  14545. * @description
  14546. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14547. * such as readonly. (Their presence means true and their absence means false.)
  14548. * If we put an Angular interpolation expression into such an attribute then the
  14549. * binding information would be lost when the browser removes the attribute.
  14550. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14551. * This complementary directive is not removed by the browser and so provides
  14552. * a permanent reliable place to store the binding information.
  14553. * @example
  14554. <example>
  14555. <file name="index.html">
  14556. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14557. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14558. </file>
  14559. <file name="protractor.js" type="protractor">
  14560. it('should toggle readonly attr', function() {
  14561. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14562. element(by.model('checked')).click();
  14563. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14564. });
  14565. </file>
  14566. </example>
  14567. *
  14568. * @element INPUT
  14569. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14570. * then special attribute "readonly" will be set on the element
  14571. */
  14572. /**
  14573. * @ngdoc directive
  14574. * @name ngSelected
  14575. * @restrict A
  14576. * @priority 100
  14577. *
  14578. * @description
  14579. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14580. * such as selected. (Their presence means true and their absence means false.)
  14581. * If we put an Angular interpolation expression into such an attribute then the
  14582. * binding information would be lost when the browser removes the attribute.
  14583. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14584. * This complementary directive is not removed by the browser and so provides
  14585. * a permanent reliable place to store the binding information.
  14586. *
  14587. * @example
  14588. <example>
  14589. <file name="index.html">
  14590. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14591. <select>
  14592. <option>Hello!</option>
  14593. <option id="greet" ng-selected="selected">Greetings!</option>
  14594. </select>
  14595. </file>
  14596. <file name="protractor.js" type="protractor">
  14597. it('should select Greetings!', function() {
  14598. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14599. element(by.model('selected')).click();
  14600. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14601. });
  14602. </file>
  14603. </example>
  14604. *
  14605. * @element OPTION
  14606. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14607. * then special attribute "selected" will be set on the element
  14608. */
  14609. /**
  14610. * @ngdoc directive
  14611. * @name ngOpen
  14612. * @restrict A
  14613. * @priority 100
  14614. *
  14615. * @description
  14616. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14617. * such as open. (Their presence means true and their absence means false.)
  14618. * If we put an Angular interpolation expression into such an attribute then the
  14619. * binding information would be lost when the browser removes the attribute.
  14620. * The `ngOpen` directive solves this problem for the `open` attribute.
  14621. * This complementary directive is not removed by the browser and so provides
  14622. * a permanent reliable place to store the binding information.
  14623. * @example
  14624. <example>
  14625. <file name="index.html">
  14626. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14627. <details id="details" ng-open="open">
  14628. <summary>Show/Hide me</summary>
  14629. </details>
  14630. </file>
  14631. <file name="protractor.js" type="protractor">
  14632. it('should toggle open', function() {
  14633. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14634. element(by.model('open')).click();
  14635. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14636. });
  14637. </file>
  14638. </example>
  14639. *
  14640. * @element DETAILS
  14641. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14642. * then special attribute "open" will be set on the element
  14643. */
  14644. var ngAttributeAliasDirectives = {};
  14645. // boolean attrs are evaluated
  14646. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14647. // binding to multiple is not supported
  14648. if (propName == "multiple") return;
  14649. var normalized = directiveNormalize('ng-' + attrName);
  14650. ngAttributeAliasDirectives[normalized] = function() {
  14651. return {
  14652. priority: 100,
  14653. link: function(scope, element, attr) {
  14654. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14655. attr.$set(attrName, !!value);
  14656. });
  14657. }
  14658. };
  14659. };
  14660. });
  14661. // ng-src, ng-srcset, ng-href are interpolated
  14662. forEach(['src', 'srcset', 'href'], function(attrName) {
  14663. var normalized = directiveNormalize('ng-' + attrName);
  14664. ngAttributeAliasDirectives[normalized] = function() {
  14665. return {
  14666. priority: 99, // it needs to run after the attributes are interpolated
  14667. link: function(scope, element, attr) {
  14668. var propName = attrName,
  14669. name = attrName;
  14670. if (attrName === 'href' &&
  14671. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14672. name = 'xlinkHref';
  14673. attr.$attr[name] = 'xlink:href';
  14674. propName = null;
  14675. }
  14676. attr.$observe(normalized, function(value) {
  14677. if (!value) {
  14678. if (attrName === 'href') {
  14679. attr.$set(name, null);
  14680. }
  14681. return;
  14682. }
  14683. attr.$set(name, value);
  14684. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14685. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14686. // to set the property as well to achieve the desired effect.
  14687. // we use attr[attrName] value since $set can sanitize the url.
  14688. if (msie && propName) element.prop(propName, attr[name]);
  14689. });
  14690. }
  14691. };
  14692. };
  14693. });
  14694. /* global -nullFormCtrl */
  14695. var nullFormCtrl = {
  14696. $addControl: noop,
  14697. $removeControl: noop,
  14698. $setValidity: noop,
  14699. $setDirty: noop,
  14700. $setPristine: noop
  14701. };
  14702. /**
  14703. * @ngdoc type
  14704. * @name form.FormController
  14705. *
  14706. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14707. * @property {boolean} $dirty True if user has already interacted with the form.
  14708. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14709. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14710. *
  14711. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14712. * forms, where:
  14713. *
  14714. * - keys are validation tokens (error names),
  14715. * - values are arrays of controls or forms that are invalid for given error name.
  14716. *
  14717. *
  14718. * Built-in validation tokens:
  14719. *
  14720. * - `email`
  14721. * - `max`
  14722. * - `maxlength`
  14723. * - `min`
  14724. * - `minlength`
  14725. * - `number`
  14726. * - `pattern`
  14727. * - `required`
  14728. * - `url`
  14729. *
  14730. * @description
  14731. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  14732. * such as being valid/invalid or dirty/pristine.
  14733. *
  14734. * Each {@link ng.directive:form form} directive creates an instance
  14735. * of `FormController`.
  14736. *
  14737. */
  14738. //asks for $scope to fool the BC controller module
  14739. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14740. function FormController(element, attrs, $scope, $animate) {
  14741. var form = this,
  14742. parentForm = element.parent().controller('form') || nullFormCtrl,
  14743. invalidCount = 0, // used to easily determine if we are valid
  14744. errors = form.$error = {},
  14745. controls = [];
  14746. // init state
  14747. form.$name = attrs.name || attrs.ngForm;
  14748. form.$dirty = false;
  14749. form.$pristine = true;
  14750. form.$valid = true;
  14751. form.$invalid = false;
  14752. parentForm.$addControl(form);
  14753. // Setup initial state of the control
  14754. element.addClass(PRISTINE_CLASS);
  14755. toggleValidCss(true);
  14756. // convenience method for easy toggling of classes
  14757. function toggleValidCss(isValid, validationErrorKey) {
  14758. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14759. $animate.setClass(element,
  14760. (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey,
  14761. (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14762. }
  14763. /**
  14764. * @ngdoc method
  14765. * @name form.FormController#$addControl
  14766. *
  14767. * @description
  14768. * Register a control with the form.
  14769. *
  14770. * Input elements using ngModelController do this automatically when they are linked.
  14771. */
  14772. form.$addControl = function(control) {
  14773. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14774. // and not added to the scope. Now we throw an error.
  14775. assertNotHasOwnProperty(control.$name, 'input');
  14776. controls.push(control);
  14777. if (control.$name) {
  14778. form[control.$name] = control;
  14779. }
  14780. };
  14781. /**
  14782. * @ngdoc method
  14783. * @name form.FormController#$removeControl
  14784. *
  14785. * @description
  14786. * Deregister a control from the form.
  14787. *
  14788. * Input elements using ngModelController do this automatically when they are destroyed.
  14789. */
  14790. form.$removeControl = function(control) {
  14791. if (control.$name && form[control.$name] === control) {
  14792. delete form[control.$name];
  14793. }
  14794. forEach(errors, function(queue, validationToken) {
  14795. form.$setValidity(validationToken, true, control);
  14796. });
  14797. arrayRemove(controls, control);
  14798. };
  14799. /**
  14800. * @ngdoc method
  14801. * @name form.FormController#$setValidity
  14802. *
  14803. * @description
  14804. * Sets the validity of a form control.
  14805. *
  14806. * This method will also propagate to parent forms.
  14807. */
  14808. form.$setValidity = function(validationToken, isValid, control) {
  14809. var queue = errors[validationToken];
  14810. if (isValid) {
  14811. if (queue) {
  14812. arrayRemove(queue, control);
  14813. if (!queue.length) {
  14814. invalidCount--;
  14815. if (!invalidCount) {
  14816. toggleValidCss(isValid);
  14817. form.$valid = true;
  14818. form.$invalid = false;
  14819. }
  14820. errors[validationToken] = false;
  14821. toggleValidCss(true, validationToken);
  14822. parentForm.$setValidity(validationToken, true, form);
  14823. }
  14824. }
  14825. } else {
  14826. if (!invalidCount) {
  14827. toggleValidCss(isValid);
  14828. }
  14829. if (queue) {
  14830. if (includes(queue, control)) return;
  14831. } else {
  14832. errors[validationToken] = queue = [];
  14833. invalidCount++;
  14834. toggleValidCss(false, validationToken);
  14835. parentForm.$setValidity(validationToken, false, form);
  14836. }
  14837. queue.push(control);
  14838. form.$valid = false;
  14839. form.$invalid = true;
  14840. }
  14841. };
  14842. /**
  14843. * @ngdoc method
  14844. * @name form.FormController#$setDirty
  14845. *
  14846. * @description
  14847. * Sets the form to a dirty state.
  14848. *
  14849. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14850. * state (ng-dirty class). This method will also propagate to parent forms.
  14851. */
  14852. form.$setDirty = function() {
  14853. $animate.removeClass(element, PRISTINE_CLASS);
  14854. $animate.addClass(element, DIRTY_CLASS);
  14855. form.$dirty = true;
  14856. form.$pristine = false;
  14857. parentForm.$setDirty();
  14858. };
  14859. /**
  14860. * @ngdoc method
  14861. * @name form.FormController#$setPristine
  14862. *
  14863. * @description
  14864. * Sets the form to its pristine state.
  14865. *
  14866. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14867. * state (ng-pristine class). This method will also propagate to all the controls contained
  14868. * in this form.
  14869. *
  14870. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14871. * saving or resetting it.
  14872. */
  14873. form.$setPristine = function () {
  14874. $animate.removeClass(element, DIRTY_CLASS);
  14875. $animate.addClass(element, PRISTINE_CLASS);
  14876. form.$dirty = false;
  14877. form.$pristine = true;
  14878. forEach(controls, function(control) {
  14879. control.$setPristine();
  14880. });
  14881. };
  14882. }
  14883. /**
  14884. * @ngdoc directive
  14885. * @name ngForm
  14886. * @restrict EAC
  14887. *
  14888. * @description
  14889. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14890. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14891. * sub-group of controls needs to be determined.
  14892. *
  14893. * Note: the purpose of `ngForm` is to group controls,
  14894. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14895. * (e.g. posting to the server, ...).
  14896. *
  14897. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14898. * related scope, under this name.
  14899. *
  14900. */
  14901. /**
  14902. * @ngdoc directive
  14903. * @name form
  14904. * @restrict E
  14905. *
  14906. * @description
  14907. * Directive that instantiates
  14908. * {@link form.FormController FormController}.
  14909. *
  14910. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14911. * this name.
  14912. *
  14913. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14914. *
  14915. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14916. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14917. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14918. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14919. * using Angular validation directives in forms that are dynamically generated using the
  14920. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14921. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14922. * `ngForm` directive and nest these in an outer `form` element.
  14923. *
  14924. *
  14925. * # CSS classes
  14926. * - `ng-valid` is set if the form is valid.
  14927. * - `ng-invalid` is set if the form is invalid.
  14928. * - `ng-pristine` is set if the form is pristine.
  14929. * - `ng-dirty` is set if the form is dirty.
  14930. *
  14931. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14932. *
  14933. *
  14934. * # Submitting a form and preventing the default action
  14935. *
  14936. * Since the role of forms in client-side Angular applications is different than in classical
  14937. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14938. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14939. * to handle the form submission in an application-specific way.
  14940. *
  14941. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14942. * `<form>` element has an `action` attribute specified.
  14943. *
  14944. * You can use one of the following two ways to specify what javascript method should be called when
  14945. * a form is submitted:
  14946. *
  14947. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14948. * - {@link ng.directive:ngClick ngClick} directive on the first
  14949. * button or input field of type submit (input[type=submit])
  14950. *
  14951. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14952. * or {@link ng.directive:ngClick ngClick} directives.
  14953. * This is because of the following form submission rules in the HTML specification:
  14954. *
  14955. * - If a form has only one input field then hitting enter in this field triggers form submit
  14956. * (`ngSubmit`)
  14957. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14958. * doesn't trigger submit
  14959. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14960. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14961. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14962. *
  14963. *
  14964. * ## Animation Hooks
  14965. *
  14966. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  14967. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  14968. * other validations that are performed within the form. Animations in ngForm are similar to how
  14969. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  14970. * as JS animations.
  14971. *
  14972. * The following example shows a simple way to utilize CSS transitions to style a form element
  14973. * that has been rendered as invalid after it has been validated:
  14974. *
  14975. * <pre>
  14976. * //be sure to include ngAnimate as a module to hook into more
  14977. * //advanced animations
  14978. * .my-form {
  14979. * transition:0.5s linear all;
  14980. * background: white;
  14981. * }
  14982. * .my-form.ng-invalid {
  14983. * background: red;
  14984. * color:white;
  14985. * }
  14986. * </pre>
  14987. *
  14988. * @example
  14989. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  14990. <file name="index.html">
  14991. <script>
  14992. angular.module('formExample', [])
  14993. .controller('FormController', ['$scope', function($scope) {
  14994. $scope.userType = 'guest';
  14995. }]);
  14996. </script>
  14997. <style>
  14998. .my-form {
  14999. -webkit-transition:all linear 0.5s;
  15000. transition:all linear 0.5s;
  15001. background: transparent;
  15002. }
  15003. .my-form.ng-invalid {
  15004. background: red;
  15005. }
  15006. </style>
  15007. <form name="myForm" ng-controller="FormController" class="my-form">
  15008. userType: <input name="input" ng-model="userType" required>
  15009. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  15010. <tt>userType = {{userType}}</tt><br>
  15011. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  15012. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  15013. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15014. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15015. </form>
  15016. </file>
  15017. <file name="protractor.js" type="protractor">
  15018. it('should initialize to model', function() {
  15019. var userType = element(by.binding('userType'));
  15020. var valid = element(by.binding('myForm.input.$valid'));
  15021. expect(userType.getText()).toContain('guest');
  15022. expect(valid.getText()).toContain('true');
  15023. });
  15024. it('should be invalid if empty', function() {
  15025. var userType = element(by.binding('userType'));
  15026. var valid = element(by.binding('myForm.input.$valid'));
  15027. var userInput = element(by.model('userType'));
  15028. userInput.clear();
  15029. userInput.sendKeys('');
  15030. expect(userType.getText()).toEqual('userType =');
  15031. expect(valid.getText()).toContain('false');
  15032. });
  15033. </file>
  15034. </example>
  15035. *
  15036. * @param {string=} name Name of the form. If specified, the form controller will be published into
  15037. * related scope, under this name.
  15038. */
  15039. var formDirectiveFactory = function(isNgForm) {
  15040. return ['$timeout', function($timeout) {
  15041. var formDirective = {
  15042. name: 'form',
  15043. restrict: isNgForm ? 'EAC' : 'E',
  15044. controller: FormController,
  15045. compile: function() {
  15046. return {
  15047. pre: function(scope, formElement, attr, controller) {
  15048. if (!attr.action) {
  15049. // we can't use jq events because if a form is destroyed during submission the default
  15050. // action is not prevented. see #1238
  15051. //
  15052. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  15053. // page reload if the form was destroyed by submission of the form via a click handler
  15054. // on a button in the form. Looks like an IE9 specific bug.
  15055. var preventDefaultListener = function(event) {
  15056. event.preventDefault
  15057. ? event.preventDefault()
  15058. : event.returnValue = false; // IE
  15059. };
  15060. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15061. // unregister the preventDefault listener so that we don't not leak memory but in a
  15062. // way that will achieve the prevention of the default action.
  15063. formElement.on('$destroy', function() {
  15064. $timeout(function() {
  15065. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  15066. }, 0, false);
  15067. });
  15068. }
  15069. var parentFormCtrl = formElement.parent().controller('form'),
  15070. alias = attr.name || attr.ngForm;
  15071. if (alias) {
  15072. setter(scope, alias, controller, alias);
  15073. }
  15074. if (parentFormCtrl) {
  15075. formElement.on('$destroy', function() {
  15076. parentFormCtrl.$removeControl(controller);
  15077. if (alias) {
  15078. setter(scope, alias, undefined, alias);
  15079. }
  15080. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  15081. });
  15082. }
  15083. }
  15084. };
  15085. }
  15086. };
  15087. return formDirective;
  15088. }];
  15089. };
  15090. var formDirective = formDirectiveFactory();
  15091. var ngFormDirective = formDirectiveFactory(true);
  15092. /* global VALID_CLASS: true,
  15093. INVALID_CLASS: true,
  15094. PRISTINE_CLASS: true,
  15095. DIRTY_CLASS: true
  15096. */
  15097. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  15098. 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;
  15099. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  15100. var inputType = {
  15101. /**
  15102. * @ngdoc input
  15103. * @name input[text]
  15104. *
  15105. * @description
  15106. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  15107. *
  15108. * *NOTE* Not every feature offered is available for all input types.
  15109. *
  15110. * @param {string} ngModel Assignable angular expression to data-bind to.
  15111. * @param {string=} name Property name of the form under which the control is published.
  15112. * @param {string=} required Adds `required` validation error key if the value is not entered.
  15113. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15114. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15115. * `required` when you want to data-bind to the `required` attribute.
  15116. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15117. * minlength.
  15118. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15119. * maxlength.
  15120. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15121. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15122. * patterns defined as scope expressions.
  15123. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15124. * interaction with the input element.
  15125. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15126. * This parameter is ignored for input[type=password] controls, which will never trim the
  15127. * input.
  15128. *
  15129. * @example
  15130. <example name="text-input-directive" module="textInputExample">
  15131. <file name="index.html">
  15132. <script>
  15133. angular.module('textInputExample', [])
  15134. .controller('ExampleController', ['$scope', function($scope) {
  15135. $scope.text = 'guest';
  15136. $scope.word = /^\s*\w*\s*$/;
  15137. }]);
  15138. </script>
  15139. <form name="myForm" ng-controller="ExampleController">
  15140. Single word: <input type="text" name="input" ng-model="text"
  15141. ng-pattern="word" required ng-trim="false">
  15142. <span class="error" ng-show="myForm.input.$error.required">
  15143. Required!</span>
  15144. <span class="error" ng-show="myForm.input.$error.pattern">
  15145. Single word only!</span>
  15146. <tt>text = {{text}}</tt><br/>
  15147. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15148. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15149. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15150. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15151. </form>
  15152. </file>
  15153. <file name="protractor.js" type="protractor">
  15154. var text = element(by.binding('text'));
  15155. var valid = element(by.binding('myForm.input.$valid'));
  15156. var input = element(by.model('text'));
  15157. it('should initialize to model', function() {
  15158. expect(text.getText()).toContain('guest');
  15159. expect(valid.getText()).toContain('true');
  15160. });
  15161. it('should be invalid if empty', function() {
  15162. input.clear();
  15163. input.sendKeys('');
  15164. expect(text.getText()).toEqual('text =');
  15165. expect(valid.getText()).toContain('false');
  15166. });
  15167. it('should be invalid if multi word', function() {
  15168. input.clear();
  15169. input.sendKeys('hello world');
  15170. expect(valid.getText()).toContain('false');
  15171. });
  15172. </file>
  15173. </example>
  15174. */
  15175. 'text': textInputType,
  15176. /**
  15177. * @ngdoc input
  15178. * @name input[number]
  15179. *
  15180. * @description
  15181. * Text input with number validation and transformation. Sets the `number` validation
  15182. * error if not a valid number.
  15183. *
  15184. * @param {string} ngModel Assignable angular expression to data-bind to.
  15185. * @param {string=} name Property name of the form under which the control is published.
  15186. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  15187. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  15188. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15189. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15190. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15191. * `required` when you want to data-bind to the `required` attribute.
  15192. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15193. * minlength.
  15194. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15195. * maxlength.
  15196. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15197. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15198. * patterns defined as scope expressions.
  15199. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15200. * interaction with the input element.
  15201. *
  15202. * @example
  15203. <example name="number-input-directive" module="numberExample">
  15204. <file name="index.html">
  15205. <script>
  15206. angular.module('numberExample', [])
  15207. .controller('ExampleController', ['$scope', function($scope) {
  15208. $scope.value = 12;
  15209. }]);
  15210. </script>
  15211. <form name="myForm" ng-controller="ExampleController">
  15212. Number: <input type="number" name="input" ng-model="value"
  15213. min="0" max="99" required>
  15214. <span class="error" ng-show="myForm.input.$error.required">
  15215. Required!</span>
  15216. <span class="error" ng-show="myForm.input.$error.number">
  15217. Not valid number!</span>
  15218. <tt>value = {{value}}</tt><br/>
  15219. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15220. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15221. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15222. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15223. </form>
  15224. </file>
  15225. <file name="protractor.js" type="protractor">
  15226. var value = element(by.binding('value'));
  15227. var valid = element(by.binding('myForm.input.$valid'));
  15228. var input = element(by.model('value'));
  15229. it('should initialize to model', function() {
  15230. expect(value.getText()).toContain('12');
  15231. expect(valid.getText()).toContain('true');
  15232. });
  15233. it('should be invalid if empty', function() {
  15234. input.clear();
  15235. input.sendKeys('');
  15236. expect(value.getText()).toEqual('value =');
  15237. expect(valid.getText()).toContain('false');
  15238. });
  15239. it('should be invalid if over max', function() {
  15240. input.clear();
  15241. input.sendKeys('123');
  15242. expect(value.getText()).toEqual('value =');
  15243. expect(valid.getText()).toContain('false');
  15244. });
  15245. </file>
  15246. </example>
  15247. */
  15248. 'number': numberInputType,
  15249. /**
  15250. * @ngdoc input
  15251. * @name input[url]
  15252. *
  15253. * @description
  15254. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  15255. * valid URL.
  15256. *
  15257. * @param {string} ngModel Assignable angular expression to data-bind to.
  15258. * @param {string=} name Property name of the form under which the control is published.
  15259. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15260. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15261. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15262. * `required` when you want to data-bind to the `required` attribute.
  15263. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15264. * minlength.
  15265. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15266. * maxlength.
  15267. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15268. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15269. * patterns defined as scope expressions.
  15270. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15271. * interaction with the input element.
  15272. *
  15273. * @example
  15274. <example name="url-input-directive" module="urlExample">
  15275. <file name="index.html">
  15276. <script>
  15277. angular.module('urlExample', [])
  15278. .controller('ExampleController', ['$scope', function($scope) {
  15279. $scope.text = 'http://google.com';
  15280. }]);
  15281. </script>
  15282. <form name="myForm" ng-controller="ExampleController">
  15283. URL: <input type="url" name="input" ng-model="text" required>
  15284. <span class="error" ng-show="myForm.input.$error.required">
  15285. Required!</span>
  15286. <span class="error" ng-show="myForm.input.$error.url">
  15287. Not valid url!</span>
  15288. <tt>text = {{text}}</tt><br/>
  15289. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15290. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15291. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15292. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15293. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  15294. </form>
  15295. </file>
  15296. <file name="protractor.js" type="protractor">
  15297. var text = element(by.binding('text'));
  15298. var valid = element(by.binding('myForm.input.$valid'));
  15299. var input = element(by.model('text'));
  15300. it('should initialize to model', function() {
  15301. expect(text.getText()).toContain('http://google.com');
  15302. expect(valid.getText()).toContain('true');
  15303. });
  15304. it('should be invalid if empty', function() {
  15305. input.clear();
  15306. input.sendKeys('');
  15307. expect(text.getText()).toEqual('text =');
  15308. expect(valid.getText()).toContain('false');
  15309. });
  15310. it('should be invalid if not url', function() {
  15311. input.clear();
  15312. input.sendKeys('box');
  15313. expect(valid.getText()).toContain('false');
  15314. });
  15315. </file>
  15316. </example>
  15317. */
  15318. 'url': urlInputType,
  15319. /**
  15320. * @ngdoc input
  15321. * @name input[email]
  15322. *
  15323. * @description
  15324. * Text input with email validation. Sets the `email` validation error key if not a valid email
  15325. * address.
  15326. *
  15327. * @param {string} ngModel Assignable angular expression to data-bind to.
  15328. * @param {string=} name Property name of the form under which the control is published.
  15329. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15330. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15331. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15332. * `required` when you want to data-bind to the `required` attribute.
  15333. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15334. * minlength.
  15335. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15336. * maxlength.
  15337. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15338. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15339. * patterns defined as scope expressions.
  15340. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15341. * interaction with the input element.
  15342. *
  15343. * @example
  15344. <example name="email-input-directive" module="emailExample">
  15345. <file name="index.html">
  15346. <script>
  15347. angular.module('emailExample', [])
  15348. .controller('ExampleController', ['$scope', function($scope) {
  15349. $scope.text = 'me@example.com';
  15350. }]);
  15351. </script>
  15352. <form name="myForm" ng-controller="ExampleController">
  15353. Email: <input type="email" name="input" ng-model="text" required>
  15354. <span class="error" ng-show="myForm.input.$error.required">
  15355. Required!</span>
  15356. <span class="error" ng-show="myForm.input.$error.email">
  15357. Not valid email!</span>
  15358. <tt>text = {{text}}</tt><br/>
  15359. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15360. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15361. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15362. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15363. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  15364. </form>
  15365. </file>
  15366. <file name="protractor.js" type="protractor">
  15367. var text = element(by.binding('text'));
  15368. var valid = element(by.binding('myForm.input.$valid'));
  15369. var input = element(by.model('text'));
  15370. it('should initialize to model', function() {
  15371. expect(text.getText()).toContain('me@example.com');
  15372. expect(valid.getText()).toContain('true');
  15373. });
  15374. it('should be invalid if empty', function() {
  15375. input.clear();
  15376. input.sendKeys('');
  15377. expect(text.getText()).toEqual('text =');
  15378. expect(valid.getText()).toContain('false');
  15379. });
  15380. it('should be invalid if not email', function() {
  15381. input.clear();
  15382. input.sendKeys('xxx');
  15383. expect(valid.getText()).toContain('false');
  15384. });
  15385. </file>
  15386. </example>
  15387. */
  15388. 'email': emailInputType,
  15389. /**
  15390. * @ngdoc input
  15391. * @name input[radio]
  15392. *
  15393. * @description
  15394. * HTML radio button.
  15395. *
  15396. * @param {string} ngModel Assignable angular expression to data-bind to.
  15397. * @param {string} value The value to which the expression should be set when selected.
  15398. * @param {string=} name Property name of the form under which the control is published.
  15399. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15400. * interaction with the input element.
  15401. * @param {string} ngValue Angular expression which sets the value to which the expression should
  15402. * be set when selected.
  15403. *
  15404. * @example
  15405. <example name="radio-input-directive" module="radioExample">
  15406. <file name="index.html">
  15407. <script>
  15408. angular.module('radioExample', [])
  15409. .controller('ExampleController', ['$scope', function($scope) {
  15410. $scope.color = 'blue';
  15411. $scope.specialValue = {
  15412. "id": "12345",
  15413. "value": "green"
  15414. };
  15415. }]);
  15416. </script>
  15417. <form name="myForm" ng-controller="ExampleController">
  15418. <input type="radio" ng-model="color" value="red"> Red <br/>
  15419. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  15420. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  15421. <tt>color = {{color | json}}</tt><br/>
  15422. </form>
  15423. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  15424. </file>
  15425. <file name="protractor.js" type="protractor">
  15426. it('should change state', function() {
  15427. var color = element(by.binding('color'));
  15428. expect(color.getText()).toContain('blue');
  15429. element.all(by.model('color')).get(0).click();
  15430. expect(color.getText()).toContain('red');
  15431. });
  15432. </file>
  15433. </example>
  15434. */
  15435. 'radio': radioInputType,
  15436. /**
  15437. * @ngdoc input
  15438. * @name input[checkbox]
  15439. *
  15440. * @description
  15441. * HTML checkbox.
  15442. *
  15443. * @param {string} ngModel Assignable angular expression to data-bind to.
  15444. * @param {string=} name Property name of the form under which the control is published.
  15445. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  15446. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  15447. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15448. * interaction with the input element.
  15449. *
  15450. * @example
  15451. <example name="checkbox-input-directive" module="checkboxExample">
  15452. <file name="index.html">
  15453. <script>
  15454. angular.module('checkboxExample', [])
  15455. .controller('ExampleController', ['$scope', function($scope) {
  15456. $scope.value1 = true;
  15457. $scope.value2 = 'YES'
  15458. }]);
  15459. </script>
  15460. <form name="myForm" ng-controller="ExampleController">
  15461. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15462. Value2: <input type="checkbox" ng-model="value2"
  15463. ng-true-value="YES" ng-false-value="NO"> <br/>
  15464. <tt>value1 = {{value1}}</tt><br/>
  15465. <tt>value2 = {{value2}}</tt><br/>
  15466. </form>
  15467. </file>
  15468. <file name="protractor.js" type="protractor">
  15469. it('should change state', function() {
  15470. var value1 = element(by.binding('value1'));
  15471. var value2 = element(by.binding('value2'));
  15472. expect(value1.getText()).toContain('true');
  15473. expect(value2.getText()).toContain('YES');
  15474. element(by.model('value1')).click();
  15475. element(by.model('value2')).click();
  15476. expect(value1.getText()).toContain('false');
  15477. expect(value2.getText()).toContain('NO');
  15478. });
  15479. </file>
  15480. </example>
  15481. */
  15482. 'checkbox': checkboxInputType,
  15483. 'hidden': noop,
  15484. 'button': noop,
  15485. 'submit': noop,
  15486. 'reset': noop,
  15487. 'file': noop
  15488. };
  15489. // A helper function to call $setValidity and return the value / undefined,
  15490. // a pattern that is repeated a lot in the input validation logic.
  15491. function validate(ctrl, validatorName, validity, value){
  15492. ctrl.$setValidity(validatorName, validity);
  15493. return validity ? value : undefined;
  15494. }
  15495. function testFlags(validity, flags) {
  15496. var i, flag;
  15497. if (flags) {
  15498. for (i=0; i<flags.length; ++i) {
  15499. flag = flags[i];
  15500. if (validity[flag]) {
  15501. return true;
  15502. }
  15503. }
  15504. }
  15505. return false;
  15506. }
  15507. // Pass validity so that behaviour can be mocked easier.
  15508. function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
  15509. if (isObject(validity)) {
  15510. ctrl.$$hasNativeValidators = true;
  15511. var validator = function(value) {
  15512. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15513. // perform the required validation)
  15514. if (!ctrl.$error[validatorName] &&
  15515. !testFlags(validity, ignoreFlags) &&
  15516. testFlags(validity, badFlags)) {
  15517. ctrl.$setValidity(validatorName, false);
  15518. return;
  15519. }
  15520. return value;
  15521. };
  15522. ctrl.$parsers.push(validator);
  15523. }
  15524. }
  15525. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15526. var validity = element.prop(VALIDITY_STATE_PROPERTY);
  15527. var placeholder = element[0].placeholder, noevent = {};
  15528. var type = lowercase(element[0].type);
  15529. ctrl.$$validityState = validity;
  15530. // In composition mode, users are still inputing intermediate text buffer,
  15531. // hold the listener until composition is done.
  15532. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15533. if (!$sniffer.android) {
  15534. var composing = false;
  15535. element.on('compositionstart', function(data) {
  15536. composing = true;
  15537. });
  15538. element.on('compositionend', function() {
  15539. composing = false;
  15540. listener();
  15541. });
  15542. }
  15543. var listener = function(ev) {
  15544. if (composing) return;
  15545. var value = element.val();
  15546. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  15547. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  15548. // IE also sends input events for other non-input-related things, (such as focusing on a
  15549. // form control), so this change is not entirely enough to solve this.
  15550. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  15551. placeholder = element[0].placeholder;
  15552. return;
  15553. }
  15554. // By default we will trim the value
  15555. // If the attribute ng-trim exists we will avoid trimming
  15556. // If input type is 'password', the value is never trimmed
  15557. if (type !== 'password' && (toBoolean(attr.ngTrim || 'T'))) {
  15558. value = trim(value);
  15559. }
  15560. // If a control is suffering from bad input, browsers discard its value, so it may be
  15561. // necessary to revalidate even if the control's value is the same empty value twice in
  15562. // a row.
  15563. var revalidate = validity && ctrl.$$hasNativeValidators;
  15564. if (ctrl.$viewValue !== value || (value === '' && revalidate)) {
  15565. if (scope.$root.$$phase) {
  15566. ctrl.$setViewValue(value);
  15567. } else {
  15568. scope.$apply(function() {
  15569. ctrl.$setViewValue(value);
  15570. });
  15571. }
  15572. }
  15573. };
  15574. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15575. // input event on backspace, delete or cut
  15576. if ($sniffer.hasEvent('input')) {
  15577. element.on('input', listener);
  15578. } else {
  15579. var timeout;
  15580. var deferListener = function() {
  15581. if (!timeout) {
  15582. timeout = $browser.defer(function() {
  15583. listener();
  15584. timeout = null;
  15585. });
  15586. }
  15587. };
  15588. element.on('keydown', function(event) {
  15589. var key = event.keyCode;
  15590. // ignore
  15591. // command modifiers arrows
  15592. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15593. deferListener();
  15594. });
  15595. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15596. if ($sniffer.hasEvent('paste')) {
  15597. element.on('paste cut', deferListener);
  15598. }
  15599. }
  15600. // if user paste into input using mouse on older browser
  15601. // or form autocomplete on newer browser, we need "change" event to catch it
  15602. element.on('change', listener);
  15603. ctrl.$render = function() {
  15604. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15605. };
  15606. // pattern validator
  15607. var pattern = attr.ngPattern,
  15608. patternValidator,
  15609. match;
  15610. if (pattern) {
  15611. var validateRegex = function(regexp, value) {
  15612. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15613. };
  15614. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15615. if (match) {
  15616. pattern = new RegExp(match[1], match[2]);
  15617. patternValidator = function(value) {
  15618. return validateRegex(pattern, value);
  15619. };
  15620. } else {
  15621. patternValidator = function(value) {
  15622. var patternObj = scope.$eval(pattern);
  15623. if (!patternObj || !patternObj.test) {
  15624. throw minErr('ngPattern')('noregexp',
  15625. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15626. patternObj, startingTag(element));
  15627. }
  15628. return validateRegex(patternObj, value);
  15629. };
  15630. }
  15631. ctrl.$formatters.push(patternValidator);
  15632. ctrl.$parsers.push(patternValidator);
  15633. }
  15634. // min length validator
  15635. if (attr.ngMinlength) {
  15636. var minlength = int(attr.ngMinlength);
  15637. var minLengthValidator = function(value) {
  15638. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15639. };
  15640. ctrl.$parsers.push(minLengthValidator);
  15641. ctrl.$formatters.push(minLengthValidator);
  15642. }
  15643. // max length validator
  15644. if (attr.ngMaxlength) {
  15645. var maxlength = int(attr.ngMaxlength);
  15646. var maxLengthValidator = function(value) {
  15647. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15648. };
  15649. ctrl.$parsers.push(maxLengthValidator);
  15650. ctrl.$formatters.push(maxLengthValidator);
  15651. }
  15652. }
  15653. var numberBadFlags = ['badInput'];
  15654. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15655. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15656. ctrl.$parsers.push(function(value) {
  15657. var empty = ctrl.$isEmpty(value);
  15658. if (empty || NUMBER_REGEXP.test(value)) {
  15659. ctrl.$setValidity('number', true);
  15660. return value === '' ? null : (empty ? value : parseFloat(value));
  15661. } else {
  15662. ctrl.$setValidity('number', false);
  15663. return undefined;
  15664. }
  15665. });
  15666. addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
  15667. ctrl.$formatters.push(function(value) {
  15668. return ctrl.$isEmpty(value) ? '' : '' + value;
  15669. });
  15670. if (attr.min) {
  15671. var minValidator = function(value) {
  15672. var min = parseFloat(attr.min);
  15673. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15674. };
  15675. ctrl.$parsers.push(minValidator);
  15676. ctrl.$formatters.push(minValidator);
  15677. }
  15678. if (attr.max) {
  15679. var maxValidator = function(value) {
  15680. var max = parseFloat(attr.max);
  15681. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15682. };
  15683. ctrl.$parsers.push(maxValidator);
  15684. ctrl.$formatters.push(maxValidator);
  15685. }
  15686. ctrl.$formatters.push(function(value) {
  15687. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15688. });
  15689. }
  15690. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15691. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15692. var urlValidator = function(value) {
  15693. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15694. };
  15695. ctrl.$formatters.push(urlValidator);
  15696. ctrl.$parsers.push(urlValidator);
  15697. }
  15698. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15699. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15700. var emailValidator = function(value) {
  15701. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15702. };
  15703. ctrl.$formatters.push(emailValidator);
  15704. ctrl.$parsers.push(emailValidator);
  15705. }
  15706. function radioInputType(scope, element, attr, ctrl) {
  15707. // make the name unique, if not defined
  15708. if (isUndefined(attr.name)) {
  15709. element.attr('name', nextUid());
  15710. }
  15711. element.on('click', function() {
  15712. if (element[0].checked) {
  15713. scope.$apply(function() {
  15714. ctrl.$setViewValue(attr.value);
  15715. });
  15716. }
  15717. });
  15718. ctrl.$render = function() {
  15719. var value = attr.value;
  15720. element[0].checked = (value == ctrl.$viewValue);
  15721. };
  15722. attr.$observe('value', ctrl.$render);
  15723. }
  15724. function checkboxInputType(scope, element, attr, ctrl) {
  15725. var trueValue = attr.ngTrueValue,
  15726. falseValue = attr.ngFalseValue;
  15727. if (!isString(trueValue)) trueValue = true;
  15728. if (!isString(falseValue)) falseValue = false;
  15729. element.on('click', function() {
  15730. scope.$apply(function() {
  15731. ctrl.$setViewValue(element[0].checked);
  15732. });
  15733. });
  15734. ctrl.$render = function() {
  15735. element[0].checked = ctrl.$viewValue;
  15736. };
  15737. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15738. ctrl.$isEmpty = function(value) {
  15739. return value !== trueValue;
  15740. };
  15741. ctrl.$formatters.push(function(value) {
  15742. return value === trueValue;
  15743. });
  15744. ctrl.$parsers.push(function(value) {
  15745. return value ? trueValue : falseValue;
  15746. });
  15747. }
  15748. /**
  15749. * @ngdoc directive
  15750. * @name textarea
  15751. * @restrict E
  15752. *
  15753. * @description
  15754. * HTML textarea element control with angular data-binding. The data-binding and validation
  15755. * properties of this element are exactly the same as those of the
  15756. * {@link ng.directive:input input element}.
  15757. *
  15758. * @param {string} ngModel Assignable angular expression to data-bind to.
  15759. * @param {string=} name Property name of the form under which the control is published.
  15760. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15761. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15762. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15763. * `required` when you want to data-bind to the `required` attribute.
  15764. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15765. * minlength.
  15766. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15767. * maxlength.
  15768. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15769. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15770. * patterns defined as scope expressions.
  15771. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15772. * interaction with the input element.
  15773. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15774. */
  15775. /**
  15776. * @ngdoc directive
  15777. * @name input
  15778. * @restrict E
  15779. *
  15780. * @description
  15781. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15782. * and polyfills the HTML5 validation behavior for older browsers.
  15783. *
  15784. * *NOTE* Not every feature offered is available for all input types.
  15785. *
  15786. * @param {string} ngModel Assignable angular expression to data-bind to.
  15787. * @param {string=} name Property name of the form under which the control is published.
  15788. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15789. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15790. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15791. * minlength.
  15792. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15793. * maxlength.
  15794. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15795. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15796. * patterns defined as scope expressions.
  15797. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15798. * interaction with the input element.
  15799. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15800. * This parameter is ignored for input[type=password] controls, which will never trim the
  15801. * input.
  15802. *
  15803. * @example
  15804. <example name="input-directive" module="inputExample">
  15805. <file name="index.html">
  15806. <script>
  15807. angular.module('inputExample', [])
  15808. .controller('ExampleController', ['$scope', function($scope) {
  15809. $scope.user = {name: 'guest', last: 'visitor'};
  15810. }]);
  15811. </script>
  15812. <div ng-controller="ExampleController">
  15813. <form name="myForm">
  15814. User name: <input type="text" name="userName" ng-model="user.name" required>
  15815. <span class="error" ng-show="myForm.userName.$error.required">
  15816. Required!</span><br>
  15817. Last name: <input type="text" name="lastName" ng-model="user.last"
  15818. ng-minlength="3" ng-maxlength="10">
  15819. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15820. Too short!</span>
  15821. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15822. Too long!</span><br>
  15823. </form>
  15824. <hr>
  15825. <tt>user = {{user}}</tt><br/>
  15826. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15827. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15828. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15829. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15830. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15831. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15832. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15833. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15834. </div>
  15835. </file>
  15836. <file name="protractor.js" type="protractor">
  15837. var user = element(by.binding('{{user}}'));
  15838. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15839. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15840. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15841. var formValid = element(by.binding('myForm.$valid'));
  15842. var userNameInput = element(by.model('user.name'));
  15843. var userLastInput = element(by.model('user.last'));
  15844. it('should initialize to model', function() {
  15845. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15846. expect(userNameValid.getText()).toContain('true');
  15847. expect(formValid.getText()).toContain('true');
  15848. });
  15849. it('should be invalid if empty when required', function() {
  15850. userNameInput.clear();
  15851. userNameInput.sendKeys('');
  15852. expect(user.getText()).toContain('{"last":"visitor"}');
  15853. expect(userNameValid.getText()).toContain('false');
  15854. expect(formValid.getText()).toContain('false');
  15855. });
  15856. it('should be valid if empty when min length is set', function() {
  15857. userLastInput.clear();
  15858. userLastInput.sendKeys('');
  15859. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15860. expect(lastNameValid.getText()).toContain('true');
  15861. expect(formValid.getText()).toContain('true');
  15862. });
  15863. it('should be invalid if less than required min length', function() {
  15864. userLastInput.clear();
  15865. userLastInput.sendKeys('xx');
  15866. expect(user.getText()).toContain('{"name":"guest"}');
  15867. expect(lastNameValid.getText()).toContain('false');
  15868. expect(lastNameError.getText()).toContain('minlength');
  15869. expect(formValid.getText()).toContain('false');
  15870. });
  15871. it('should be invalid if longer than max length', function() {
  15872. userLastInput.clear();
  15873. userLastInput.sendKeys('some ridiculously long name');
  15874. expect(user.getText()).toContain('{"name":"guest"}');
  15875. expect(lastNameValid.getText()).toContain('false');
  15876. expect(lastNameError.getText()).toContain('maxlength');
  15877. expect(formValid.getText()).toContain('false');
  15878. });
  15879. </file>
  15880. </example>
  15881. */
  15882. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15883. return {
  15884. restrict: 'E',
  15885. require: '?ngModel',
  15886. link: function(scope, element, attr, ctrl) {
  15887. if (ctrl) {
  15888. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15889. $browser);
  15890. }
  15891. }
  15892. };
  15893. }];
  15894. var VALID_CLASS = 'ng-valid',
  15895. INVALID_CLASS = 'ng-invalid',
  15896. PRISTINE_CLASS = 'ng-pristine',
  15897. DIRTY_CLASS = 'ng-dirty';
  15898. /**
  15899. * @ngdoc type
  15900. * @name ngModel.NgModelController
  15901. *
  15902. * @property {string} $viewValue Actual string value in the view.
  15903. * @property {*} $modelValue The value in the model, that the control is bound to.
  15904. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15905. the control reads value from the DOM. Each function is called, in turn, passing the value
  15906. through to the next. The last return value is used to populate the model.
  15907. Used to sanitize / convert the value as well as validation. For validation,
  15908. the parsers should update the validity state using
  15909. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15910. and return `undefined` for invalid values.
  15911. *
  15912. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15913. the model value changes. Each function is called, in turn, passing the value through to the
  15914. next. Used to format / convert values for display in the control and validation.
  15915. * ```js
  15916. * function formatter(value) {
  15917. * if (value) {
  15918. * return value.toUpperCase();
  15919. * }
  15920. * }
  15921. * ngModel.$formatters.push(formatter);
  15922. * ```
  15923. *
  15924. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15925. * view value has changed. It is called with no arguments, and its return value is ignored.
  15926. * This can be used in place of additional $watches against the model value.
  15927. *
  15928. * @property {Object} $error An object hash with all errors as keys.
  15929. *
  15930. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15931. * @property {boolean} $dirty True if user has already interacted with the control.
  15932. * @property {boolean} $valid True if there is no error.
  15933. * @property {boolean} $invalid True if at least one error on the control.
  15934. *
  15935. * @description
  15936. *
  15937. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15938. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15939. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15940. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15941. * `NgModelController` for data-binding.
  15942. *
  15943. * ## Custom Control Example
  15944. * This example shows how to use `NgModelController` with a custom control to achieve
  15945. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  15946. * collaborate together to achieve the desired result.
  15947. *
  15948. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  15949. * contents be edited in place by the user. This will not work on older browsers.
  15950. *
  15951. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  15952. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  15953. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  15954. * that content using the `$sce` service.
  15955. *
  15956. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  15957. <file name="style.css">
  15958. [contenteditable] {
  15959. border: 1px solid black;
  15960. background-color: white;
  15961. min-height: 20px;
  15962. }
  15963. .ng-invalid {
  15964. border: 1px solid red;
  15965. }
  15966. </file>
  15967. <file name="script.js">
  15968. angular.module('customControl', ['ngSanitize']).
  15969. directive('contenteditable', ['$sce', function($sce) {
  15970. return {
  15971. restrict: 'A', // only activate on element attribute
  15972. require: '?ngModel', // get a hold of NgModelController
  15973. link: function(scope, element, attrs, ngModel) {
  15974. if(!ngModel) return; // do nothing if no ng-model
  15975. // Specify how UI should be updated
  15976. ngModel.$render = function() {
  15977. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  15978. };
  15979. // Listen for change events to enable binding
  15980. element.on('blur keyup change', function() {
  15981. scope.$evalAsync(read);
  15982. });
  15983. read(); // initialize
  15984. // Write data to the model
  15985. function read() {
  15986. var html = element.html();
  15987. // When we clear the content editable the browser leaves a <br> behind
  15988. // If strip-br attribute is provided then we strip this out
  15989. if( attrs.stripBr && html == '<br>' ) {
  15990. html = '';
  15991. }
  15992. ngModel.$setViewValue(html);
  15993. }
  15994. }
  15995. };
  15996. }]);
  15997. </file>
  15998. <file name="index.html">
  15999. <form name="myForm">
  16000. <div contenteditable
  16001. name="myWidget" ng-model="userContent"
  16002. strip-br="true"
  16003. required>Change me!</div>
  16004. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  16005. <hr>
  16006. <textarea ng-model="userContent"></textarea>
  16007. </form>
  16008. </file>
  16009. <file name="protractor.js" type="protractor">
  16010. it('should data-bind and become invalid', function() {
  16011. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  16012. // SafariDriver can't handle contenteditable
  16013. // and Firefox driver can't clear contenteditables very well
  16014. return;
  16015. }
  16016. var contentEditable = element(by.css('[contenteditable]'));
  16017. var content = 'Change me!';
  16018. expect(contentEditable.getText()).toEqual(content);
  16019. contentEditable.clear();
  16020. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  16021. expect(contentEditable.getText()).toEqual('');
  16022. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  16023. });
  16024. </file>
  16025. * </example>
  16026. *
  16027. *
  16028. */
  16029. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  16030. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  16031. this.$viewValue = Number.NaN;
  16032. this.$modelValue = Number.NaN;
  16033. this.$parsers = [];
  16034. this.$formatters = [];
  16035. this.$viewChangeListeners = [];
  16036. this.$pristine = true;
  16037. this.$dirty = false;
  16038. this.$valid = true;
  16039. this.$invalid = false;
  16040. this.$name = $attr.name;
  16041. var ngModelGet = $parse($attr.ngModel),
  16042. ngModelSet = ngModelGet.assign;
  16043. if (!ngModelSet) {
  16044. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  16045. $attr.ngModel, startingTag($element));
  16046. }
  16047. /**
  16048. * @ngdoc method
  16049. * @name ngModel.NgModelController#$render
  16050. *
  16051. * @description
  16052. * Called when the view needs to be updated. It is expected that the user of the ng-model
  16053. * directive will implement this method.
  16054. */
  16055. this.$render = noop;
  16056. /**
  16057. * @ngdoc method
  16058. * @name ngModel.NgModelController#$isEmpty
  16059. *
  16060. * @description
  16061. * This is called when we need to determine if the value of the input is empty.
  16062. *
  16063. * For instance, the required directive does this to work out if the input has data or not.
  16064. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  16065. *
  16066. * You can override this for input directives whose concept of being empty is different to the
  16067. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  16068. * implies empty.
  16069. *
  16070. * @param {*} value Reference to check.
  16071. * @returns {boolean} True if `value` is empty.
  16072. */
  16073. this.$isEmpty = function(value) {
  16074. return isUndefined(value) || value === '' || value === null || value !== value;
  16075. };
  16076. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  16077. invalidCount = 0, // used to easily determine if we are valid
  16078. $error = this.$error = {}; // keep invalid keys here
  16079. // Setup initial state of the control
  16080. $element.addClass(PRISTINE_CLASS);
  16081. toggleValidCss(true);
  16082. // convenience method for easy toggling of classes
  16083. function toggleValidCss(isValid, validationErrorKey) {
  16084. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  16085. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  16086. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  16087. }
  16088. /**
  16089. * @ngdoc method
  16090. * @name ngModel.NgModelController#$setValidity
  16091. *
  16092. * @description
  16093. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  16094. * does not notify form if given validator is already marked as invalid).
  16095. *
  16096. * This method should be called by validators - i.e. the parser or formatter functions.
  16097. *
  16098. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  16099. * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding.
  16100. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  16101. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  16102. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  16103. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  16104. */
  16105. this.$setValidity = function(validationErrorKey, isValid) {
  16106. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  16107. // jshint -W018
  16108. if ($error[validationErrorKey] === !isValid) return;
  16109. // jshint +W018
  16110. if (isValid) {
  16111. if ($error[validationErrorKey]) invalidCount--;
  16112. if (!invalidCount) {
  16113. toggleValidCss(true);
  16114. this.$valid = true;
  16115. this.$invalid = false;
  16116. }
  16117. } else {
  16118. toggleValidCss(false);
  16119. this.$invalid = true;
  16120. this.$valid = false;
  16121. invalidCount++;
  16122. }
  16123. $error[validationErrorKey] = !isValid;
  16124. toggleValidCss(isValid, validationErrorKey);
  16125. parentForm.$setValidity(validationErrorKey, isValid, this);
  16126. };
  16127. /**
  16128. * @ngdoc method
  16129. * @name ngModel.NgModelController#$setPristine
  16130. *
  16131. * @description
  16132. * Sets the control to its pristine state.
  16133. *
  16134. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  16135. * state (ng-pristine class).
  16136. */
  16137. this.$setPristine = function () {
  16138. this.$dirty = false;
  16139. this.$pristine = true;
  16140. $animate.removeClass($element, DIRTY_CLASS);
  16141. $animate.addClass($element, PRISTINE_CLASS);
  16142. };
  16143. /**
  16144. * @ngdoc method
  16145. * @name ngModel.NgModelController#$setViewValue
  16146. *
  16147. * @description
  16148. * Update the view value.
  16149. *
  16150. * This method should be called when the view value changes, typically from within a DOM event handler.
  16151. * For example {@link ng.directive:input input} and
  16152. * {@link ng.directive:select select} directives call it.
  16153. *
  16154. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  16155. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  16156. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  16157. *
  16158. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  16159. *
  16160. * Note that calling this function does not trigger a `$digest`.
  16161. *
  16162. * @param {string} value Value from the view.
  16163. */
  16164. this.$setViewValue = function(value) {
  16165. this.$viewValue = value;
  16166. // change to dirty
  16167. if (this.$pristine) {
  16168. this.$dirty = true;
  16169. this.$pristine = false;
  16170. $animate.removeClass($element, PRISTINE_CLASS);
  16171. $animate.addClass($element, DIRTY_CLASS);
  16172. parentForm.$setDirty();
  16173. }
  16174. forEach(this.$parsers, function(fn) {
  16175. value = fn(value);
  16176. });
  16177. if (this.$modelValue !== value) {
  16178. this.$modelValue = value;
  16179. ngModelSet($scope, value);
  16180. forEach(this.$viewChangeListeners, function(listener) {
  16181. try {
  16182. listener();
  16183. } catch(e) {
  16184. $exceptionHandler(e);
  16185. }
  16186. });
  16187. }
  16188. };
  16189. // model -> value
  16190. var ctrl = this;
  16191. $scope.$watch(function ngModelWatch() {
  16192. var value = ngModelGet($scope);
  16193. // if scope model value and ngModel value are out of sync
  16194. if (ctrl.$modelValue !== value) {
  16195. var formatters = ctrl.$formatters,
  16196. idx = formatters.length;
  16197. ctrl.$modelValue = value;
  16198. while(idx--) {
  16199. value = formatters[idx](value);
  16200. }
  16201. if (ctrl.$viewValue !== value) {
  16202. ctrl.$viewValue = value;
  16203. ctrl.$render();
  16204. }
  16205. }
  16206. return value;
  16207. });
  16208. }];
  16209. /**
  16210. * @ngdoc directive
  16211. * @name ngModel
  16212. *
  16213. * @element input
  16214. *
  16215. * @description
  16216. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  16217. * property on the scope using {@link ngModel.NgModelController NgModelController},
  16218. * which is created and exposed by this directive.
  16219. *
  16220. * `ngModel` is responsible for:
  16221. *
  16222. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  16223. * require.
  16224. * - Providing validation behavior (i.e. required, number, email, url).
  16225. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  16226. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  16227. * - Registering the control with its parent {@link ng.directive:form form}.
  16228. *
  16229. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  16230. * current scope. If the property doesn't already exist on this scope, it will be created
  16231. * implicitly and added to the scope.
  16232. *
  16233. * For best practices on using `ngModel`, see:
  16234. *
  16235. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  16236. *
  16237. * For basic examples, how to use `ngModel`, see:
  16238. *
  16239. * - {@link ng.directive:input input}
  16240. * - {@link input[text] text}
  16241. * - {@link input[checkbox] checkbox}
  16242. * - {@link input[radio] radio}
  16243. * - {@link input[number] number}
  16244. * - {@link input[email] email}
  16245. * - {@link input[url] url}
  16246. * - {@link ng.directive:select select}
  16247. * - {@link ng.directive:textarea textarea}
  16248. *
  16249. * # CSS classes
  16250. * The following CSS classes are added and removed on the associated input/select/textarea element
  16251. * depending on the validity of the model.
  16252. *
  16253. * - `ng-valid` is set if the model is valid.
  16254. * - `ng-invalid` is set if the model is invalid.
  16255. * - `ng-pristine` is set if the model is pristine.
  16256. * - `ng-dirty` is set if the model is dirty.
  16257. *
  16258. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16259. *
  16260. * ## Animation Hooks
  16261. *
  16262. * Animations within models are triggered when any of the associated CSS classes are added and removed
  16263. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  16264. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  16265. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  16266. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  16267. *
  16268. * The following example shows a simple way to utilize CSS transitions to style an input element
  16269. * that has been rendered as invalid after it has been validated:
  16270. *
  16271. * <pre>
  16272. * //be sure to include ngAnimate as a module to hook into more
  16273. * //advanced animations
  16274. * .my-input {
  16275. * transition:0.5s linear all;
  16276. * background: white;
  16277. * }
  16278. * .my-input.ng-invalid {
  16279. * background: red;
  16280. * color:white;
  16281. * }
  16282. * </pre>
  16283. *
  16284. * @example
  16285. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  16286. <file name="index.html">
  16287. <script>
  16288. angular.module('inputExample', [])
  16289. .controller('ExampleController', ['$scope', function($scope) {
  16290. $scope.val = '1';
  16291. }]);
  16292. </script>
  16293. <style>
  16294. .my-input {
  16295. -webkit-transition:all linear 0.5s;
  16296. transition:all linear 0.5s;
  16297. background: transparent;
  16298. }
  16299. .my-input.ng-invalid {
  16300. color:white;
  16301. background: red;
  16302. }
  16303. </style>
  16304. Update input to see transitions when valid/invalid.
  16305. Integer is a valid value.
  16306. <form name="testForm" ng-controller="ExampleController">
  16307. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  16308. </form>
  16309. </file>
  16310. * </example>
  16311. */
  16312. var ngModelDirective = function() {
  16313. return {
  16314. require: ['ngModel', '^?form'],
  16315. controller: NgModelController,
  16316. link: function(scope, element, attr, ctrls) {
  16317. // notify others, especially parent forms
  16318. var modelCtrl = ctrls[0],
  16319. formCtrl = ctrls[1] || nullFormCtrl;
  16320. formCtrl.$addControl(modelCtrl);
  16321. scope.$on('$destroy', function() {
  16322. formCtrl.$removeControl(modelCtrl);
  16323. });
  16324. }
  16325. };
  16326. };
  16327. /**
  16328. * @ngdoc directive
  16329. * @name ngChange
  16330. *
  16331. * @description
  16332. * Evaluate the given expression when the user changes the input.
  16333. * The expression is evaluated immediately, unlike the JavaScript onchange event
  16334. * which only triggers at the end of a change (usually, when the user leaves the
  16335. * form element or presses the return key).
  16336. * The expression is not evaluated when the value change is coming from the model.
  16337. *
  16338. * Note, this directive requires `ngModel` to be present.
  16339. *
  16340. * @element input
  16341. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  16342. * in input value.
  16343. *
  16344. * @example
  16345. * <example name="ngChange-directive" module="changeExample">
  16346. * <file name="index.html">
  16347. * <script>
  16348. * angular.module('changeExample', [])
  16349. * .controller('ExampleController', ['$scope', function($scope) {
  16350. * $scope.counter = 0;
  16351. * $scope.change = function() {
  16352. * $scope.counter++;
  16353. * };
  16354. * }]);
  16355. * </script>
  16356. * <div ng-controller="ExampleController">
  16357. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  16358. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  16359. * <label for="ng-change-example2">Confirmed</label><br />
  16360. * <tt>debug = {{confirmed}}</tt><br/>
  16361. * <tt>counter = {{counter}}</tt><br/>
  16362. * </div>
  16363. * </file>
  16364. * <file name="protractor.js" type="protractor">
  16365. * var counter = element(by.binding('counter'));
  16366. * var debug = element(by.binding('confirmed'));
  16367. *
  16368. * it('should evaluate the expression if changing from view', function() {
  16369. * expect(counter.getText()).toContain('0');
  16370. *
  16371. * element(by.id('ng-change-example1')).click();
  16372. *
  16373. * expect(counter.getText()).toContain('1');
  16374. * expect(debug.getText()).toContain('true');
  16375. * });
  16376. *
  16377. * it('should not evaluate the expression if changing from model', function() {
  16378. * element(by.id('ng-change-example2')).click();
  16379. * expect(counter.getText()).toContain('0');
  16380. * expect(debug.getText()).toContain('true');
  16381. * });
  16382. * </file>
  16383. * </example>
  16384. */
  16385. var ngChangeDirective = valueFn({
  16386. require: 'ngModel',
  16387. link: function(scope, element, attr, ctrl) {
  16388. ctrl.$viewChangeListeners.push(function() {
  16389. scope.$eval(attr.ngChange);
  16390. });
  16391. }
  16392. });
  16393. var requiredDirective = function() {
  16394. return {
  16395. require: '?ngModel',
  16396. link: function(scope, elm, attr, ctrl) {
  16397. if (!ctrl) return;
  16398. attr.required = true; // force truthy in case we are on non input element
  16399. var validator = function(value) {
  16400. if (attr.required && ctrl.$isEmpty(value)) {
  16401. ctrl.$setValidity('required', false);
  16402. return;
  16403. } else {
  16404. ctrl.$setValidity('required', true);
  16405. return value;
  16406. }
  16407. };
  16408. ctrl.$formatters.push(validator);
  16409. ctrl.$parsers.unshift(validator);
  16410. attr.$observe('required', function() {
  16411. validator(ctrl.$viewValue);
  16412. });
  16413. }
  16414. };
  16415. };
  16416. /**
  16417. * @ngdoc directive
  16418. * @name ngList
  16419. *
  16420. * @description
  16421. * Text input that converts between a delimited string and an array of strings. The delimiter
  16422. * can be a fixed string (by default a comma) or a regular expression.
  16423. *
  16424. * @element input
  16425. * @param {string=} ngList optional delimiter that should be used to split the value. If
  16426. * specified in form `/something/` then the value will be converted into a regular expression.
  16427. *
  16428. * @example
  16429. <example name="ngList-directive" module="listExample">
  16430. <file name="index.html">
  16431. <script>
  16432. angular.module('listExample', [])
  16433. .controller('ExampleController', ['$scope', function($scope) {
  16434. $scope.names = ['igor', 'misko', 'vojta'];
  16435. }]);
  16436. </script>
  16437. <form name="myForm" ng-controller="ExampleController">
  16438. List: <input name="namesInput" ng-model="names" ng-list required>
  16439. <span class="error" ng-show="myForm.namesInput.$error.required">
  16440. Required!</span>
  16441. <br>
  16442. <tt>names = {{names}}</tt><br/>
  16443. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  16444. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  16445. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16446. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16447. </form>
  16448. </file>
  16449. <file name="protractor.js" type="protractor">
  16450. var listInput = element(by.model('names'));
  16451. var names = element(by.binding('{{names}}'));
  16452. var valid = element(by.binding('myForm.namesInput.$valid'));
  16453. var error = element(by.css('span.error'));
  16454. it('should initialize to model', function() {
  16455. expect(names.getText()).toContain('["igor","misko","vojta"]');
  16456. expect(valid.getText()).toContain('true');
  16457. expect(error.getCssValue('display')).toBe('none');
  16458. });
  16459. it('should be invalid if empty', function() {
  16460. listInput.clear();
  16461. listInput.sendKeys('');
  16462. expect(names.getText()).toContain('');
  16463. expect(valid.getText()).toContain('false');
  16464. expect(error.getCssValue('display')).not.toBe('none'); });
  16465. </file>
  16466. </example>
  16467. */
  16468. var ngListDirective = function() {
  16469. return {
  16470. require: 'ngModel',
  16471. link: function(scope, element, attr, ctrl) {
  16472. var match = /\/(.*)\//.exec(attr.ngList),
  16473. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  16474. var parse = function(viewValue) {
  16475. // If the viewValue is invalid (say required but empty) it will be `undefined`
  16476. if (isUndefined(viewValue)) return;
  16477. var list = [];
  16478. if (viewValue) {
  16479. forEach(viewValue.split(separator), function(value) {
  16480. if (value) list.push(trim(value));
  16481. });
  16482. }
  16483. return list;
  16484. };
  16485. ctrl.$parsers.push(parse);
  16486. ctrl.$formatters.push(function(value) {
  16487. if (isArray(value)) {
  16488. return value.join(', ');
  16489. }
  16490. return undefined;
  16491. });
  16492. // Override the standard $isEmpty because an empty array means the input is empty.
  16493. ctrl.$isEmpty = function(value) {
  16494. return !value || !value.length;
  16495. };
  16496. }
  16497. };
  16498. };
  16499. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  16500. /**
  16501. * @ngdoc directive
  16502. * @name ngValue
  16503. *
  16504. * @description
  16505. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16506. * that when the element is selected, the `ngModel` of that element is set to the
  16507. * bound value.
  16508. *
  16509. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16510. * shown below.
  16511. *
  16512. * @element input
  16513. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16514. * of the `input` element
  16515. *
  16516. * @example
  16517. <example name="ngValue-directive" module="valueExample">
  16518. <file name="index.html">
  16519. <script>
  16520. angular.module('valueExample', [])
  16521. .controller('ExampleController', ['$scope', function($scope) {
  16522. $scope.names = ['pizza', 'unicorns', 'robots'];
  16523. $scope.my = { favorite: 'unicorns' };
  16524. }]);
  16525. </script>
  16526. <form ng-controller="ExampleController">
  16527. <h2>Which is your favorite?</h2>
  16528. <label ng-repeat="name in names" for="{{name}}">
  16529. {{name}}
  16530. <input type="radio"
  16531. ng-model="my.favorite"
  16532. ng-value="name"
  16533. id="{{name}}"
  16534. name="favorite">
  16535. </label>
  16536. <div>You chose {{my.favorite}}</div>
  16537. </form>
  16538. </file>
  16539. <file name="protractor.js" type="protractor">
  16540. var favorite = element(by.binding('my.favorite'));
  16541. it('should initialize to model', function() {
  16542. expect(favorite.getText()).toContain('unicorns');
  16543. });
  16544. it('should bind the values to the inputs', function() {
  16545. element.all(by.model('my.favorite')).get(0).click();
  16546. expect(favorite.getText()).toContain('pizza');
  16547. });
  16548. </file>
  16549. </example>
  16550. */
  16551. var ngValueDirective = function() {
  16552. return {
  16553. priority: 100,
  16554. compile: function(tpl, tplAttr) {
  16555. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16556. return function ngValueConstantLink(scope, elm, attr) {
  16557. attr.$set('value', scope.$eval(attr.ngValue));
  16558. };
  16559. } else {
  16560. return function ngValueLink(scope, elm, attr) {
  16561. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16562. attr.$set('value', value);
  16563. });
  16564. };
  16565. }
  16566. }
  16567. };
  16568. };
  16569. /**
  16570. * @ngdoc directive
  16571. * @name ngBind
  16572. * @restrict AC
  16573. *
  16574. * @description
  16575. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16576. * with the value of a given expression, and to update the text content when the value of that
  16577. * expression changes.
  16578. *
  16579. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16580. * `{{ expression }}` which is similar but less verbose.
  16581. *
  16582. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  16583. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16584. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16585. *
  16586. * An alternative solution to this problem would be using the
  16587. * {@link ng.directive:ngCloak ngCloak} directive.
  16588. *
  16589. *
  16590. * @element ANY
  16591. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16592. *
  16593. * @example
  16594. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16595. <example module="bindExample">
  16596. <file name="index.html">
  16597. <script>
  16598. angular.module('bindExample', [])
  16599. .controller('ExampleController', ['$scope', function($scope) {
  16600. $scope.name = 'Whirled';
  16601. }]);
  16602. </script>
  16603. <div ng-controller="ExampleController">
  16604. Enter name: <input type="text" ng-model="name"><br>
  16605. Hello <span ng-bind="name"></span>!
  16606. </div>
  16607. </file>
  16608. <file name="protractor.js" type="protractor">
  16609. it('should check ng-bind', function() {
  16610. var nameInput = element(by.model('name'));
  16611. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16612. nameInput.clear();
  16613. nameInput.sendKeys('world');
  16614. expect(element(by.binding('name')).getText()).toBe('world');
  16615. });
  16616. </file>
  16617. </example>
  16618. */
  16619. var ngBindDirective = ngDirective({
  16620. compile: function(templateElement) {
  16621. templateElement.addClass('ng-binding');
  16622. return function (scope, element, attr) {
  16623. element.data('$binding', attr.ngBind);
  16624. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16625. // We are purposefully using == here rather than === because we want to
  16626. // catch when value is "null or undefined"
  16627. // jshint -W041
  16628. element.text(value == undefined ? '' : value);
  16629. });
  16630. };
  16631. }
  16632. });
  16633. /**
  16634. * @ngdoc directive
  16635. * @name ngBindTemplate
  16636. *
  16637. * @description
  16638. * The `ngBindTemplate` directive specifies that the element
  16639. * text content should be replaced with the interpolation of the template
  16640. * in the `ngBindTemplate` attribute.
  16641. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16642. * expressions. This directive is needed since some HTML elements
  16643. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16644. *
  16645. * @element ANY
  16646. * @param {string} ngBindTemplate template of form
  16647. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16648. *
  16649. * @example
  16650. * Try it here: enter text in text box and watch the greeting change.
  16651. <example module="bindExample">
  16652. <file name="index.html">
  16653. <script>
  16654. angular.module('bindExample', [])
  16655. .controller('ExampleController', ['$scope', function ($scope) {
  16656. $scope.salutation = 'Hello';
  16657. $scope.name = 'World';
  16658. }]);
  16659. </script>
  16660. <div ng-controller="ExampleController">
  16661. Salutation: <input type="text" ng-model="salutation"><br>
  16662. Name: <input type="text" ng-model="name"><br>
  16663. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16664. </div>
  16665. </file>
  16666. <file name="protractor.js" type="protractor">
  16667. it('should check ng-bind', function() {
  16668. var salutationElem = element(by.binding('salutation'));
  16669. var salutationInput = element(by.model('salutation'));
  16670. var nameInput = element(by.model('name'));
  16671. expect(salutationElem.getText()).toBe('Hello World!');
  16672. salutationInput.clear();
  16673. salutationInput.sendKeys('Greetings');
  16674. nameInput.clear();
  16675. nameInput.sendKeys('user');
  16676. expect(salutationElem.getText()).toBe('Greetings user!');
  16677. });
  16678. </file>
  16679. </example>
  16680. */
  16681. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16682. return function(scope, element, attr) {
  16683. // TODO: move this to scenario runner
  16684. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16685. element.addClass('ng-binding').data('$binding', interpolateFn);
  16686. attr.$observe('ngBindTemplate', function(value) {
  16687. element.text(value);
  16688. });
  16689. };
  16690. }];
  16691. /**
  16692. * @ngdoc directive
  16693. * @name ngBindHtml
  16694. *
  16695. * @description
  16696. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16697. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16698. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16699. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16700. * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
  16701. * include "angular-sanitize.js" in your application.
  16702. *
  16703. * You may also bypass sanitization for values you know are safe. To do so, bind to
  16704. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16705. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16706. *
  16707. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16708. * will have an exception (instead of an exploit.)
  16709. *
  16710. * @element ANY
  16711. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16712. *
  16713. * @example
  16714. <example module="bindHtmlExample" deps="angular-sanitize.js">
  16715. <file name="index.html">
  16716. <div ng-controller="ExampleController">
  16717. <p ng-bind-html="myHTML"></p>
  16718. </div>
  16719. </file>
  16720. <file name="script.js">
  16721. angular.module('bindHtmlExample', ['ngSanitize'])
  16722. .controller('ExampleController', ['$scope', function($scope) {
  16723. $scope.myHTML =
  16724. 'I am an <code>HTML</code>string with ' +
  16725. '<a href="#">links!</a> and other <em>stuff</em>';
  16726. }]);
  16727. </file>
  16728. <file name="protractor.js" type="protractor">
  16729. it('should check ng-bind-html', function() {
  16730. expect(element(by.binding('myHTML')).getText()).toBe(
  16731. 'I am an HTMLstring with links! and other stuff');
  16732. });
  16733. </file>
  16734. </example>
  16735. */
  16736. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16737. return {
  16738. compile: function (tElement) {
  16739. tElement.addClass('ng-binding');
  16740. return function (scope, element, attr) {
  16741. element.data('$binding', attr.ngBindHtml);
  16742. var parsed = $parse(attr.ngBindHtml);
  16743. function getStringValue() {
  16744. return (parsed(scope) || '').toString();
  16745. }
  16746. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16747. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16748. });
  16749. };
  16750. }
  16751. };
  16752. }];
  16753. function classDirective(name, selector) {
  16754. name = 'ngClass' + name;
  16755. return ['$animate', function($animate) {
  16756. return {
  16757. restrict: 'AC',
  16758. link: function(scope, element, attr) {
  16759. var oldVal;
  16760. scope.$watch(attr[name], ngClassWatchAction, true);
  16761. attr.$observe('class', function(value) {
  16762. ngClassWatchAction(scope.$eval(attr[name]));
  16763. });
  16764. if (name !== 'ngClass') {
  16765. scope.$watch('$index', function($index, old$index) {
  16766. // jshint bitwise: false
  16767. var mod = $index & 1;
  16768. if (mod !== (old$index & 1)) {
  16769. var classes = arrayClasses(scope.$eval(attr[name]));
  16770. mod === selector ?
  16771. addClasses(classes) :
  16772. removeClasses(classes);
  16773. }
  16774. });
  16775. }
  16776. function addClasses(classes) {
  16777. var newClasses = digestClassCounts(classes, 1);
  16778. attr.$addClass(newClasses);
  16779. }
  16780. function removeClasses(classes) {
  16781. var newClasses = digestClassCounts(classes, -1);
  16782. attr.$removeClass(newClasses);
  16783. }
  16784. function digestClassCounts (classes, count) {
  16785. var classCounts = element.data('$classCounts') || {};
  16786. var classesToUpdate = [];
  16787. forEach(classes, function (className) {
  16788. if (count > 0 || classCounts[className]) {
  16789. classCounts[className] = (classCounts[className] || 0) + count;
  16790. if (classCounts[className] === +(count > 0)) {
  16791. classesToUpdate.push(className);
  16792. }
  16793. }
  16794. });
  16795. element.data('$classCounts', classCounts);
  16796. return classesToUpdate.join(' ');
  16797. }
  16798. function updateClasses (oldClasses, newClasses) {
  16799. var toAdd = arrayDifference(newClasses, oldClasses);
  16800. var toRemove = arrayDifference(oldClasses, newClasses);
  16801. toRemove = digestClassCounts(toRemove, -1);
  16802. toAdd = digestClassCounts(toAdd, 1);
  16803. if (toAdd.length === 0) {
  16804. $animate.removeClass(element, toRemove);
  16805. } else if (toRemove.length === 0) {
  16806. $animate.addClass(element, toAdd);
  16807. } else {
  16808. $animate.setClass(element, toAdd, toRemove);
  16809. }
  16810. }
  16811. function ngClassWatchAction(newVal) {
  16812. if (selector === true || scope.$index % 2 === selector) {
  16813. var newClasses = arrayClasses(newVal || []);
  16814. if (!oldVal) {
  16815. addClasses(newClasses);
  16816. } else if (!equals(newVal,oldVal)) {
  16817. var oldClasses = arrayClasses(oldVal);
  16818. updateClasses(oldClasses, newClasses);
  16819. }
  16820. }
  16821. oldVal = shallowCopy(newVal);
  16822. }
  16823. }
  16824. };
  16825. function arrayDifference(tokens1, tokens2) {
  16826. var values = [];
  16827. outer:
  16828. for(var i = 0; i < tokens1.length; i++) {
  16829. var token = tokens1[i];
  16830. for(var j = 0; j < tokens2.length; j++) {
  16831. if(token == tokens2[j]) continue outer;
  16832. }
  16833. values.push(token);
  16834. }
  16835. return values;
  16836. }
  16837. function arrayClasses (classVal) {
  16838. if (isArray(classVal)) {
  16839. return classVal;
  16840. } else if (isString(classVal)) {
  16841. return classVal.split(' ');
  16842. } else if (isObject(classVal)) {
  16843. var classes = [], i = 0;
  16844. forEach(classVal, function(v, k) {
  16845. if (v) {
  16846. classes = classes.concat(k.split(' '));
  16847. }
  16848. });
  16849. return classes;
  16850. }
  16851. return classVal;
  16852. }
  16853. }];
  16854. }
  16855. /**
  16856. * @ngdoc directive
  16857. * @name ngClass
  16858. * @restrict AC
  16859. *
  16860. * @description
  16861. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16862. * an expression that represents all classes to be added.
  16863. *
  16864. * The directive operates in three different ways, depending on which of three types the expression
  16865. * evaluates to:
  16866. *
  16867. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16868. * names.
  16869. *
  16870. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16871. * one or more space-delimited class names.
  16872. *
  16873. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16874. * object with a truthy value the corresponding key is used as a class name.
  16875. *
  16876. * The directive won't add duplicate classes if a particular class was already set.
  16877. *
  16878. * When the expression changes, the previously added classes are removed and only then the
  16879. * new classes are added.
  16880. *
  16881. * @animations
  16882. * add - happens just before the class is applied to the element
  16883. * remove - happens just before the class is removed from the element
  16884. *
  16885. * @element ANY
  16886. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16887. * of the evaluation can be a string representing space delimited class
  16888. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16889. * names of the properties whose values are truthy will be added as css classes to the
  16890. * element.
  16891. *
  16892. * @example Example that demonstrates basic bindings via ngClass directive.
  16893. <example>
  16894. <file name="index.html">
  16895. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16896. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16897. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16898. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16899. <hr>
  16900. <p ng-class="style">Using String Syntax</p>
  16901. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16902. <hr>
  16903. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16904. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16905. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16906. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16907. </file>
  16908. <file name="style.css">
  16909. .strike {
  16910. text-decoration: line-through;
  16911. }
  16912. .bold {
  16913. font-weight: bold;
  16914. }
  16915. .red {
  16916. color: red;
  16917. }
  16918. </file>
  16919. <file name="protractor.js" type="protractor">
  16920. var ps = element.all(by.css('p'));
  16921. it('should let you toggle the class', function() {
  16922. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16923. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16924. element(by.model('important')).click();
  16925. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16926. element(by.model('error')).click();
  16927. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16928. });
  16929. it('should let you toggle string example', function() {
  16930. expect(ps.get(1).getAttribute('class')).toBe('');
  16931. element(by.model('style')).clear();
  16932. element(by.model('style')).sendKeys('red');
  16933. expect(ps.get(1).getAttribute('class')).toBe('red');
  16934. });
  16935. it('array example should have 3 classes', function() {
  16936. expect(ps.last().getAttribute('class')).toBe('');
  16937. element(by.model('style1')).sendKeys('bold');
  16938. element(by.model('style2')).sendKeys('strike');
  16939. element(by.model('style3')).sendKeys('red');
  16940. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16941. });
  16942. </file>
  16943. </example>
  16944. ## Animations
  16945. The example below demonstrates how to perform animations using ngClass.
  16946. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  16947. <file name="index.html">
  16948. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  16949. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  16950. <br>
  16951. <span class="base-class" ng-class="myVar">Sample Text</span>
  16952. </file>
  16953. <file name="style.css">
  16954. .base-class {
  16955. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16956. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16957. }
  16958. .base-class.my-class {
  16959. color: red;
  16960. font-size:3em;
  16961. }
  16962. </file>
  16963. <file name="protractor.js" type="protractor">
  16964. it('should check ng-class', function() {
  16965. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16966. toMatch(/my-class/);
  16967. element(by.id('setbtn')).click();
  16968. expect(element(by.css('.base-class')).getAttribute('class')).
  16969. toMatch(/my-class/);
  16970. element(by.id('clearbtn')).click();
  16971. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16972. toMatch(/my-class/);
  16973. });
  16974. </file>
  16975. </example>
  16976. ## ngClass and pre-existing CSS3 Transitions/Animations
  16977. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  16978. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  16979. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  16980. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  16981. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  16982. */
  16983. var ngClassDirective = classDirective('', true);
  16984. /**
  16985. * @ngdoc directive
  16986. * @name ngClassOdd
  16987. * @restrict AC
  16988. *
  16989. * @description
  16990. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16991. * {@link ng.directive:ngClass ngClass}, except they work in
  16992. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16993. *
  16994. * This directive can be applied only within the scope of an
  16995. * {@link ng.directive:ngRepeat ngRepeat}.
  16996. *
  16997. * @element ANY
  16998. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  16999. * of the evaluation can be a string representing space delimited class names or an array.
  17000. *
  17001. * @example
  17002. <example>
  17003. <file name="index.html">
  17004. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17005. <li ng-repeat="name in names">
  17006. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17007. {{name}}
  17008. </span>
  17009. </li>
  17010. </ol>
  17011. </file>
  17012. <file name="style.css">
  17013. .odd {
  17014. color: red;
  17015. }
  17016. .even {
  17017. color: blue;
  17018. }
  17019. </file>
  17020. <file name="protractor.js" type="protractor">
  17021. it('should check ng-class-odd and ng-class-even', function() {
  17022. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17023. toMatch(/odd/);
  17024. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17025. toMatch(/even/);
  17026. });
  17027. </file>
  17028. </example>
  17029. */
  17030. var ngClassOddDirective = classDirective('Odd', 0);
  17031. /**
  17032. * @ngdoc directive
  17033. * @name ngClassEven
  17034. * @restrict AC
  17035. *
  17036. * @description
  17037. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  17038. * {@link ng.directive:ngClass ngClass}, except they work in
  17039. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  17040. *
  17041. * This directive can be applied only within the scope of an
  17042. * {@link ng.directive:ngRepeat ngRepeat}.
  17043. *
  17044. * @element ANY
  17045. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  17046. * result of the evaluation can be a string representing space delimited class names or an array.
  17047. *
  17048. * @example
  17049. <example>
  17050. <file name="index.html">
  17051. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  17052. <li ng-repeat="name in names">
  17053. <span ng-class-odd="'odd'" ng-class-even="'even'">
  17054. {{name}} &nbsp; &nbsp; &nbsp;
  17055. </span>
  17056. </li>
  17057. </ol>
  17058. </file>
  17059. <file name="style.css">
  17060. .odd {
  17061. color: red;
  17062. }
  17063. .even {
  17064. color: blue;
  17065. }
  17066. </file>
  17067. <file name="protractor.js" type="protractor">
  17068. it('should check ng-class-odd and ng-class-even', function() {
  17069. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  17070. toMatch(/odd/);
  17071. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  17072. toMatch(/even/);
  17073. });
  17074. </file>
  17075. </example>
  17076. */
  17077. var ngClassEvenDirective = classDirective('Even', 1);
  17078. /**
  17079. * @ngdoc directive
  17080. * @name ngCloak
  17081. * @restrict AC
  17082. *
  17083. * @description
  17084. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  17085. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  17086. * directive to avoid the undesirable flicker effect caused by the html template display.
  17087. *
  17088. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  17089. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  17090. * of the browser view.
  17091. *
  17092. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  17093. * `angular.min.js`.
  17094. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17095. *
  17096. * ```css
  17097. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  17098. * display: none !important;
  17099. * }
  17100. * ```
  17101. *
  17102. * When this css rule is loaded by the browser, all html elements (including their children) that
  17103. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  17104. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  17105. * the compiled element visible.
  17106. *
  17107. * For the best result, the `angular.js` script must be loaded in the head section of the html
  17108. * document; alternatively, the css rule above must be included in the external stylesheet of the
  17109. * application.
  17110. *
  17111. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  17112. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  17113. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  17114. *
  17115. * @element ANY
  17116. *
  17117. * @example
  17118. <example>
  17119. <file name="index.html">
  17120. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  17121. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  17122. </file>
  17123. <file name="protractor.js" type="protractor">
  17124. it('should remove the template directive and css class', function() {
  17125. expect($('#template1').getAttribute('ng-cloak')).
  17126. toBeNull();
  17127. expect($('#template2').getAttribute('ng-cloak')).
  17128. toBeNull();
  17129. });
  17130. </file>
  17131. </example>
  17132. *
  17133. */
  17134. var ngCloakDirective = ngDirective({
  17135. compile: function(element, attr) {
  17136. attr.$set('ngCloak', undefined);
  17137. element.removeClass('ng-cloak');
  17138. }
  17139. });
  17140. /**
  17141. * @ngdoc directive
  17142. * @name ngController
  17143. *
  17144. * @description
  17145. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  17146. * supports the principles behind the Model-View-Controller design pattern.
  17147. *
  17148. * MVC components in angular:
  17149. *
  17150. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  17151. * are accessed through bindings.
  17152. * * View — The template (HTML with data bindings) that is rendered into the View.
  17153. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  17154. * logic behind the application to decorate the scope with functions and values
  17155. *
  17156. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  17157. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  17158. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  17159. * and executed twice.
  17160. *
  17161. * @element ANY
  17162. * @scope
  17163. * @priority 500
  17164. * @param {expression} ngController Name of a globally accessible constructor function or an
  17165. * {@link guide/expression expression} that on the current scope evaluates to a
  17166. * constructor function. The controller instance can be published into a scope property
  17167. * by specifying `as propertyName`.
  17168. *
  17169. * @example
  17170. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  17171. * greeting are methods declared on the controller (see source tab). These methods can
  17172. * easily be called from the angular markup. Any changes to the data are automatically reflected
  17173. * in the View without the need for a manual update.
  17174. *
  17175. * Two different declaration styles are included below:
  17176. *
  17177. * * one binds methods and properties directly onto the controller using `this`:
  17178. * `ng-controller="SettingsController1 as settings"`
  17179. * * one injects `$scope` into the controller:
  17180. * `ng-controller="SettingsController2"`
  17181. *
  17182. * The second option is more common in the Angular community, and is generally used in boilerplates
  17183. * and in this guide. However, there are advantages to binding properties directly to the controller
  17184. * and avoiding scope.
  17185. *
  17186. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  17187. * multiple controllers apply to an element.
  17188. * * If you are writing your controllers as classes you have easier access to the properties and
  17189. * methods, which will appear on the scope, from inside the controller code.
  17190. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  17191. * inheritance masking primitives.
  17192. *
  17193. * This example demonstrates the `controller as` syntax.
  17194. *
  17195. * <example name="ngControllerAs" module="controllerAsExample">
  17196. * <file name="index.html">
  17197. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  17198. * Name: <input type="text" ng-model="settings.name"/>
  17199. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  17200. * Contact:
  17201. * <ul>
  17202. * <li ng-repeat="contact in settings.contacts">
  17203. * <select ng-model="contact.type">
  17204. * <option>phone</option>
  17205. * <option>email</option>
  17206. * </select>
  17207. * <input type="text" ng-model="contact.value"/>
  17208. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  17209. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  17210. * </li>
  17211. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  17212. * </ul>
  17213. * </div>
  17214. * </file>
  17215. * <file name="app.js">
  17216. * angular.module('controllerAsExample', [])
  17217. * .controller('SettingsController1', SettingsController1);
  17218. *
  17219. * function SettingsController1() {
  17220. * this.name = "John Smith";
  17221. * this.contacts = [
  17222. * {type: 'phone', value: '408 555 1212'},
  17223. * {type: 'email', value: 'john.smith@example.org'} ];
  17224. * }
  17225. *
  17226. * SettingsController1.prototype.greet = function() {
  17227. * alert(this.name);
  17228. * };
  17229. *
  17230. * SettingsController1.prototype.addContact = function() {
  17231. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  17232. * };
  17233. *
  17234. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  17235. * var index = this.contacts.indexOf(contactToRemove);
  17236. * this.contacts.splice(index, 1);
  17237. * };
  17238. *
  17239. * SettingsController1.prototype.clearContact = function(contact) {
  17240. * contact.type = 'phone';
  17241. * contact.value = '';
  17242. * };
  17243. * </file>
  17244. * <file name="protractor.js" type="protractor">
  17245. * it('should check controller as', function() {
  17246. * var container = element(by.id('ctrl-as-exmpl'));
  17247. * expect(container.element(by.model('settings.name'))
  17248. * .getAttribute('value')).toBe('John Smith');
  17249. *
  17250. * var firstRepeat =
  17251. * container.element(by.repeater('contact in settings.contacts').row(0));
  17252. * var secondRepeat =
  17253. * container.element(by.repeater('contact in settings.contacts').row(1));
  17254. *
  17255. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17256. * .toBe('408 555 1212');
  17257. *
  17258. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17259. * .toBe('john.smith@example.org');
  17260. *
  17261. * firstRepeat.element(by.linkText('clear')).click();
  17262. *
  17263. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17264. * .toBe('');
  17265. *
  17266. * container.element(by.linkText('add')).click();
  17267. *
  17268. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  17269. * .element(by.model('contact.value'))
  17270. * .getAttribute('value'))
  17271. * .toBe('yourname@example.org');
  17272. * });
  17273. * </file>
  17274. * </example>
  17275. *
  17276. * This example demonstrates the "attach to `$scope`" style of controller.
  17277. *
  17278. * <example name="ngController" module="controllerExample">
  17279. * <file name="index.html">
  17280. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  17281. * Name: <input type="text" ng-model="name"/>
  17282. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  17283. * Contact:
  17284. * <ul>
  17285. * <li ng-repeat="contact in contacts">
  17286. * <select ng-model="contact.type">
  17287. * <option>phone</option>
  17288. * <option>email</option>
  17289. * </select>
  17290. * <input type="text" ng-model="contact.value"/>
  17291. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  17292. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  17293. * </li>
  17294. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  17295. * </ul>
  17296. * </div>
  17297. * </file>
  17298. * <file name="app.js">
  17299. * angular.module('controllerExample', [])
  17300. * .controller('SettingsController2', ['$scope', SettingsController2]);
  17301. *
  17302. * function SettingsController2($scope) {
  17303. * $scope.name = "John Smith";
  17304. * $scope.contacts = [
  17305. * {type:'phone', value:'408 555 1212'},
  17306. * {type:'email', value:'john.smith@example.org'} ];
  17307. *
  17308. * $scope.greet = function() {
  17309. * alert($scope.name);
  17310. * };
  17311. *
  17312. * $scope.addContact = function() {
  17313. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  17314. * };
  17315. *
  17316. * $scope.removeContact = function(contactToRemove) {
  17317. * var index = $scope.contacts.indexOf(contactToRemove);
  17318. * $scope.contacts.splice(index, 1);
  17319. * };
  17320. *
  17321. * $scope.clearContact = function(contact) {
  17322. * contact.type = 'phone';
  17323. * contact.value = '';
  17324. * };
  17325. * }
  17326. * </file>
  17327. * <file name="protractor.js" type="protractor">
  17328. * it('should check controller', function() {
  17329. * var container = element(by.id('ctrl-exmpl'));
  17330. *
  17331. * expect(container.element(by.model('name'))
  17332. * .getAttribute('value')).toBe('John Smith');
  17333. *
  17334. * var firstRepeat =
  17335. * container.element(by.repeater('contact in contacts').row(0));
  17336. * var secondRepeat =
  17337. * container.element(by.repeater('contact in contacts').row(1));
  17338. *
  17339. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17340. * .toBe('408 555 1212');
  17341. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17342. * .toBe('john.smith@example.org');
  17343. *
  17344. * firstRepeat.element(by.linkText('clear')).click();
  17345. *
  17346. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17347. * .toBe('');
  17348. *
  17349. * container.element(by.linkText('add')).click();
  17350. *
  17351. * expect(container.element(by.repeater('contact in contacts').row(2))
  17352. * .element(by.model('contact.value'))
  17353. * .getAttribute('value'))
  17354. * .toBe('yourname@example.org');
  17355. * });
  17356. * </file>
  17357. *</example>
  17358. */
  17359. var ngControllerDirective = [function() {
  17360. return {
  17361. scope: true,
  17362. controller: '@',
  17363. priority: 500
  17364. };
  17365. }];
  17366. /**
  17367. * @ngdoc directive
  17368. * @name ngCsp
  17369. *
  17370. * @element html
  17371. * @description
  17372. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  17373. *
  17374. * This is necessary when developing things like Google Chrome Extensions.
  17375. *
  17376. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  17377. * For Angular to be CSP compatible there are only two things that we need to do differently:
  17378. *
  17379. * - don't use `Function` constructor to generate optimized value getters
  17380. * - don't inject custom stylesheet into the document
  17381. *
  17382. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  17383. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  17384. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  17385. * be raised.
  17386. *
  17387. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  17388. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  17389. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  17390. *
  17391. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  17392. * autodetection however triggers a CSP error to be logged in the console:
  17393. *
  17394. * ```
  17395. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  17396. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  17397. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  17398. * ```
  17399. *
  17400. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  17401. * directive on the root element of the application or on the `angular.js` script tag, whichever
  17402. * appears first in the html document.
  17403. *
  17404. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  17405. *
  17406. * @example
  17407. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  17408. ```html
  17409. <!doctype html>
  17410. <html ng-app ng-csp>
  17411. ...
  17412. ...
  17413. </html>
  17414. ```
  17415. */
  17416. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  17417. // bootstrap the system (before $parse is instantiated), for this reason we just have
  17418. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  17419. /**
  17420. * @ngdoc directive
  17421. * @name ngClick
  17422. *
  17423. * @description
  17424. * The ngClick directive allows you to specify custom behavior when
  17425. * an element is clicked.
  17426. *
  17427. * @element ANY
  17428. * @priority 0
  17429. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  17430. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  17431. *
  17432. * @example
  17433. <example>
  17434. <file name="index.html">
  17435. <button ng-click="count = count + 1" ng-init="count=0">
  17436. Increment
  17437. </button>
  17438. <span>
  17439. count: {{count}}
  17440. <span>
  17441. </file>
  17442. <file name="protractor.js" type="protractor">
  17443. it('should check ng-click', function() {
  17444. expect(element(by.binding('count')).getText()).toMatch('0');
  17445. element(by.css('button')).click();
  17446. expect(element(by.binding('count')).getText()).toMatch('1');
  17447. });
  17448. </file>
  17449. </example>
  17450. */
  17451. /*
  17452. * A collection of directives that allows creation of custom event handlers that are defined as
  17453. * angular expressions and are compiled and executed within the current scope.
  17454. */
  17455. var ngEventDirectives = {};
  17456. // For events that might fire synchronously during DOM manipulation
  17457. // we need to execute their event handlers asynchronously using $evalAsync,
  17458. // so that they are not executed in an inconsistent state.
  17459. var forceAsyncEvents = {
  17460. 'blur': true,
  17461. 'focus': true
  17462. };
  17463. forEach(
  17464. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  17465. function(eventName) {
  17466. var directiveName = directiveNormalize('ng-' + eventName);
  17467. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  17468. return {
  17469. compile: function($element, attr) {
  17470. // We expose the powerful $event object on the scope that provides access to the Window,
  17471. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  17472. // checks at the cost of speed since event handler expressions are not executed as
  17473. // frequently as regular change detection.
  17474. var fn = $parse(attr[directiveName], /* expensiveChecks */ true);
  17475. return function ngEventHandler(scope, element) {
  17476. element.on(eventName, function(event) {
  17477. var callback = function() {
  17478. fn(scope, {$event:event});
  17479. };
  17480. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  17481. scope.$evalAsync(callback);
  17482. } else {
  17483. scope.$apply(callback);
  17484. }
  17485. });
  17486. };
  17487. }
  17488. };
  17489. }];
  17490. }
  17491. );
  17492. /**
  17493. * @ngdoc directive
  17494. * @name ngDblclick
  17495. *
  17496. * @description
  17497. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  17498. *
  17499. * @element ANY
  17500. * @priority 0
  17501. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  17502. * a dblclick. (The Event object is available as `$event`)
  17503. *
  17504. * @example
  17505. <example>
  17506. <file name="index.html">
  17507. <button ng-dblclick="count = count + 1" ng-init="count=0">
  17508. Increment (on double click)
  17509. </button>
  17510. count: {{count}}
  17511. </file>
  17512. </example>
  17513. */
  17514. /**
  17515. * @ngdoc directive
  17516. * @name ngMousedown
  17517. *
  17518. * @description
  17519. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  17520. *
  17521. * @element ANY
  17522. * @priority 0
  17523. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  17524. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  17525. *
  17526. * @example
  17527. <example>
  17528. <file name="index.html">
  17529. <button ng-mousedown="count = count + 1" ng-init="count=0">
  17530. Increment (on mouse down)
  17531. </button>
  17532. count: {{count}}
  17533. </file>
  17534. </example>
  17535. */
  17536. /**
  17537. * @ngdoc directive
  17538. * @name ngMouseup
  17539. *
  17540. * @description
  17541. * Specify custom behavior on mouseup event.
  17542. *
  17543. * @element ANY
  17544. * @priority 0
  17545. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  17546. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  17547. *
  17548. * @example
  17549. <example>
  17550. <file name="index.html">
  17551. <button ng-mouseup="count = count + 1" ng-init="count=0">
  17552. Increment (on mouse up)
  17553. </button>
  17554. count: {{count}}
  17555. </file>
  17556. </example>
  17557. */
  17558. /**
  17559. * @ngdoc directive
  17560. * @name ngMouseover
  17561. *
  17562. * @description
  17563. * Specify custom behavior on mouseover event.
  17564. *
  17565. * @element ANY
  17566. * @priority 0
  17567. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  17568. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  17569. *
  17570. * @example
  17571. <example>
  17572. <file name="index.html">
  17573. <button ng-mouseover="count = count + 1" ng-init="count=0">
  17574. Increment (when mouse is over)
  17575. </button>
  17576. count: {{count}}
  17577. </file>
  17578. </example>
  17579. */
  17580. /**
  17581. * @ngdoc directive
  17582. * @name ngMouseenter
  17583. *
  17584. * @description
  17585. * Specify custom behavior on mouseenter event.
  17586. *
  17587. * @element ANY
  17588. * @priority 0
  17589. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  17590. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  17591. *
  17592. * @example
  17593. <example>
  17594. <file name="index.html">
  17595. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  17596. Increment (when mouse enters)
  17597. </button>
  17598. count: {{count}}
  17599. </file>
  17600. </example>
  17601. */
  17602. /**
  17603. * @ngdoc directive
  17604. * @name ngMouseleave
  17605. *
  17606. * @description
  17607. * Specify custom behavior on mouseleave event.
  17608. *
  17609. * @element ANY
  17610. * @priority 0
  17611. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17612. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17613. *
  17614. * @example
  17615. <example>
  17616. <file name="index.html">
  17617. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17618. Increment (when mouse leaves)
  17619. </button>
  17620. count: {{count}}
  17621. </file>
  17622. </example>
  17623. */
  17624. /**
  17625. * @ngdoc directive
  17626. * @name ngMousemove
  17627. *
  17628. * @description
  17629. * Specify custom behavior on mousemove event.
  17630. *
  17631. * @element ANY
  17632. * @priority 0
  17633. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17634. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17635. *
  17636. * @example
  17637. <example>
  17638. <file name="index.html">
  17639. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17640. Increment (when mouse moves)
  17641. </button>
  17642. count: {{count}}
  17643. </file>
  17644. </example>
  17645. */
  17646. /**
  17647. * @ngdoc directive
  17648. * @name ngKeydown
  17649. *
  17650. * @description
  17651. * Specify custom behavior on keydown event.
  17652. *
  17653. * @element ANY
  17654. * @priority 0
  17655. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17656. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17657. *
  17658. * @example
  17659. <example>
  17660. <file name="index.html">
  17661. <input ng-keydown="count = count + 1" ng-init="count=0">
  17662. key down count: {{count}}
  17663. </file>
  17664. </example>
  17665. */
  17666. /**
  17667. * @ngdoc directive
  17668. * @name ngKeyup
  17669. *
  17670. * @description
  17671. * Specify custom behavior on keyup event.
  17672. *
  17673. * @element ANY
  17674. * @priority 0
  17675. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17676. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17677. *
  17678. * @example
  17679. <example>
  17680. <file name="index.html">
  17681. <p>Typing in the input box below updates the key count</p>
  17682. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  17683. <p>Typing in the input box below updates the keycode</p>
  17684. <input ng-keyup="event=$event">
  17685. <p>event keyCode: {{ event.keyCode }}</p>
  17686. <p>event altKey: {{ event.altKey }}</p>
  17687. </file>
  17688. </example>
  17689. */
  17690. /**
  17691. * @ngdoc directive
  17692. * @name ngKeypress
  17693. *
  17694. * @description
  17695. * Specify custom behavior on keypress event.
  17696. *
  17697. * @element ANY
  17698. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17699. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17700. * and can be interrogated for keyCode, altKey, etc.)
  17701. *
  17702. * @example
  17703. <example>
  17704. <file name="index.html">
  17705. <input ng-keypress="count = count + 1" ng-init="count=0">
  17706. key press count: {{count}}
  17707. </file>
  17708. </example>
  17709. */
  17710. /**
  17711. * @ngdoc directive
  17712. * @name ngSubmit
  17713. *
  17714. * @description
  17715. * Enables binding angular expressions to onsubmit events.
  17716. *
  17717. * Additionally it prevents the default action (which for form means sending the request to the
  17718. * server and reloading the current page), but only if the form does not contain `action`,
  17719. * `data-action`, or `x-action` attributes.
  17720. *
  17721. * <div class="alert alert-warning">
  17722. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  17723. * `ngSubmit` handlers together. See the
  17724. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  17725. * for a detailed discussion of when `ngSubmit` may be triggered.
  17726. * </div>
  17727. *
  17728. * @element form
  17729. * @priority 0
  17730. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17731. * ({@link guide/expression#-event- Event object is available as `$event`})
  17732. *
  17733. * @example
  17734. <example module="submitExample">
  17735. <file name="index.html">
  17736. <script>
  17737. angular.module('submitExample', [])
  17738. .controller('ExampleController', ['$scope', function($scope) {
  17739. $scope.list = [];
  17740. $scope.text = 'hello';
  17741. $scope.submit = function() {
  17742. if ($scope.text) {
  17743. $scope.list.push(this.text);
  17744. $scope.text = '';
  17745. }
  17746. };
  17747. }]);
  17748. </script>
  17749. <form ng-submit="submit()" ng-controller="ExampleController">
  17750. Enter text and hit enter:
  17751. <input type="text" ng-model="text" name="text" />
  17752. <input type="submit" id="submit" value="Submit" />
  17753. <pre>list={{list}}</pre>
  17754. </form>
  17755. </file>
  17756. <file name="protractor.js" type="protractor">
  17757. it('should check ng-submit', function() {
  17758. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17759. element(by.css('#submit')).click();
  17760. expect(element(by.binding('list')).getText()).toContain('hello');
  17761. expect(element(by.model('text')).getAttribute('value')).toBe('');
  17762. });
  17763. it('should ignore empty strings', function() {
  17764. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17765. element(by.css('#submit')).click();
  17766. element(by.css('#submit')).click();
  17767. expect(element(by.binding('list')).getText()).toContain('hello');
  17768. });
  17769. </file>
  17770. </example>
  17771. */
  17772. /**
  17773. * @ngdoc directive
  17774. * @name ngFocus
  17775. *
  17776. * @description
  17777. * Specify custom behavior on focus event.
  17778. *
  17779. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  17780. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17781. * during an `$apply` to ensure a consistent state.
  17782. *
  17783. * @element window, input, select, textarea, a
  17784. * @priority 0
  17785. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17786. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17787. *
  17788. * @example
  17789. * See {@link ng.directive:ngClick ngClick}
  17790. */
  17791. /**
  17792. * @ngdoc directive
  17793. * @name ngBlur
  17794. *
  17795. * @description
  17796. * Specify custom behavior on blur event.
  17797. *
  17798. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  17799. * an element has lost focus.
  17800. *
  17801. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  17802. * (e.g. removing a focussed input),
  17803. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  17804. * during an `$apply` to ensure a consistent state.
  17805. *
  17806. * @element window, input, select, textarea, a
  17807. * @priority 0
  17808. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17809. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17810. *
  17811. * @example
  17812. * See {@link ng.directive:ngClick ngClick}
  17813. */
  17814. /**
  17815. * @ngdoc directive
  17816. * @name ngCopy
  17817. *
  17818. * @description
  17819. * Specify custom behavior on copy event.
  17820. *
  17821. * @element window, input, select, textarea, a
  17822. * @priority 0
  17823. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17824. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17825. *
  17826. * @example
  17827. <example>
  17828. <file name="index.html">
  17829. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17830. copied: {{copied}}
  17831. </file>
  17832. </example>
  17833. */
  17834. /**
  17835. * @ngdoc directive
  17836. * @name ngCut
  17837. *
  17838. * @description
  17839. * Specify custom behavior on cut event.
  17840. *
  17841. * @element window, input, select, textarea, a
  17842. * @priority 0
  17843. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17844. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17845. *
  17846. * @example
  17847. <example>
  17848. <file name="index.html">
  17849. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17850. cut: {{cut}}
  17851. </file>
  17852. </example>
  17853. */
  17854. /**
  17855. * @ngdoc directive
  17856. * @name ngPaste
  17857. *
  17858. * @description
  17859. * Specify custom behavior on paste event.
  17860. *
  17861. * @element window, input, select, textarea, a
  17862. * @priority 0
  17863. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17864. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17865. *
  17866. * @example
  17867. <example>
  17868. <file name="index.html">
  17869. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17870. pasted: {{paste}}
  17871. </file>
  17872. </example>
  17873. */
  17874. /**
  17875. * @ngdoc directive
  17876. * @name ngIf
  17877. * @restrict A
  17878. *
  17879. * @description
  17880. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17881. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17882. * value then the element is removed from the DOM, otherwise a clone of the
  17883. * element is reinserted into the DOM.
  17884. *
  17885. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17886. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17887. * case when this difference is significant is when using css selectors that rely on an element's
  17888. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17889. *
  17890. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17891. * is created when the element is restored. The scope created within `ngIf` inherits from
  17892. * its parent scope using
  17893. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  17894. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17895. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17896. * variable within the child scope will override (hide) the value in the parent scope.
  17897. *
  17898. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17899. * is if an element's class attribute is directly modified after it's compiled, using something like
  17900. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17901. * the added class will be lost because the original compiled state is used to regenerate the element.
  17902. *
  17903. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17904. * and `leave` effects.
  17905. *
  17906. * @animations
  17907. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  17908. * leave - happens just before the `ngIf` contents are removed from the DOM
  17909. *
  17910. * @element ANY
  17911. * @scope
  17912. * @priority 600
  17913. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17914. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17915. * element is added to the DOM tree.
  17916. *
  17917. * @example
  17918. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17919. <file name="index.html">
  17920. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17921. Show when checked:
  17922. <span ng-if="checked" class="animate-if">
  17923. I'm removed when the checkbox is unchecked.
  17924. </span>
  17925. </file>
  17926. <file name="animations.css">
  17927. .animate-if {
  17928. background:white;
  17929. border:1px solid black;
  17930. padding:10px;
  17931. }
  17932. .animate-if.ng-enter, .animate-if.ng-leave {
  17933. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17934. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17935. }
  17936. .animate-if.ng-enter,
  17937. .animate-if.ng-leave.ng-leave-active {
  17938. opacity:0;
  17939. }
  17940. .animate-if.ng-leave,
  17941. .animate-if.ng-enter.ng-enter-active {
  17942. opacity:1;
  17943. }
  17944. </file>
  17945. </example>
  17946. */
  17947. var ngIfDirective = ['$animate', function($animate) {
  17948. return {
  17949. transclude: 'element',
  17950. priority: 600,
  17951. terminal: true,
  17952. restrict: 'A',
  17953. $$tlb: true,
  17954. link: function ($scope, $element, $attr, ctrl, $transclude) {
  17955. var block, childScope, previousElements;
  17956. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  17957. if (toBoolean(value)) {
  17958. if (!childScope) {
  17959. childScope = $scope.$new();
  17960. $transclude(childScope, function (clone) {
  17961. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  17962. // Note: We only need the first/last node of the cloned nodes.
  17963. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17964. // by a directive with templateUrl when its template arrives.
  17965. block = {
  17966. clone: clone
  17967. };
  17968. $animate.enter(clone, $element.parent(), $element);
  17969. });
  17970. }
  17971. } else {
  17972. if(previousElements) {
  17973. previousElements.remove();
  17974. previousElements = null;
  17975. }
  17976. if(childScope) {
  17977. childScope.$destroy();
  17978. childScope = null;
  17979. }
  17980. if(block) {
  17981. previousElements = getBlockElements(block.clone);
  17982. $animate.leave(previousElements, function() {
  17983. previousElements = null;
  17984. });
  17985. block = null;
  17986. }
  17987. }
  17988. });
  17989. }
  17990. };
  17991. }];
  17992. /**
  17993. * @ngdoc directive
  17994. * @name ngInclude
  17995. * @restrict ECA
  17996. *
  17997. * @description
  17998. * Fetches, compiles and includes an external HTML fragment.
  17999. *
  18000. * By default, the template URL is restricted to the same domain and protocol as the
  18001. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  18002. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  18003. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  18004. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  18005. * ng.$sce Strict Contextual Escaping}.
  18006. *
  18007. * In addition, the browser's
  18008. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  18009. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  18010. * policy may further restrict whether the template is successfully loaded.
  18011. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  18012. * access on some browsers.
  18013. *
  18014. * @animations
  18015. * enter - animation is used to bring new content into the browser.
  18016. * leave - animation is used to animate existing content away.
  18017. *
  18018. * The enter and leave animation occur concurrently.
  18019. *
  18020. * @scope
  18021. * @priority 400
  18022. *
  18023. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  18024. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  18025. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  18026. *
  18027. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  18028. * $anchorScroll} to scroll the viewport after the content is loaded.
  18029. *
  18030. * - If the attribute is not set, disable scrolling.
  18031. * - If the attribute is set without value, enable scrolling.
  18032. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  18033. *
  18034. * @example
  18035. <example module="includeExample" deps="angular-animate.js" animations="true">
  18036. <file name="index.html">
  18037. <div ng-controller="ExampleController">
  18038. <select ng-model="template" ng-options="t.name for t in templates">
  18039. <option value="">(blank)</option>
  18040. </select>
  18041. url of the template: <tt>{{template.url}}</tt>
  18042. <hr/>
  18043. <div class="slide-animate-container">
  18044. <div class="slide-animate" ng-include="template.url"></div>
  18045. </div>
  18046. </div>
  18047. </file>
  18048. <file name="script.js">
  18049. angular.module('includeExample', ['ngAnimate'])
  18050. .controller('ExampleController', ['$scope', function($scope) {
  18051. $scope.templates =
  18052. [ { name: 'template1.html', url: 'template1.html'},
  18053. { name: 'template2.html', url: 'template2.html'} ];
  18054. $scope.template = $scope.templates[0];
  18055. }]);
  18056. </file>
  18057. <file name="template1.html">
  18058. Content of template1.html
  18059. </file>
  18060. <file name="template2.html">
  18061. Content of template2.html
  18062. </file>
  18063. <file name="animations.css">
  18064. .slide-animate-container {
  18065. position:relative;
  18066. background:white;
  18067. border:1px solid black;
  18068. height:40px;
  18069. overflow:hidden;
  18070. }
  18071. .slide-animate {
  18072. padding:10px;
  18073. }
  18074. .slide-animate.ng-enter, .slide-animate.ng-leave {
  18075. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18076. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18077. position:absolute;
  18078. top:0;
  18079. left:0;
  18080. right:0;
  18081. bottom:0;
  18082. display:block;
  18083. padding:10px;
  18084. }
  18085. .slide-animate.ng-enter {
  18086. top:-50px;
  18087. }
  18088. .slide-animate.ng-enter.ng-enter-active {
  18089. top:0;
  18090. }
  18091. .slide-animate.ng-leave {
  18092. top:0;
  18093. }
  18094. .slide-animate.ng-leave.ng-leave-active {
  18095. top:50px;
  18096. }
  18097. </file>
  18098. <file name="protractor.js" type="protractor">
  18099. var templateSelect = element(by.model('template'));
  18100. var includeElem = element(by.css('[ng-include]'));
  18101. it('should load template1.html', function() {
  18102. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  18103. });
  18104. it('should load template2.html', function() {
  18105. if (browser.params.browser == 'firefox') {
  18106. // Firefox can't handle using selects
  18107. // See https://github.com/angular/protractor/issues/480
  18108. return;
  18109. }
  18110. templateSelect.click();
  18111. templateSelect.all(by.css('option')).get(2).click();
  18112. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  18113. });
  18114. it('should change to blank', function() {
  18115. if (browser.params.browser == 'firefox') {
  18116. // Firefox can't handle using selects
  18117. return;
  18118. }
  18119. templateSelect.click();
  18120. templateSelect.all(by.css('option')).get(0).click();
  18121. expect(includeElem.isPresent()).toBe(false);
  18122. });
  18123. </file>
  18124. </example>
  18125. */
  18126. /**
  18127. * @ngdoc event
  18128. * @name ngInclude#$includeContentRequested
  18129. * @eventType emit on the scope ngInclude was declared in
  18130. * @description
  18131. * Emitted every time the ngInclude content is requested.
  18132. */
  18133. /**
  18134. * @ngdoc event
  18135. * @name ngInclude#$includeContentLoaded
  18136. * @eventType emit on the current ngInclude scope
  18137. * @description
  18138. * Emitted every time the ngInclude content is reloaded.
  18139. */
  18140. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  18141. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  18142. return {
  18143. restrict: 'ECA',
  18144. priority: 400,
  18145. terminal: true,
  18146. transclude: 'element',
  18147. controller: angular.noop,
  18148. compile: function(element, attr) {
  18149. var srcExp = attr.ngInclude || attr.src,
  18150. onloadExp = attr.onload || '',
  18151. autoScrollExp = attr.autoscroll;
  18152. return function(scope, $element, $attr, ctrl, $transclude) {
  18153. var changeCounter = 0,
  18154. currentScope,
  18155. previousElement,
  18156. currentElement;
  18157. var cleanupLastIncludeContent = function() {
  18158. if(previousElement) {
  18159. previousElement.remove();
  18160. previousElement = null;
  18161. }
  18162. if(currentScope) {
  18163. currentScope.$destroy();
  18164. currentScope = null;
  18165. }
  18166. if(currentElement) {
  18167. $animate.leave(currentElement, function() {
  18168. previousElement = null;
  18169. });
  18170. previousElement = currentElement;
  18171. currentElement = null;
  18172. }
  18173. };
  18174. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  18175. var afterAnimation = function() {
  18176. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  18177. $anchorScroll();
  18178. }
  18179. };
  18180. var thisChangeId = ++changeCounter;
  18181. if (src) {
  18182. $http.get(src, {cache: $templateCache}).success(function(response) {
  18183. if (thisChangeId !== changeCounter) return;
  18184. var newScope = scope.$new();
  18185. ctrl.template = response;
  18186. // Note: This will also link all children of ng-include that were contained in the original
  18187. // html. If that content contains controllers, ... they could pollute/change the scope.
  18188. // However, using ng-include on an element with additional content does not make sense...
  18189. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  18190. // function is called before linking the content, which would apply child
  18191. // directives to non existing elements.
  18192. var clone = $transclude(newScope, function(clone) {
  18193. cleanupLastIncludeContent();
  18194. $animate.enter(clone, null, $element, afterAnimation);
  18195. });
  18196. currentScope = newScope;
  18197. currentElement = clone;
  18198. currentScope.$emit('$includeContentLoaded');
  18199. scope.$eval(onloadExp);
  18200. }).error(function() {
  18201. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  18202. });
  18203. scope.$emit('$includeContentRequested');
  18204. } else {
  18205. cleanupLastIncludeContent();
  18206. ctrl.template = null;
  18207. }
  18208. });
  18209. };
  18210. }
  18211. };
  18212. }];
  18213. // This directive is called during the $transclude call of the first `ngInclude` directive.
  18214. // It will replace and compile the content of the element with the loaded template.
  18215. // We need this directive so that the element content is already filled when
  18216. // the link function of another directive on the same element as ngInclude
  18217. // is called.
  18218. var ngIncludeFillContentDirective = ['$compile',
  18219. function($compile) {
  18220. return {
  18221. restrict: 'ECA',
  18222. priority: -400,
  18223. require: 'ngInclude',
  18224. link: function(scope, $element, $attr, ctrl) {
  18225. $element.html(ctrl.template);
  18226. $compile($element.contents())(scope);
  18227. }
  18228. };
  18229. }];
  18230. /**
  18231. * @ngdoc directive
  18232. * @name ngInit
  18233. * @restrict AC
  18234. *
  18235. * @description
  18236. * The `ngInit` directive allows you to evaluate an expression in the
  18237. * current scope.
  18238. *
  18239. * <div class="alert alert-error">
  18240. * The only appropriate use of `ngInit` is for aliasing special properties of
  18241. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  18242. * should use {@link guide/controller controllers} rather than `ngInit`
  18243. * to initialize values on a scope.
  18244. * </div>
  18245. * <div class="alert alert-warning">
  18246. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  18247. * sure you have parenthesis for correct precedence:
  18248. * <pre class="prettyprint">
  18249. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  18250. * </pre>
  18251. * </div>
  18252. *
  18253. * @priority 450
  18254. *
  18255. * @element ANY
  18256. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  18257. *
  18258. * @example
  18259. <example module="initExample">
  18260. <file name="index.html">
  18261. <script>
  18262. angular.module('initExample', [])
  18263. .controller('ExampleController', ['$scope', function($scope) {
  18264. $scope.list = [['a', 'b'], ['c', 'd']];
  18265. }]);
  18266. </script>
  18267. <div ng-controller="ExampleController">
  18268. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  18269. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  18270. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  18271. </div>
  18272. </div>
  18273. </div>
  18274. </file>
  18275. <file name="protractor.js" type="protractor">
  18276. it('should alias index positions', function() {
  18277. var elements = element.all(by.css('.example-init'));
  18278. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  18279. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  18280. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  18281. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  18282. });
  18283. </file>
  18284. </example>
  18285. */
  18286. var ngInitDirective = ngDirective({
  18287. priority: 450,
  18288. compile: function() {
  18289. return {
  18290. pre: function(scope, element, attrs) {
  18291. scope.$eval(attrs.ngInit);
  18292. }
  18293. };
  18294. }
  18295. });
  18296. /**
  18297. * @ngdoc directive
  18298. * @name ngNonBindable
  18299. * @restrict AC
  18300. * @priority 1000
  18301. *
  18302. * @description
  18303. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  18304. * DOM element. This is useful if the element contains what appears to be Angular directives and
  18305. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  18306. * displays snippets of code, for instance.
  18307. *
  18308. * @element ANY
  18309. *
  18310. * @example
  18311. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  18312. * but the one wrapped in `ngNonBindable` is left alone.
  18313. *
  18314. * @example
  18315. <example>
  18316. <file name="index.html">
  18317. <div>Normal: {{1 + 2}}</div>
  18318. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  18319. </file>
  18320. <file name="protractor.js" type="protractor">
  18321. it('should check ng-non-bindable', function() {
  18322. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  18323. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  18324. });
  18325. </file>
  18326. </example>
  18327. */
  18328. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  18329. /**
  18330. * @ngdoc directive
  18331. * @name ngPluralize
  18332. * @restrict EA
  18333. *
  18334. * @description
  18335. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  18336. * These rules are bundled with angular.js, but can be overridden
  18337. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  18338. * by specifying the mappings between
  18339. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18340. * and the strings to be displayed.
  18341. *
  18342. * # Plural categories and explicit number rules
  18343. * There are two
  18344. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18345. * in Angular's default en-US locale: "one" and "other".
  18346. *
  18347. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  18348. * any number that is not 1), an explicit number rule can only match one number. For example, the
  18349. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  18350. * and explicit number rules throughout the rest of this documentation.
  18351. *
  18352. * # Configuring ngPluralize
  18353. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  18354. * You can also provide an optional attribute, `offset`.
  18355. *
  18356. * The value of the `count` attribute can be either a string or an {@link guide/expression
  18357. * Angular expression}; these are evaluated on the current scope for its bound value.
  18358. *
  18359. * The `when` attribute specifies the mappings between plural categories and the actual
  18360. * string to be displayed. The value of the attribute should be a JSON object.
  18361. *
  18362. * The following example shows how to configure ngPluralize:
  18363. *
  18364. * ```html
  18365. * <ng-pluralize count="personCount"
  18366. when="{'0': 'Nobody is viewing.',
  18367. * 'one': '1 person is viewing.',
  18368. * 'other': '{} people are viewing.'}">
  18369. * </ng-pluralize>
  18370. *```
  18371. *
  18372. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  18373. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  18374. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  18375. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  18376. * show "a dozen people are viewing".
  18377. *
  18378. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  18379. * into pluralized strings. In the previous example, Angular will replace `{}` with
  18380. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  18381. * for <span ng-non-bindable>{{numberExpression}}</span>.
  18382. *
  18383. * # Configuring ngPluralize with offset
  18384. * The `offset` attribute allows further customization of pluralized text, which can result in
  18385. * a better user experience. For example, instead of the message "4 people are viewing this document",
  18386. * you might display "John, Kate and 2 others are viewing this document".
  18387. * The offset attribute allows you to offset a number by any desired value.
  18388. * Let's take a look at an example:
  18389. *
  18390. * ```html
  18391. * <ng-pluralize count="personCount" offset=2
  18392. * when="{'0': 'Nobody is viewing.',
  18393. * '1': '{{person1}} is viewing.',
  18394. * '2': '{{person1}} and {{person2}} are viewing.',
  18395. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18396. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18397. * </ng-pluralize>
  18398. * ```
  18399. *
  18400. * Notice that we are still using two plural categories(one, other), but we added
  18401. * three explicit number rules 0, 1 and 2.
  18402. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  18403. * When three people view the document, no explicit number rule is found, so
  18404. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  18405. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  18406. * is shown.
  18407. *
  18408. * Note that when you specify offsets, you must provide explicit number rules for
  18409. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  18410. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  18411. * plural categories "one" and "other".
  18412. *
  18413. * @param {string|expression} count The variable to be bound to.
  18414. * @param {string} when The mapping between plural category to its corresponding strings.
  18415. * @param {number=} offset Offset to deduct from the total number.
  18416. *
  18417. * @example
  18418. <example module="pluralizeExample">
  18419. <file name="index.html">
  18420. <script>
  18421. angular.module('pluralizeExample', [])
  18422. .controller('ExampleController', ['$scope', function($scope) {
  18423. $scope.person1 = 'Igor';
  18424. $scope.person2 = 'Misko';
  18425. $scope.personCount = 1;
  18426. }]);
  18427. </script>
  18428. <div ng-controller="ExampleController">
  18429. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  18430. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  18431. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  18432. <!--- Example with simple pluralization rules for en locale --->
  18433. Without Offset:
  18434. <ng-pluralize count="personCount"
  18435. when="{'0': 'Nobody is viewing.',
  18436. 'one': '1 person is viewing.',
  18437. 'other': '{} people are viewing.'}">
  18438. </ng-pluralize><br>
  18439. <!--- Example with offset --->
  18440. With Offset(2):
  18441. <ng-pluralize count="personCount" offset=2
  18442. when="{'0': 'Nobody is viewing.',
  18443. '1': '{{person1}} is viewing.',
  18444. '2': '{{person1}} and {{person2}} are viewing.',
  18445. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18446. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18447. </ng-pluralize>
  18448. </div>
  18449. </file>
  18450. <file name="protractor.js" type="protractor">
  18451. it('should show correct pluralized string', function() {
  18452. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  18453. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18454. var countInput = element(by.model('personCount'));
  18455. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  18456. expect(withOffset.getText()).toEqual('Igor is viewing.');
  18457. countInput.clear();
  18458. countInput.sendKeys('0');
  18459. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  18460. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  18461. countInput.clear();
  18462. countInput.sendKeys('2');
  18463. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  18464. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  18465. countInput.clear();
  18466. countInput.sendKeys('3');
  18467. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  18468. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  18469. countInput.clear();
  18470. countInput.sendKeys('4');
  18471. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  18472. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  18473. });
  18474. it('should show data-bound names', function() {
  18475. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18476. var personCount = element(by.model('personCount'));
  18477. var person1 = element(by.model('person1'));
  18478. var person2 = element(by.model('person2'));
  18479. personCount.clear();
  18480. personCount.sendKeys('4');
  18481. person1.clear();
  18482. person1.sendKeys('Di');
  18483. person2.clear();
  18484. person2.sendKeys('Vojta');
  18485. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  18486. });
  18487. </file>
  18488. </example>
  18489. */
  18490. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  18491. var BRACE = /{}/g;
  18492. return {
  18493. restrict: 'EA',
  18494. link: function(scope, element, attr) {
  18495. var numberExp = attr.count,
  18496. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  18497. offset = attr.offset || 0,
  18498. whens = scope.$eval(whenExp) || {},
  18499. whensExpFns = {},
  18500. startSymbol = $interpolate.startSymbol(),
  18501. endSymbol = $interpolate.endSymbol(),
  18502. isWhen = /^when(Minus)?(.+)$/;
  18503. forEach(attr, function(expression, attributeName) {
  18504. if (isWhen.test(attributeName)) {
  18505. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  18506. element.attr(attr.$attr[attributeName]);
  18507. }
  18508. });
  18509. forEach(whens, function(expression, key) {
  18510. whensExpFns[key] =
  18511. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  18512. offset + endSymbol));
  18513. });
  18514. scope.$watch(function ngPluralizeWatch() {
  18515. var value = parseFloat(scope.$eval(numberExp));
  18516. if (!isNaN(value)) {
  18517. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  18518. //check it against pluralization rules in $locale service
  18519. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  18520. return whensExpFns[value](scope, element, true);
  18521. } else {
  18522. return '';
  18523. }
  18524. }, function ngPluralizeWatchAction(newVal) {
  18525. element.text(newVal);
  18526. });
  18527. }
  18528. };
  18529. }];
  18530. /**
  18531. * @ngdoc directive
  18532. * @name ngRepeat
  18533. *
  18534. * @description
  18535. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  18536. * instance gets its own scope, where the given loop variable is set to the current collection item,
  18537. * and `$index` is set to the item index or key.
  18538. *
  18539. * Special properties are exposed on the local scope of each template instance, including:
  18540. *
  18541. * | Variable | Type | Details |
  18542. * |-----------|-----------------|-----------------------------------------------------------------------------|
  18543. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  18544. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  18545. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  18546. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  18547. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  18548. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  18549. *
  18550. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  18551. * This may be useful when, for instance, nesting ngRepeats.
  18552. *
  18553. * # Special repeat start and end points
  18554. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  18555. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  18556. * 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)
  18557. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  18558. *
  18559. * The example below makes use of this feature:
  18560. * ```html
  18561. * <header ng-repeat-start="item in items">
  18562. * Header {{ item }}
  18563. * </header>
  18564. * <div class="body">
  18565. * Body {{ item }}
  18566. * </div>
  18567. * <footer ng-repeat-end>
  18568. * Footer {{ item }}
  18569. * </footer>
  18570. * ```
  18571. *
  18572. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  18573. * ```html
  18574. * <header>
  18575. * Header A
  18576. * </header>
  18577. * <div class="body">
  18578. * Body A
  18579. * </div>
  18580. * <footer>
  18581. * Footer A
  18582. * </footer>
  18583. * <header>
  18584. * Header B
  18585. * </header>
  18586. * <div class="body">
  18587. * Body B
  18588. * </div>
  18589. * <footer>
  18590. * Footer B
  18591. * </footer>
  18592. * ```
  18593. *
  18594. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  18595. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  18596. *
  18597. * @animations
  18598. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  18599. *
  18600. * **.leave** - when an item is removed from the list or when an item is filtered out
  18601. *
  18602. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  18603. *
  18604. * @element ANY
  18605. * @scope
  18606. * @priority 1000
  18607. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  18608. * formats are currently supported:
  18609. *
  18610. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  18611. * is a scope expression giving the collection to enumerate.
  18612. *
  18613. * For example: `album in artist.albums`.
  18614. *
  18615. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  18616. * and `expression` is the scope expression giving the collection to enumerate.
  18617. *
  18618. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  18619. *
  18620. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  18621. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  18622. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  18623. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  18624. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  18625. * before specifying a tracking expression.
  18626. *
  18627. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  18628. * will be associated by item identity in the array.
  18629. *
  18630. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18631. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18632. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18633. * element in the same way in the DOM.
  18634. *
  18635. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18636. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18637. * property is same.
  18638. *
  18639. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18640. * to items in conjunction with a tracking expression.
  18641. *
  18642. * @example
  18643. * This example initializes the scope to a list of names and
  18644. * then uses `ngRepeat` to display every person:
  18645. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18646. <file name="index.html">
  18647. <div ng-init="friends = [
  18648. {name:'John', age:25, gender:'boy'},
  18649. {name:'Jessie', age:30, gender:'girl'},
  18650. {name:'Johanna', age:28, gender:'girl'},
  18651. {name:'Joy', age:15, gender:'girl'},
  18652. {name:'Mary', age:28, gender:'girl'},
  18653. {name:'Peter', age:95, gender:'boy'},
  18654. {name:'Sebastian', age:50, gender:'boy'},
  18655. {name:'Erika', age:27, gender:'girl'},
  18656. {name:'Patrick', age:40, gender:'boy'},
  18657. {name:'Samantha', age:60, gender:'girl'}
  18658. ]">
  18659. I have {{friends.length}} friends. They are:
  18660. <input type="search" ng-model="q" placeholder="filter friends..." />
  18661. <ul class="example-animate-container">
  18662. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18663. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18664. </li>
  18665. </ul>
  18666. </div>
  18667. </file>
  18668. <file name="animations.css">
  18669. .example-animate-container {
  18670. background:white;
  18671. border:1px solid black;
  18672. list-style:none;
  18673. margin:0;
  18674. padding:0 10px;
  18675. }
  18676. .animate-repeat {
  18677. line-height:40px;
  18678. list-style:none;
  18679. box-sizing:border-box;
  18680. }
  18681. .animate-repeat.ng-move,
  18682. .animate-repeat.ng-enter,
  18683. .animate-repeat.ng-leave {
  18684. -webkit-transition:all linear 0.5s;
  18685. transition:all linear 0.5s;
  18686. }
  18687. .animate-repeat.ng-leave.ng-leave-active,
  18688. .animate-repeat.ng-move,
  18689. .animate-repeat.ng-enter {
  18690. opacity:0;
  18691. max-height:0;
  18692. }
  18693. .animate-repeat.ng-leave,
  18694. .animate-repeat.ng-move.ng-move-active,
  18695. .animate-repeat.ng-enter.ng-enter-active {
  18696. opacity:1;
  18697. max-height:40px;
  18698. }
  18699. </file>
  18700. <file name="protractor.js" type="protractor">
  18701. var friends = element.all(by.repeater('friend in friends'));
  18702. it('should render initial data set', function() {
  18703. expect(friends.count()).toBe(10);
  18704. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18705. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18706. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18707. expect(element(by.binding('friends.length')).getText())
  18708. .toMatch("I have 10 friends. They are:");
  18709. });
  18710. it('should update repeater when filter predicate changes', function() {
  18711. expect(friends.count()).toBe(10);
  18712. element(by.model('q')).sendKeys('ma');
  18713. expect(friends.count()).toBe(2);
  18714. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18715. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18716. });
  18717. </file>
  18718. </example>
  18719. */
  18720. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18721. var NG_REMOVED = '$$NG_REMOVED';
  18722. var ngRepeatMinErr = minErr('ngRepeat');
  18723. return {
  18724. transclude: 'element',
  18725. priority: 1000,
  18726. terminal: true,
  18727. $$tlb: true,
  18728. link: function($scope, $element, $attr, ctrl, $transclude){
  18729. var expression = $attr.ngRepeat;
  18730. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18731. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18732. lhs, rhs, valueIdentifier, keyIdentifier,
  18733. hashFnLocals = {$id: hashKey};
  18734. if (!match) {
  18735. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18736. expression);
  18737. }
  18738. lhs = match[1];
  18739. rhs = match[2];
  18740. trackByExp = match[3];
  18741. if (trackByExp) {
  18742. trackByExpGetter = $parse(trackByExp);
  18743. trackByIdExpFn = function(key, value, index) {
  18744. // assign key, value, and $index to the locals so that they can be used in hash functions
  18745. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18746. hashFnLocals[valueIdentifier] = value;
  18747. hashFnLocals.$index = index;
  18748. return trackByExpGetter($scope, hashFnLocals);
  18749. };
  18750. } else {
  18751. trackByIdArrayFn = function(key, value) {
  18752. return hashKey(value);
  18753. };
  18754. trackByIdObjFn = function(key) {
  18755. return key;
  18756. };
  18757. }
  18758. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18759. if (!match) {
  18760. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18761. lhs);
  18762. }
  18763. valueIdentifier = match[3] || match[1];
  18764. keyIdentifier = match[2];
  18765. // Store a list of elements from previous run. This is a hash where key is the item from the
  18766. // iterator, and the value is objects with following properties.
  18767. // - scope: bound scope
  18768. // - element: previous element.
  18769. // - index: position
  18770. var lastBlockMap = {};
  18771. //watch props
  18772. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18773. var index, length,
  18774. previousNode = $element[0], // current position of the node
  18775. nextNode,
  18776. // Same as lastBlockMap but it has the current state. It will become the
  18777. // lastBlockMap on the next iteration.
  18778. nextBlockMap = {},
  18779. arrayLength,
  18780. childScope,
  18781. key, value, // key/value of iteration
  18782. trackById,
  18783. trackByIdFn,
  18784. collectionKeys,
  18785. block, // last object information {scope, element, id}
  18786. nextBlockOrder = [],
  18787. elementsToRemove;
  18788. if (isArrayLike(collection)) {
  18789. collectionKeys = collection;
  18790. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18791. } else {
  18792. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18793. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18794. collectionKeys = [];
  18795. for (key in collection) {
  18796. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18797. collectionKeys.push(key);
  18798. }
  18799. }
  18800. collectionKeys.sort();
  18801. }
  18802. arrayLength = collectionKeys.length;
  18803. // locate existing items
  18804. length = nextBlockOrder.length = collectionKeys.length;
  18805. for(index = 0; index < length; index++) {
  18806. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18807. value = collection[key];
  18808. trackById = trackByIdFn(key, value, index);
  18809. assertNotHasOwnProperty(trackById, '`track by` id');
  18810. if(lastBlockMap.hasOwnProperty(trackById)) {
  18811. block = lastBlockMap[trackById];
  18812. delete lastBlockMap[trackById];
  18813. nextBlockMap[trackById] = block;
  18814. nextBlockOrder[index] = block;
  18815. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18816. // restore lastBlockMap
  18817. forEach(nextBlockOrder, function(block) {
  18818. if (block && block.scope) lastBlockMap[block.id] = block;
  18819. });
  18820. // This is a duplicate and we need to throw an error
  18821. throw ngRepeatMinErr('dupes',
  18822. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  18823. expression, trackById, toJson(value));
  18824. } else {
  18825. // new never before seen block
  18826. nextBlockOrder[index] = { id: trackById };
  18827. nextBlockMap[trackById] = false;
  18828. }
  18829. }
  18830. // remove existing items
  18831. for (key in lastBlockMap) {
  18832. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18833. if (lastBlockMap.hasOwnProperty(key)) {
  18834. block = lastBlockMap[key];
  18835. elementsToRemove = getBlockElements(block.clone);
  18836. $animate.leave(elementsToRemove);
  18837. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18838. block.scope.$destroy();
  18839. }
  18840. }
  18841. // we are not using forEach for perf reasons (trying to avoid #call)
  18842. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18843. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18844. value = collection[key];
  18845. block = nextBlockOrder[index];
  18846. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18847. if (block.scope) {
  18848. // if we have already seen this object, then we need to reuse the
  18849. // associated scope/element
  18850. childScope = block.scope;
  18851. nextNode = previousNode;
  18852. do {
  18853. nextNode = nextNode.nextSibling;
  18854. } while(nextNode && nextNode[NG_REMOVED]);
  18855. if (getBlockStart(block) != nextNode) {
  18856. // existing item which got moved
  18857. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18858. }
  18859. previousNode = getBlockEnd(block);
  18860. } else {
  18861. // new item which we don't know about
  18862. childScope = $scope.$new();
  18863. }
  18864. childScope[valueIdentifier] = value;
  18865. if (keyIdentifier) childScope[keyIdentifier] = key;
  18866. childScope.$index = index;
  18867. childScope.$first = (index === 0);
  18868. childScope.$last = (index === (arrayLength - 1));
  18869. childScope.$middle = !(childScope.$first || childScope.$last);
  18870. // jshint bitwise: false
  18871. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18872. // jshint bitwise: true
  18873. if (!block.scope) {
  18874. $transclude(childScope, function(clone) {
  18875. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18876. $animate.enter(clone, null, jqLite(previousNode));
  18877. previousNode = clone;
  18878. block.scope = childScope;
  18879. // Note: We only need the first/last node of the cloned nodes.
  18880. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18881. // by a directive with templateUrl when its template arrives.
  18882. block.clone = clone;
  18883. nextBlockMap[block.id] = block;
  18884. });
  18885. }
  18886. }
  18887. lastBlockMap = nextBlockMap;
  18888. });
  18889. }
  18890. };
  18891. function getBlockStart(block) {
  18892. return block.clone[0];
  18893. }
  18894. function getBlockEnd(block) {
  18895. return block.clone[block.clone.length - 1];
  18896. }
  18897. }];
  18898. /**
  18899. * @ngdoc directive
  18900. * @name ngShow
  18901. *
  18902. * @description
  18903. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18904. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  18905. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18906. * in AngularJS and sets the display style to none (using an !important flag).
  18907. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18908. *
  18909. * ```html
  18910. * <!-- when $scope.myValue is truthy (element is visible) -->
  18911. * <div ng-show="myValue"></div>
  18912. *
  18913. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18914. * <div ng-show="myValue" class="ng-hide"></div>
  18915. * ```
  18916. *
  18917. * When the `ngShow` expression evaluates to false then the `.ng-hide` CSS class is added to the class attribute
  18918. * on the element causing it to become hidden. When true, the `.ng-hide` CSS class is removed
  18919. * from the element causing the element not to appear hidden.
  18920. *
  18921. * <div class="alert alert-warning">
  18922. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18923. * "f" / "0" / "false" / "no" / "n" / "[]"
  18924. * </div>
  18925. *
  18926. * ## Why is !important used?
  18927. *
  18928. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  18929. * can be easily overridden by heavier selectors. For example, something as simple
  18930. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18931. * This also becomes a bigger issue when dealing with CSS frameworks.
  18932. *
  18933. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18934. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18935. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18936. *
  18937. * ### Overriding `.ng-hide`
  18938. *
  18939. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18940. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18941. * class in CSS:
  18942. *
  18943. * ```css
  18944. * .ng-hide {
  18945. * //this is just another form of hiding an element
  18946. * display:block!important;
  18947. * position:absolute;
  18948. * top:-9999px;
  18949. * left:-9999px;
  18950. * }
  18951. * ```
  18952. *
  18953. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18954. *
  18955. * ## A note about animations with `ngShow`
  18956. *
  18957. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18958. * is true and false. This system works like the animation system present with ngClass except that
  18959. * you must also include the !important flag to override the display property
  18960. * so that you can perform an animation when the element is hidden during the time of the animation.
  18961. *
  18962. * ```css
  18963. * //
  18964. * //a working example can be found at the bottom of this page
  18965. * //
  18966. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18967. * transition:0.5s linear all;
  18968. * }
  18969. *
  18970. * .my-element.ng-hide-add { ... }
  18971. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18972. * .my-element.ng-hide-remove { ... }
  18973. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18974. * ```
  18975. *
  18976. * 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
  18977. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  18978. *
  18979. * @animations
  18980. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  18981. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  18982. *
  18983. * @element ANY
  18984. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  18985. * then the element is shown or hidden respectively.
  18986. *
  18987. * @example
  18988. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18989. <file name="index.html">
  18990. Click me: <input type="checkbox" ng-model="checked"><br/>
  18991. <div>
  18992. Show:
  18993. <div class="check-element animate-show" ng-show="checked">
  18994. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18995. </div>
  18996. </div>
  18997. <div>
  18998. Hide:
  18999. <div class="check-element animate-show" ng-hide="checked">
  19000. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19001. </div>
  19002. </div>
  19003. </file>
  19004. <file name="glyphicons.css">
  19005. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19006. </file>
  19007. <file name="animations.css">
  19008. .animate-show {
  19009. -webkit-transition:all linear 0.5s;
  19010. transition:all linear 0.5s;
  19011. line-height:20px;
  19012. opacity:1;
  19013. padding:10px;
  19014. border:1px solid black;
  19015. background:white;
  19016. }
  19017. .animate-show.ng-hide {
  19018. line-height:0;
  19019. opacity:0;
  19020. padding:0 10px;
  19021. }
  19022. .check-element {
  19023. padding:10px;
  19024. border:1px solid black;
  19025. background:white;
  19026. }
  19027. </file>
  19028. <file name="protractor.js" type="protractor">
  19029. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19030. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19031. it('should check ng-show / ng-hide', function() {
  19032. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19033. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19034. element(by.model('checked')).click();
  19035. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19036. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19037. });
  19038. </file>
  19039. </example>
  19040. */
  19041. var ngShowDirective = ['$animate', function($animate) {
  19042. return function(scope, element, attr) {
  19043. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  19044. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  19045. });
  19046. };
  19047. }];
  19048. /**
  19049. * @ngdoc directive
  19050. * @name ngHide
  19051. *
  19052. * @description
  19053. * The `ngHide` directive shows or hides the given HTML element based on the expression
  19054. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  19055. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  19056. * in AngularJS and sets the display style to none (using an !important flag).
  19057. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19058. *
  19059. * ```html
  19060. * <!-- when $scope.myValue is truthy (element is hidden) -->
  19061. * <div ng-hide="myValue" class="ng-hide"></div>
  19062. *
  19063. * <!-- when $scope.myValue is falsy (element is visible) -->
  19064. * <div ng-hide="myValue"></div>
  19065. * ```
  19066. *
  19067. * When the `.ngHide` expression evaluates to true then the `.ng-hide` CSS class is added to the class attribute
  19068. * on the element causing it to become hidden. When false, the `.ng-hide` CSS class is removed
  19069. * from the element causing the element not to appear hidden.
  19070. *
  19071. * <div class="alert alert-warning">
  19072. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  19073. * "f" / "0" / "false" / "no" / "n" / "[]"
  19074. * </div>
  19075. *
  19076. * ## Why is !important used?
  19077. *
  19078. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  19079. * can be easily overridden by heavier selectors. For example, something as simple
  19080. * as changing the display style on a HTML list item would make hidden elements appear visible.
  19081. * This also becomes a bigger issue when dealing with CSS frameworks.
  19082. *
  19083. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  19084. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  19085. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  19086. *
  19087. * ### Overriding `.ng-hide`
  19088. *
  19089. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  19090. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  19091. * class in CSS:
  19092. *
  19093. * ```css
  19094. * .ng-hide {
  19095. * //this is just another form of hiding an element
  19096. * display:block!important;
  19097. * position:absolute;
  19098. * top:-9999px;
  19099. * left:-9999px;
  19100. * }
  19101. * ```
  19102. *
  19103. * By default you don't need to override in CSS anything and the animations will work around the display style.
  19104. *
  19105. * ## A note about animations with `ngHide`
  19106. *
  19107. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  19108. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  19109. * CSS class is added and removed for you instead of your own CSS class.
  19110. *
  19111. * ```css
  19112. * //
  19113. * //a working example can be found at the bottom of this page
  19114. * //
  19115. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  19116. * transition:0.5s linear all;
  19117. * }
  19118. *
  19119. * .my-element.ng-hide-add { ... }
  19120. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  19121. * .my-element.ng-hide-remove { ... }
  19122. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  19123. * ```
  19124. *
  19125. * 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
  19126. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  19127. *
  19128. * @animations
  19129. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  19130. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  19131. *
  19132. * @element ANY
  19133. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  19134. * the element is shown or hidden respectively.
  19135. *
  19136. * @example
  19137. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19138. <file name="index.html">
  19139. Click me: <input type="checkbox" ng-model="checked"><br/>
  19140. <div>
  19141. Show:
  19142. <div class="check-element animate-hide" ng-show="checked">
  19143. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  19144. </div>
  19145. </div>
  19146. <div>
  19147. Hide:
  19148. <div class="check-element animate-hide" ng-hide="checked">
  19149. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  19150. </div>
  19151. </div>
  19152. </file>
  19153. <file name="glyphicons.css">
  19154. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  19155. </file>
  19156. <file name="animations.css">
  19157. .animate-hide {
  19158. -webkit-transition:all linear 0.5s;
  19159. transition:all linear 0.5s;
  19160. line-height:20px;
  19161. opacity:1;
  19162. padding:10px;
  19163. border:1px solid black;
  19164. background:white;
  19165. }
  19166. .animate-hide.ng-hide {
  19167. line-height:0;
  19168. opacity:0;
  19169. padding:0 10px;
  19170. }
  19171. .check-element {
  19172. padding:10px;
  19173. border:1px solid black;
  19174. background:white;
  19175. }
  19176. </file>
  19177. <file name="protractor.js" type="protractor">
  19178. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  19179. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  19180. it('should check ng-show / ng-hide', function() {
  19181. expect(thumbsUp.isDisplayed()).toBeFalsy();
  19182. expect(thumbsDown.isDisplayed()).toBeTruthy();
  19183. element(by.model('checked')).click();
  19184. expect(thumbsUp.isDisplayed()).toBeTruthy();
  19185. expect(thumbsDown.isDisplayed()).toBeFalsy();
  19186. });
  19187. </file>
  19188. </example>
  19189. */
  19190. var ngHideDirective = ['$animate', function($animate) {
  19191. return function(scope, element, attr) {
  19192. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  19193. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  19194. });
  19195. };
  19196. }];
  19197. /**
  19198. * @ngdoc directive
  19199. * @name ngStyle
  19200. * @restrict AC
  19201. *
  19202. * @description
  19203. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  19204. *
  19205. * @element ANY
  19206. * @param {expression} ngStyle
  19207. *
  19208. * {@link guide/expression Expression} which evals to an
  19209. * object whose keys are CSS style names and values are corresponding values for those CSS
  19210. * keys.
  19211. *
  19212. * Since some CSS style names are not valid keys for an object, they must be quoted.
  19213. * See the 'background-color' style in the example below.
  19214. *
  19215. * @example
  19216. <example>
  19217. <file name="index.html">
  19218. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  19219. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  19220. <input type="button" value="clear" ng-click="myStyle={}">
  19221. <br/>
  19222. <span ng-style="myStyle">Sample Text</span>
  19223. <pre>myStyle={{myStyle}}</pre>
  19224. </file>
  19225. <file name="style.css">
  19226. span {
  19227. color: black;
  19228. }
  19229. </file>
  19230. <file name="protractor.js" type="protractor">
  19231. var colorSpan = element(by.css('span'));
  19232. it('should check ng-style', function() {
  19233. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19234. element(by.css('input[value=\'set color\']')).click();
  19235. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  19236. element(by.css('input[value=clear]')).click();
  19237. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19238. });
  19239. </file>
  19240. </example>
  19241. */
  19242. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  19243. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  19244. if (oldStyles && (newStyles !== oldStyles)) {
  19245. forEach(oldStyles, function(val, style) { element.css(style, '');});
  19246. }
  19247. if (newStyles) element.css(newStyles);
  19248. }, true);
  19249. });
  19250. /**
  19251. * @ngdoc directive
  19252. * @name ngSwitch
  19253. * @restrict EA
  19254. *
  19255. * @description
  19256. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  19257. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  19258. * as specified in the template.
  19259. *
  19260. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  19261. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  19262. * matches the value obtained from the evaluated expression. In other words, you define a container element
  19263. * (where you place the directive), place an expression on the **`on="..."` attribute**
  19264. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  19265. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  19266. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  19267. * attribute is displayed.
  19268. *
  19269. * <div class="alert alert-info">
  19270. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  19271. * as literal string values to match against.
  19272. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  19273. * value of the expression `$scope.someVal`.
  19274. * </div>
  19275. * @animations
  19276. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  19277. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  19278. *
  19279. * @usage
  19280. *
  19281. * ```
  19282. * <ANY ng-switch="expression">
  19283. * <ANY ng-switch-when="matchValue1">...</ANY>
  19284. * <ANY ng-switch-when="matchValue2">...</ANY>
  19285. * <ANY ng-switch-default>...</ANY>
  19286. * </ANY>
  19287. * ```
  19288. *
  19289. *
  19290. * @scope
  19291. * @priority 800
  19292. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  19293. * On child elements add:
  19294. *
  19295. * * `ngSwitchWhen`: the case statement to match against. If match then this
  19296. * case will be displayed. If the same match appears multiple times, all the
  19297. * elements will be displayed.
  19298. * * `ngSwitchDefault`: the default case when no other case match. If there
  19299. * are multiple default cases, all of them will be displayed when no other
  19300. * case match.
  19301. *
  19302. *
  19303. * @example
  19304. <example module="switchExample" deps="angular-animate.js" animations="true">
  19305. <file name="index.html">
  19306. <div ng-controller="ExampleController">
  19307. <select ng-model="selection" ng-options="item for item in items">
  19308. </select>
  19309. <tt>selection={{selection}}</tt>
  19310. <hr/>
  19311. <div class="animate-switch-container"
  19312. ng-switch on="selection">
  19313. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  19314. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  19315. <div class="animate-switch" ng-switch-default>default</div>
  19316. </div>
  19317. </div>
  19318. </file>
  19319. <file name="script.js">
  19320. angular.module('switchExample', ['ngAnimate'])
  19321. .controller('ExampleController', ['$scope', function($scope) {
  19322. $scope.items = ['settings', 'home', 'other'];
  19323. $scope.selection = $scope.items[0];
  19324. }]);
  19325. </file>
  19326. <file name="animations.css">
  19327. .animate-switch-container {
  19328. position:relative;
  19329. background:white;
  19330. border:1px solid black;
  19331. height:40px;
  19332. overflow:hidden;
  19333. }
  19334. .animate-switch {
  19335. padding:10px;
  19336. }
  19337. .animate-switch.ng-animate {
  19338. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19339. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19340. position:absolute;
  19341. top:0;
  19342. left:0;
  19343. right:0;
  19344. bottom:0;
  19345. }
  19346. .animate-switch.ng-leave.ng-leave-active,
  19347. .animate-switch.ng-enter {
  19348. top:-50px;
  19349. }
  19350. .animate-switch.ng-leave,
  19351. .animate-switch.ng-enter.ng-enter-active {
  19352. top:0;
  19353. }
  19354. </file>
  19355. <file name="protractor.js" type="protractor">
  19356. var switchElem = element(by.css('[ng-switch]'));
  19357. var select = element(by.model('selection'));
  19358. it('should start in settings', function() {
  19359. expect(switchElem.getText()).toMatch(/Settings Div/);
  19360. });
  19361. it('should change to home', function() {
  19362. select.all(by.css('option')).get(1).click();
  19363. expect(switchElem.getText()).toMatch(/Home Span/);
  19364. });
  19365. it('should select default', function() {
  19366. select.all(by.css('option')).get(2).click();
  19367. expect(switchElem.getText()).toMatch(/default/);
  19368. });
  19369. </file>
  19370. </example>
  19371. */
  19372. var ngSwitchDirective = ['$animate', function($animate) {
  19373. return {
  19374. restrict: 'EA',
  19375. require: 'ngSwitch',
  19376. // asks for $scope to fool the BC controller module
  19377. controller: ['$scope', function ngSwitchController() {
  19378. this.cases = {};
  19379. }],
  19380. link: function(scope, element, attr, ngSwitchController) {
  19381. var watchExpr = attr.ngSwitch || attr.on,
  19382. selectedTranscludes = [],
  19383. selectedElements = [],
  19384. previousElements = [],
  19385. selectedScopes = [];
  19386. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  19387. var i, ii;
  19388. for (i = 0, ii = previousElements.length; i < ii; ++i) {
  19389. previousElements[i].remove();
  19390. }
  19391. previousElements.length = 0;
  19392. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  19393. var selected = selectedElements[i];
  19394. selectedScopes[i].$destroy();
  19395. previousElements[i] = selected;
  19396. $animate.leave(selected, function() {
  19397. previousElements.splice(i, 1);
  19398. });
  19399. }
  19400. selectedElements.length = 0;
  19401. selectedScopes.length = 0;
  19402. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  19403. scope.$eval(attr.change);
  19404. forEach(selectedTranscludes, function(selectedTransclude) {
  19405. var selectedScope = scope.$new();
  19406. selectedScopes.push(selectedScope);
  19407. selectedTransclude.transclude(selectedScope, function(caseElement) {
  19408. var anchor = selectedTransclude.element;
  19409. selectedElements.push(caseElement);
  19410. $animate.enter(caseElement, anchor.parent(), anchor);
  19411. });
  19412. });
  19413. }
  19414. });
  19415. }
  19416. };
  19417. }];
  19418. var ngSwitchWhenDirective = ngDirective({
  19419. transclude: 'element',
  19420. priority: 800,
  19421. require: '^ngSwitch',
  19422. link: function(scope, element, attrs, ctrl, $transclude) {
  19423. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  19424. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  19425. }
  19426. });
  19427. var ngSwitchDefaultDirective = ngDirective({
  19428. transclude: 'element',
  19429. priority: 800,
  19430. require: '^ngSwitch',
  19431. link: function(scope, element, attr, ctrl, $transclude) {
  19432. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  19433. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  19434. }
  19435. });
  19436. /**
  19437. * @ngdoc directive
  19438. * @name ngTransclude
  19439. * @restrict AC
  19440. *
  19441. * @description
  19442. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  19443. *
  19444. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  19445. *
  19446. * @element ANY
  19447. *
  19448. * @example
  19449. <example module="transcludeExample">
  19450. <file name="index.html">
  19451. <script>
  19452. angular.module('transcludeExample', [])
  19453. .directive('pane', function(){
  19454. return {
  19455. restrict: 'E',
  19456. transclude: true,
  19457. scope: { title:'@' },
  19458. template: '<div style="border: 1px solid black;">' +
  19459. '<div style="background-color: gray">{{title}}</div>' +
  19460. '<div ng-transclude></div>' +
  19461. '</div>'
  19462. };
  19463. })
  19464. .controller('ExampleController', ['$scope', function($scope) {
  19465. $scope.title = 'Lorem Ipsum';
  19466. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  19467. }]);
  19468. </script>
  19469. <div ng-controller="ExampleController">
  19470. <input ng-model="title"><br>
  19471. <textarea ng-model="text"></textarea> <br/>
  19472. <pane title="{{title}}">{{text}}</pane>
  19473. </div>
  19474. </file>
  19475. <file name="protractor.js" type="protractor">
  19476. it('should have transcluded', function() {
  19477. var titleElement = element(by.model('title'));
  19478. titleElement.clear();
  19479. titleElement.sendKeys('TITLE');
  19480. var textElement = element(by.model('text'));
  19481. textElement.clear();
  19482. textElement.sendKeys('TEXT');
  19483. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  19484. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  19485. });
  19486. </file>
  19487. </example>
  19488. *
  19489. */
  19490. var ngTranscludeDirective = ngDirective({
  19491. link: function($scope, $element, $attrs, controller, $transclude) {
  19492. if (!$transclude) {
  19493. throw minErr('ngTransclude')('orphan',
  19494. 'Illegal use of ngTransclude directive in the template! ' +
  19495. 'No parent directive that requires a transclusion found. ' +
  19496. 'Element: {0}',
  19497. startingTag($element));
  19498. }
  19499. $transclude(function(clone) {
  19500. $element.empty();
  19501. $element.append(clone);
  19502. });
  19503. }
  19504. });
  19505. /**
  19506. * @ngdoc directive
  19507. * @name script
  19508. * @restrict E
  19509. *
  19510. * @description
  19511. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  19512. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  19513. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  19514. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  19515. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  19516. *
  19517. * @param {string} type Must be set to `'text/ng-template'`.
  19518. * @param {string} id Cache name of the template.
  19519. *
  19520. * @example
  19521. <example>
  19522. <file name="index.html">
  19523. <script type="text/ng-template" id="/tpl.html">
  19524. Content of the template.
  19525. </script>
  19526. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  19527. <div id="tpl-content" ng-include src="currentTpl"></div>
  19528. </file>
  19529. <file name="protractor.js" type="protractor">
  19530. it('should load template defined inside script tag', function() {
  19531. element(by.css('#tpl-link')).click();
  19532. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  19533. });
  19534. </file>
  19535. </example>
  19536. */
  19537. var scriptDirective = ['$templateCache', function($templateCache) {
  19538. return {
  19539. restrict: 'E',
  19540. terminal: true,
  19541. compile: function(element, attr) {
  19542. if (attr.type == 'text/ng-template') {
  19543. var templateUrl = attr.id,
  19544. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  19545. text = element[0].text;
  19546. $templateCache.put(templateUrl, text);
  19547. }
  19548. }
  19549. };
  19550. }];
  19551. var ngOptionsMinErr = minErr('ngOptions');
  19552. /**
  19553. * @ngdoc directive
  19554. * @name select
  19555. * @restrict E
  19556. *
  19557. * @description
  19558. * HTML `SELECT` element with angular data-binding.
  19559. *
  19560. * # `ngOptions`
  19561. *
  19562. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  19563. * elements for the `<select>` element using the array or object obtained by evaluating the
  19564. * `ngOptions` comprehension_expression.
  19565. *
  19566. * When an item in the `<select>` menu is selected, the array element or object property
  19567. * represented by the selected option will be bound to the model identified by the `ngModel`
  19568. * directive.
  19569. *
  19570. * <div class="alert alert-warning">
  19571. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  19572. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  19573. * </div>
  19574. *
  19575. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  19576. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  19577. * option. See example below for demonstration.
  19578. *
  19579. * <div class="alert alert-warning">
  19580. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  19581. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  19582. * `select` model to be bound to a non-string value. This is because an option element can only
  19583. * be bound to string values at present.
  19584. * </div>
  19585. *
  19586. * @param {string} ngModel Assignable angular expression to data-bind to.
  19587. * @param {string=} name Property name of the form under which the control is published.
  19588. * @param {string=} required The control is considered valid only if value is entered.
  19589. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19590. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19591. * `required` when you want to data-bind to the `required` attribute.
  19592. * @param {comprehension_expression=} ngOptions in one of the following forms:
  19593. *
  19594. * * for array data sources:
  19595. * * `label` **`for`** `value` **`in`** `array`
  19596. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  19597. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  19598. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  19599. * * for object data sources:
  19600. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19601. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19602. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  19603. * * `select` **`as`** `label` **`group by`** `group`
  19604. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  19605. *
  19606. * Where:
  19607. *
  19608. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  19609. * * `value`: local variable which will refer to each item in the `array` or each property value
  19610. * of `object` during iteration.
  19611. * * `key`: local variable which will refer to a property name in `object` during iteration.
  19612. * * `label`: The result of this expression will be the label for `<option>` element. The
  19613. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  19614. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  19615. * element. If not specified, `select` expression will default to `value`.
  19616. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  19617. * DOM element.
  19618. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  19619. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  19620. * `value` variable (e.g. `value.propertyName`).
  19621. *
  19622. * @example
  19623. <example module="selectExample">
  19624. <file name="index.html">
  19625. <script>
  19626. angular.module('selectExample', [])
  19627. .controller('ExampleController', ['$scope', function($scope) {
  19628. $scope.colors = [
  19629. {name:'black', shade:'dark'},
  19630. {name:'white', shade:'light'},
  19631. {name:'red', shade:'dark'},
  19632. {name:'blue', shade:'dark'},
  19633. {name:'yellow', shade:'light'}
  19634. ];
  19635. $scope.myColor = $scope.colors[2]; // red
  19636. }]);
  19637. </script>
  19638. <div ng-controller="ExampleController">
  19639. <ul>
  19640. <li ng-repeat="color in colors">
  19641. Name: <input ng-model="color.name">
  19642. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19643. </li>
  19644. <li>
  19645. [<a href ng-click="colors.push({})">add</a>]
  19646. </li>
  19647. </ul>
  19648. <hr/>
  19649. Color (null not allowed):
  19650. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  19651. Color (null allowed):
  19652. <span class="nullable">
  19653. <select ng-model="myColor" ng-options="color.name for color in colors">
  19654. <option value="">-- choose color --</option>
  19655. </select>
  19656. </span><br/>
  19657. Color grouped by shade:
  19658. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  19659. </select><br/>
  19660. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  19661. <hr/>
  19662. Currently selected: {{ {selected_color:myColor} }}
  19663. <div style="border:solid 1px black; height:20px"
  19664. ng-style="{'background-color':myColor.name}">
  19665. </div>
  19666. </div>
  19667. </file>
  19668. <file name="protractor.js" type="protractor">
  19669. it('should check ng-options', function() {
  19670. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  19671. element.all(by.model('myColor')).first().click();
  19672. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  19673. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  19674. element(by.css('.nullable select[ng-model="myColor"]')).click();
  19675. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  19676. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  19677. });
  19678. </file>
  19679. </example>
  19680. */
  19681. var ngOptionsDirective = valueFn({ terminal: true });
  19682. // jshint maxlen: false
  19683. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19684. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19685. 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]+?))?$/,
  19686. nullModelCtrl = {$setViewValue: noop};
  19687. // jshint maxlen: 100
  19688. return {
  19689. restrict: 'E',
  19690. require: ['select', '?ngModel'],
  19691. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19692. var self = this,
  19693. optionsMap = {},
  19694. ngModelCtrl = nullModelCtrl,
  19695. nullOption,
  19696. unknownOption;
  19697. self.databound = $attrs.ngModel;
  19698. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19699. ngModelCtrl = ngModelCtrl_;
  19700. nullOption = nullOption_;
  19701. unknownOption = unknownOption_;
  19702. };
  19703. self.addOption = function(value) {
  19704. assertNotHasOwnProperty(value, '"option value"');
  19705. optionsMap[value] = true;
  19706. if (ngModelCtrl.$viewValue == value) {
  19707. $element.val(value);
  19708. if (unknownOption.parent()) unknownOption.remove();
  19709. }
  19710. };
  19711. self.removeOption = function(value) {
  19712. if (this.hasOption(value)) {
  19713. delete optionsMap[value];
  19714. if (ngModelCtrl.$viewValue == value) {
  19715. this.renderUnknownOption(value);
  19716. }
  19717. }
  19718. };
  19719. self.renderUnknownOption = function(val) {
  19720. var unknownVal = '? ' + hashKey(val) + ' ?';
  19721. unknownOption.val(unknownVal);
  19722. $element.prepend(unknownOption);
  19723. $element.val(unknownVal);
  19724. unknownOption.prop('selected', true); // needed for IE
  19725. };
  19726. self.hasOption = function(value) {
  19727. return optionsMap.hasOwnProperty(value);
  19728. };
  19729. $scope.$on('$destroy', function() {
  19730. // disable unknown option so that we don't do work when the whole select is being destroyed
  19731. self.renderUnknownOption = noop;
  19732. });
  19733. }],
  19734. link: function(scope, element, attr, ctrls) {
  19735. // if ngModel is not defined, we don't need to do anything
  19736. if (!ctrls[1]) return;
  19737. var selectCtrl = ctrls[0],
  19738. ngModelCtrl = ctrls[1],
  19739. multiple = attr.multiple,
  19740. optionsExp = attr.ngOptions,
  19741. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19742. emptyOption,
  19743. // we can't just jqLite('<option>') since jqLite is not smart enough
  19744. // to create it in <select> and IE barfs otherwise.
  19745. optionTemplate = jqLite(document.createElement('option')),
  19746. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19747. unknownOption = optionTemplate.clone();
  19748. // find "null" option
  19749. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19750. if (children[i].value === '') {
  19751. emptyOption = nullOption = children.eq(i);
  19752. break;
  19753. }
  19754. }
  19755. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19756. // required validator
  19757. if (multiple) {
  19758. ngModelCtrl.$isEmpty = function(value) {
  19759. return !value || value.length === 0;
  19760. };
  19761. }
  19762. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19763. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19764. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19765. ////////////////////////////
  19766. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19767. ngModelCtrl.$render = function() {
  19768. var viewValue = ngModelCtrl.$viewValue;
  19769. if (selectCtrl.hasOption(viewValue)) {
  19770. if (unknownOption.parent()) unknownOption.remove();
  19771. selectElement.val(viewValue);
  19772. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19773. } else {
  19774. if (isUndefined(viewValue) && emptyOption) {
  19775. selectElement.val('');
  19776. } else {
  19777. selectCtrl.renderUnknownOption(viewValue);
  19778. }
  19779. }
  19780. };
  19781. selectElement.on('change', function() {
  19782. scope.$apply(function() {
  19783. if (unknownOption.parent()) unknownOption.remove();
  19784. ngModelCtrl.$setViewValue(selectElement.val());
  19785. });
  19786. });
  19787. }
  19788. function setupAsMultiple(scope, selectElement, ctrl) {
  19789. var lastView;
  19790. ctrl.$render = function() {
  19791. var items = new HashMap(ctrl.$viewValue);
  19792. forEach(selectElement.find('option'), function(option) {
  19793. option.selected = isDefined(items.get(option.value));
  19794. });
  19795. };
  19796. // we have to do it on each watch since ngModel watches reference, but
  19797. // we need to work of an array, so we need to see if anything was inserted/removed
  19798. scope.$watch(function selectMultipleWatch() {
  19799. if (!equals(lastView, ctrl.$viewValue)) {
  19800. lastView = shallowCopy(ctrl.$viewValue);
  19801. ctrl.$render();
  19802. }
  19803. });
  19804. selectElement.on('change', function() {
  19805. scope.$apply(function() {
  19806. var array = [];
  19807. forEach(selectElement.find('option'), function(option) {
  19808. if (option.selected) {
  19809. array.push(option.value);
  19810. }
  19811. });
  19812. ctrl.$setViewValue(array);
  19813. });
  19814. });
  19815. }
  19816. function setupAsOptions(scope, selectElement, ctrl) {
  19817. var match;
  19818. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19819. throw ngOptionsMinErr('iexp',
  19820. "Expected expression in form of " +
  19821. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19822. " but got '{0}'. Element: {1}",
  19823. optionsExp, startingTag(selectElement));
  19824. }
  19825. var displayFn = $parse(match[2] || match[1]),
  19826. valueName = match[4] || match[6],
  19827. keyName = match[5],
  19828. groupByFn = $parse(match[3] || ''),
  19829. valueFn = $parse(match[2] ? match[1] : valueName),
  19830. valuesFn = $parse(match[7]),
  19831. track = match[8],
  19832. trackFn = track ? $parse(match[8]) : null,
  19833. // This is an array of array of existing option groups in DOM.
  19834. // We try to reuse these if possible
  19835. // - optionGroupsCache[0] is the options with no option group
  19836. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19837. optionGroupsCache = [[{element: selectElement, label:''}]];
  19838. if (nullOption) {
  19839. // compile the element since there might be bindings in it
  19840. $compile(nullOption)(scope);
  19841. // remove the class, which is added automatically because we recompile the element and it
  19842. // becomes the compilation root
  19843. nullOption.removeClass('ng-scope');
  19844. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19845. // remove the label from the element. wtf?
  19846. nullOption.remove();
  19847. }
  19848. // clear contents, we'll add what's needed based on the model
  19849. selectElement.empty();
  19850. selectElement.on('change', function() {
  19851. scope.$apply(function() {
  19852. var optionGroup,
  19853. collection = valuesFn(scope) || [],
  19854. locals = {},
  19855. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19856. if (multiple) {
  19857. value = [];
  19858. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19859. groupIndex < groupLength;
  19860. groupIndex++) {
  19861. // list of options for that group. (first item has the parent)
  19862. optionGroup = optionGroupsCache[groupIndex];
  19863. for(index = 1, length = optionGroup.length; index < length; index++) {
  19864. if ((optionElement = optionGroup[index].element)[0].selected) {
  19865. key = optionElement.val();
  19866. if (keyName) locals[keyName] = key;
  19867. if (trackFn) {
  19868. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19869. locals[valueName] = collection[trackIndex];
  19870. if (trackFn(scope, locals) == key) break;
  19871. }
  19872. } else {
  19873. locals[valueName] = collection[key];
  19874. }
  19875. value.push(valueFn(scope, locals));
  19876. }
  19877. }
  19878. }
  19879. } else {
  19880. key = selectElement.val();
  19881. if (key == '?') {
  19882. value = undefined;
  19883. } else if (key === ''){
  19884. value = null;
  19885. } else {
  19886. if (trackFn) {
  19887. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19888. locals[valueName] = collection[trackIndex];
  19889. if (trackFn(scope, locals) == key) {
  19890. value = valueFn(scope, locals);
  19891. break;
  19892. }
  19893. }
  19894. } else {
  19895. locals[valueName] = collection[key];
  19896. if (keyName) locals[keyName] = key;
  19897. value = valueFn(scope, locals);
  19898. }
  19899. }
  19900. }
  19901. ctrl.$setViewValue(value);
  19902. render();
  19903. });
  19904. });
  19905. ctrl.$render = render;
  19906. scope.$watchCollection(valuesFn, render);
  19907. scope.$watchCollection(function () {
  19908. var locals = {},
  19909. values = valuesFn(scope);
  19910. if (values) {
  19911. var toDisplay = new Array(values.length);
  19912. for (var i = 0, ii = values.length; i < ii; i++) {
  19913. locals[valueName] = values[i];
  19914. toDisplay[i] = displayFn(scope, locals);
  19915. }
  19916. return toDisplay;
  19917. }
  19918. }, render);
  19919. if ( multiple ) {
  19920. scope.$watchCollection(function() { return ctrl.$modelValue; }, render);
  19921. }
  19922. function getSelectedSet() {
  19923. var selectedSet = false;
  19924. if (multiple) {
  19925. var modelValue = ctrl.$modelValue;
  19926. if (trackFn && isArray(modelValue)) {
  19927. selectedSet = new HashMap([]);
  19928. var locals = {};
  19929. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19930. locals[valueName] = modelValue[trackIndex];
  19931. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19932. }
  19933. } else {
  19934. selectedSet = new HashMap(modelValue);
  19935. }
  19936. }
  19937. return selectedSet;
  19938. }
  19939. function render() {
  19940. // Temporary location for the option groups before we render them
  19941. var optionGroups = {'':[]},
  19942. optionGroupNames = [''],
  19943. optionGroupName,
  19944. optionGroup,
  19945. option,
  19946. existingParent, existingOptions, existingOption,
  19947. modelValue = ctrl.$modelValue,
  19948. values = valuesFn(scope) || [],
  19949. keys = keyName ? sortedKeys(values) : values,
  19950. key,
  19951. groupLength, length,
  19952. groupIndex, index,
  19953. locals = {},
  19954. selected,
  19955. selectedSet = getSelectedSet(),
  19956. lastElement,
  19957. element,
  19958. label;
  19959. // We now build up the list of options we need (we merge later)
  19960. for (index = 0; length = keys.length, index < length; index++) {
  19961. key = index;
  19962. if (keyName) {
  19963. key = keys[index];
  19964. if ( key.charAt(0) === '$' ) continue;
  19965. locals[keyName] = key;
  19966. }
  19967. locals[valueName] = values[key];
  19968. optionGroupName = groupByFn(scope, locals) || '';
  19969. if (!(optionGroup = optionGroups[optionGroupName])) {
  19970. optionGroup = optionGroups[optionGroupName] = [];
  19971. optionGroupNames.push(optionGroupName);
  19972. }
  19973. if (multiple) {
  19974. selected = isDefined(
  19975. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  19976. );
  19977. } else {
  19978. if (trackFn) {
  19979. var modelCast = {};
  19980. modelCast[valueName] = modelValue;
  19981. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  19982. } else {
  19983. selected = modelValue === valueFn(scope, locals);
  19984. }
  19985. selectedSet = selectedSet || selected; // see if at least one item is selected
  19986. }
  19987. label = displayFn(scope, locals); // what will be seen by the user
  19988. // doing displayFn(scope, locals) || '' overwrites zero values
  19989. label = isDefined(label) ? label : '';
  19990. optionGroup.push({
  19991. // either the index into array or key from object
  19992. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  19993. label: label,
  19994. selected: selected // determine if we should be selected
  19995. });
  19996. }
  19997. if (!multiple) {
  19998. if (nullOption || modelValue === null) {
  19999. // insert null option if we have a placeholder, or the model is null
  20000. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  20001. } else if (!selectedSet) {
  20002. // option could not be found, we have to insert the undefined item
  20003. optionGroups[''].unshift({id:'?', label:'', selected:true});
  20004. }
  20005. }
  20006. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  20007. for (groupIndex = 0, groupLength = optionGroupNames.length;
  20008. groupIndex < groupLength;
  20009. groupIndex++) {
  20010. // current option group name or '' if no group
  20011. optionGroupName = optionGroupNames[groupIndex];
  20012. // list of options for that group. (first item has the parent)
  20013. optionGroup = optionGroups[optionGroupName];
  20014. if (optionGroupsCache.length <= groupIndex) {
  20015. // we need to grow the optionGroups
  20016. existingParent = {
  20017. element: optGroupTemplate.clone().attr('label', optionGroupName),
  20018. label: optionGroup.label
  20019. };
  20020. existingOptions = [existingParent];
  20021. optionGroupsCache.push(existingOptions);
  20022. selectElement.append(existingParent.element);
  20023. } else {
  20024. existingOptions = optionGroupsCache[groupIndex];
  20025. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  20026. // update the OPTGROUP label if not the same.
  20027. if (existingParent.label != optionGroupName) {
  20028. existingParent.element.attr('label', existingParent.label = optionGroupName);
  20029. }
  20030. }
  20031. lastElement = null; // start at the beginning
  20032. for(index = 0, length = optionGroup.length; index < length; index++) {
  20033. option = optionGroup[index];
  20034. if ((existingOption = existingOptions[index+1])) {
  20035. // reuse elements
  20036. lastElement = existingOption.element;
  20037. if (existingOption.label !== option.label) {
  20038. lastElement.text(existingOption.label = option.label);
  20039. lastElement.prop('label', existingOption.label);
  20040. }
  20041. if (existingOption.id !== option.id) {
  20042. lastElement.val(existingOption.id = option.id);
  20043. }
  20044. // lastElement.prop('selected') provided by jQuery has side-effects
  20045. if (lastElement[0].selected !== option.selected) {
  20046. lastElement.prop('selected', (existingOption.selected = option.selected));
  20047. if (msie) {
  20048. // See #7692
  20049. // The selected item wouldn't visually update on IE without this.
  20050. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  20051. lastElement.prop('selected', existingOption.selected);
  20052. }
  20053. }
  20054. } else {
  20055. // grow elements
  20056. // if it's a null option
  20057. if (option.id === '' && nullOption) {
  20058. // put back the pre-compiled element
  20059. element = nullOption;
  20060. } else {
  20061. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  20062. // in this version of jQuery on some browser the .text() returns a string
  20063. // rather then the element.
  20064. (element = optionTemplate.clone())
  20065. .val(option.id)
  20066. .prop('selected', option.selected)
  20067. .attr('selected', option.selected)
  20068. .prop('label', option.label)
  20069. .text(option.label);
  20070. }
  20071. existingOptions.push(existingOption = {
  20072. element: element,
  20073. label: option.label,
  20074. id: option.id,
  20075. selected: option.selected
  20076. });
  20077. selectCtrl.addOption(option.label, element);
  20078. if (lastElement) {
  20079. lastElement.after(element);
  20080. } else {
  20081. existingParent.element.append(element);
  20082. }
  20083. lastElement = element;
  20084. }
  20085. }
  20086. // remove any excessive OPTIONs in a group
  20087. index++; // increment since the existingOptions[0] is parent element not OPTION
  20088. while(existingOptions.length > index) {
  20089. option = existingOptions.pop();
  20090. selectCtrl.removeOption(option.label);
  20091. option.element.remove();
  20092. }
  20093. }
  20094. // remove any excessive OPTGROUPs from select
  20095. while(optionGroupsCache.length > groupIndex) {
  20096. optionGroupsCache.pop()[0].element.remove();
  20097. }
  20098. }
  20099. }
  20100. }
  20101. };
  20102. }];
  20103. var optionDirective = ['$interpolate', function($interpolate) {
  20104. var nullSelectCtrl = {
  20105. addOption: noop,
  20106. removeOption: noop
  20107. };
  20108. return {
  20109. restrict: 'E',
  20110. priority: 100,
  20111. compile: function(element, attr) {
  20112. if (isUndefined(attr.value)) {
  20113. var interpolateFn = $interpolate(element.text(), true);
  20114. if (!interpolateFn) {
  20115. attr.$set('value', element.text());
  20116. }
  20117. }
  20118. return function (scope, element, attr) {
  20119. var selectCtrlName = '$selectController',
  20120. parent = element.parent(),
  20121. selectCtrl = parent.data(selectCtrlName) ||
  20122. parent.parent().data(selectCtrlName); // in case we are in optgroup
  20123. if (selectCtrl && selectCtrl.databound) {
  20124. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  20125. // We don't want the view to drive the initialization of the model anyway.
  20126. element.prop('selected', false);
  20127. } else {
  20128. selectCtrl = nullSelectCtrl;
  20129. }
  20130. if (interpolateFn) {
  20131. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  20132. attr.$set('value', newVal);
  20133. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  20134. selectCtrl.addOption(newVal);
  20135. });
  20136. } else {
  20137. selectCtrl.addOption(attr.value);
  20138. }
  20139. element.on('$destroy', function() {
  20140. selectCtrl.removeOption(attr.value);
  20141. });
  20142. };
  20143. }
  20144. };
  20145. }];
  20146. var styleDirective = valueFn({
  20147. restrict: 'E',
  20148. terminal: true
  20149. });
  20150. if (window.angular.bootstrap) {
  20151. //AngularJS is already loaded, so we can return here...
  20152. console.log('WARNING: Tried to load angular more than once.');
  20153. return;
  20154. }
  20155. //try to bind to jquery now so that one can write angular.element().read()
  20156. //but we will rebind on bootstrap again.
  20157. bindJQuery();
  20158. publishExternalAPI(angular);
  20159. jqLite(document).ready(function() {
  20160. angularInit(document, bootstrap);
  20161. });
  20162. })(window, document);
  20163. !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>');