angular.js 880 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465
  1. /**
  2. * @license AngularJS v1.2.16
  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.16/' +
  67. (module ? module + '/' : '') + code;
  68. for (i = 2; i < arguments.length; i++) {
  69. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  70. encodeURIComponent(stringify(arguments[i]));
  71. }
  72. return new Error(message);
  73. };
  74. }
  75. /* We need to tell jshint what variables are being exported */
  76. /* global
  77. -angular,
  78. -msie,
  79. -jqLite,
  80. -jQuery,
  81. -slice,
  82. -push,
  83. -toString,
  84. -ngMinErr,
  85. -_angular,
  86. -angularModule,
  87. -nodeName_,
  88. -uid,
  89. -lowercase,
  90. -uppercase,
  91. -manualLowercase,
  92. -manualUppercase,
  93. -nodeName_,
  94. -isArrayLike,
  95. -forEach,
  96. -sortedKeys,
  97. -forEachSorted,
  98. -reverseParams,
  99. -nextUid,
  100. -setHashKey,
  101. -extend,
  102. -int,
  103. -inherit,
  104. -noop,
  105. -identity,
  106. -valueFn,
  107. -isUndefined,
  108. -isDefined,
  109. -isObject,
  110. -isString,
  111. -isNumber,
  112. -isDate,
  113. -isArray,
  114. -isFunction,
  115. -isRegExp,
  116. -isWindow,
  117. -isScope,
  118. -isFile,
  119. -isBlob,
  120. -isBoolean,
  121. -trim,
  122. -isElement,
  123. -makeMap,
  124. -map,
  125. -size,
  126. -includes,
  127. -indexOf,
  128. -arrayRemove,
  129. -isLeafNode,
  130. -copy,
  131. -shallowCopy,
  132. -equals,
  133. -csp,
  134. -concat,
  135. -sliceArgs,
  136. -bind,
  137. -toJsonReplacer,
  138. -toJson,
  139. -fromJson,
  140. -toBoolean,
  141. -startingTag,
  142. -tryDecodeURIComponent,
  143. -parseKeyValue,
  144. -toKeyValue,
  145. -encodeUriSegment,
  146. -encodeUriQuery,
  147. -angularInit,
  148. -bootstrap,
  149. -snake_case,
  150. -bindJQuery,
  151. -assertArg,
  152. -assertArgFn,
  153. -assertNotHasOwnProperty,
  154. -getter,
  155. -getBlockElements,
  156. -hasOwnProperty,
  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. /**
  174. * @ngdoc function
  175. * @name angular.lowercase
  176. * @module ng
  177. * @function
  178. *
  179. * @description Converts the specified string to lowercase.
  180. * @param {string} string String to be converted to lowercase.
  181. * @returns {string} Lowercased string.
  182. */
  183. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  184. var hasOwnProperty = Object.prototype.hasOwnProperty;
  185. /**
  186. * @ngdoc function
  187. * @name angular.uppercase
  188. * @module ng
  189. * @function
  190. *
  191. * @description Converts the specified string to uppercase.
  192. * @param {string} string String to be converted to uppercase.
  193. * @returns {string} Uppercased string.
  194. */
  195. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  196. var manualLowercase = function(s) {
  197. /* jshint bitwise: false */
  198. return isString(s)
  199. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  200. : s;
  201. };
  202. var manualUppercase = function(s) {
  203. /* jshint bitwise: false */
  204. return isString(s)
  205. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  206. : s;
  207. };
  208. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  209. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  210. // with correct but slower alternatives.
  211. if ('i' !== 'I'.toLowerCase()) {
  212. lowercase = manualLowercase;
  213. uppercase = manualUppercase;
  214. }
  215. var /** holds major version number for IE or NaN for real browsers */
  216. msie,
  217. jqLite, // delay binding since jQuery could be loaded after us.
  218. jQuery, // delay binding
  219. slice = [].slice,
  220. push = [].push,
  221. toString = Object.prototype.toString,
  222. ngMinErr = minErr('ng'),
  223. _angular = window.angular,
  224. /** @name angular */
  225. angular = window.angular || (window.angular = {}),
  226. angularModule,
  227. nodeName_,
  228. uid = ['0', '0', '0'];
  229. /**
  230. * IE 11 changed the format of the UserAgent string.
  231. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  232. */
  233. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  234. if (isNaN(msie)) {
  235. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  236. }
  237. /**
  238. * @private
  239. * @param {*} obj
  240. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  241. * String ...)
  242. */
  243. function isArrayLike(obj) {
  244. if (obj == null || isWindow(obj)) {
  245. return false;
  246. }
  247. var length = obj.length;
  248. if (obj.nodeType === 1 && length) {
  249. return true;
  250. }
  251. return isString(obj) || isArray(obj) || length === 0 ||
  252. typeof length === 'number' && length > 0 && (length - 1) in obj;
  253. }
  254. /**
  255. * @ngdoc function
  256. * @name angular.forEach
  257. * @module ng
  258. * @function
  259. *
  260. * @description
  261. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  262. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  263. * is the value of an object property or an array element and `key` is the object property key or
  264. * array element index. Specifying a `context` for the function is optional.
  265. *
  266. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  267. * using the `hasOwnProperty` method.
  268. *
  269. ```js
  270. var values = {name: 'misko', gender: 'male'};
  271. var log = [];
  272. angular.forEach(values, function(value, key){
  273. this.push(key + ': ' + value);
  274. }, log);
  275. expect(log).toEqual(['name: misko', 'gender: male']);
  276. ```
  277. *
  278. * @param {Object|Array} obj Object to iterate over.
  279. * @param {Function} iterator Iterator function.
  280. * @param {Object=} context Object to become context (`this`) for the iterator function.
  281. * @returns {Object|Array} Reference to `obj`.
  282. */
  283. function forEach(obj, iterator, context) {
  284. var key;
  285. if (obj) {
  286. if (isFunction(obj)){
  287. for (key in obj) {
  288. // Need to check if hasOwnProperty exists,
  289. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  290. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  291. iterator.call(context, obj[key], key);
  292. }
  293. }
  294. } else if (obj.forEach && obj.forEach !== forEach) {
  295. obj.forEach(iterator, context);
  296. } else if (isArrayLike(obj)) {
  297. for (key = 0; key < obj.length; key++)
  298. iterator.call(context, obj[key], key);
  299. } else {
  300. for (key in obj) {
  301. if (obj.hasOwnProperty(key)) {
  302. iterator.call(context, obj[key], key);
  303. }
  304. }
  305. }
  306. }
  307. return obj;
  308. }
  309. function sortedKeys(obj) {
  310. var keys = [];
  311. for (var key in obj) {
  312. if (obj.hasOwnProperty(key)) {
  313. keys.push(key);
  314. }
  315. }
  316. return keys.sort();
  317. }
  318. function forEachSorted(obj, iterator, context) {
  319. var keys = sortedKeys(obj);
  320. for ( var i = 0; i < keys.length; i++) {
  321. iterator.call(context, obj[keys[i]], keys[i]);
  322. }
  323. return keys;
  324. }
  325. /**
  326. * when using forEach the params are value, key, but it is often useful to have key, value.
  327. * @param {function(string, *)} iteratorFn
  328. * @returns {function(*, string)}
  329. */
  330. function reverseParams(iteratorFn) {
  331. return function(value, key) { iteratorFn(key, value); };
  332. }
  333. /**
  334. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  335. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  336. * the number string gets longer over time, and it can also overflow, where as the nextId
  337. * will grow much slower, it is a string, and it will never overflow.
  338. *
  339. * @returns {string} an unique alpha-numeric string
  340. */
  341. function nextUid() {
  342. var index = uid.length;
  343. var digit;
  344. while(index) {
  345. index--;
  346. digit = uid[index].charCodeAt(0);
  347. if (digit == 57 /*'9'*/) {
  348. uid[index] = 'A';
  349. return uid.join('');
  350. }
  351. if (digit == 90 /*'Z'*/) {
  352. uid[index] = '0';
  353. } else {
  354. uid[index] = String.fromCharCode(digit + 1);
  355. return uid.join('');
  356. }
  357. }
  358. uid.unshift('0');
  359. return uid.join('');
  360. }
  361. /**
  362. * Set or clear the hashkey for an object.
  363. * @param obj object
  364. * @param h the hashkey (!truthy to delete the hashkey)
  365. */
  366. function setHashKey(obj, h) {
  367. if (h) {
  368. obj.$$hashKey = h;
  369. }
  370. else {
  371. delete obj.$$hashKey;
  372. }
  373. }
  374. /**
  375. * @ngdoc function
  376. * @name angular.extend
  377. * @module ng
  378. * @function
  379. *
  380. * @description
  381. * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
  382. * to `dst`. You can specify multiple `src` objects.
  383. *
  384. * @param {Object} dst Destination object.
  385. * @param {...Object} src Source object(s).
  386. * @returns {Object} Reference to `dst`.
  387. */
  388. function extend(dst) {
  389. var h = dst.$$hashKey;
  390. forEach(arguments, function(obj){
  391. if (obj !== dst) {
  392. forEach(obj, function(value, key){
  393. dst[key] = value;
  394. });
  395. }
  396. });
  397. setHashKey(dst,h);
  398. return dst;
  399. }
  400. function int(str) {
  401. return parseInt(str, 10);
  402. }
  403. function inherit(parent, extra) {
  404. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  405. }
  406. /**
  407. * @ngdoc function
  408. * @name angular.noop
  409. * @module ng
  410. * @function
  411. *
  412. * @description
  413. * A function that performs no operations. This function can be useful when writing code in the
  414. * functional style.
  415. ```js
  416. function foo(callback) {
  417. var result = calculateResult();
  418. (callback || angular.noop)(result);
  419. }
  420. ```
  421. */
  422. function noop() {}
  423. noop.$inject = [];
  424. /**
  425. * @ngdoc function
  426. * @name angular.identity
  427. * @module ng
  428. * @function
  429. *
  430. * @description
  431. * A function that returns its first argument. This function is useful when writing code in the
  432. * functional style.
  433. *
  434. ```js
  435. function transformer(transformationFn, value) {
  436. return (transformationFn || angular.identity)(value);
  437. };
  438. ```
  439. */
  440. function identity($) {return $;}
  441. identity.$inject = [];
  442. function valueFn(value) {return function() {return value;};}
  443. /**
  444. * @ngdoc function
  445. * @name angular.isUndefined
  446. * @module ng
  447. * @function
  448. *
  449. * @description
  450. * Determines if a reference is undefined.
  451. *
  452. * @param {*} value Reference to check.
  453. * @returns {boolean} True if `value` is undefined.
  454. */
  455. function isUndefined(value){return typeof value === 'undefined';}
  456. /**
  457. * @ngdoc function
  458. * @name angular.isDefined
  459. * @module ng
  460. * @function
  461. *
  462. * @description
  463. * Determines if a reference is defined.
  464. *
  465. * @param {*} value Reference to check.
  466. * @returns {boolean} True if `value` is defined.
  467. */
  468. function isDefined(value){return typeof value !== 'undefined';}
  469. /**
  470. * @ngdoc function
  471. * @name angular.isObject
  472. * @module ng
  473. * @function
  474. *
  475. * @description
  476. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  477. * considered to be objects. Note that JavaScript arrays are objects.
  478. *
  479. * @param {*} value Reference to check.
  480. * @returns {boolean} True if `value` is an `Object` but not `null`.
  481. */
  482. function isObject(value){return value != null && typeof value === 'object';}
  483. /**
  484. * @ngdoc function
  485. * @name angular.isString
  486. * @module ng
  487. * @function
  488. *
  489. * @description
  490. * Determines if a reference is a `String`.
  491. *
  492. * @param {*} value Reference to check.
  493. * @returns {boolean} True if `value` is a `String`.
  494. */
  495. function isString(value){return typeof value === 'string';}
  496. /**
  497. * @ngdoc function
  498. * @name angular.isNumber
  499. * @module ng
  500. * @function
  501. *
  502. * @description
  503. * Determines if a reference is a `Number`.
  504. *
  505. * @param {*} value Reference to check.
  506. * @returns {boolean} True if `value` is a `Number`.
  507. */
  508. function isNumber(value){return typeof value === 'number';}
  509. /**
  510. * @ngdoc function
  511. * @name angular.isDate
  512. * @module ng
  513. * @function
  514. *
  515. * @description
  516. * Determines if a value is a date.
  517. *
  518. * @param {*} value Reference to check.
  519. * @returns {boolean} True if `value` is a `Date`.
  520. */
  521. function isDate(value){
  522. return toString.call(value) === '[object Date]';
  523. }
  524. /**
  525. * @ngdoc function
  526. * @name angular.isArray
  527. * @module ng
  528. * @function
  529. *
  530. * @description
  531. * Determines if a reference is an `Array`.
  532. *
  533. * @param {*} value Reference to check.
  534. * @returns {boolean} True if `value` is an `Array`.
  535. */
  536. function isArray(value) {
  537. return toString.call(value) === '[object Array]';
  538. }
  539. /**
  540. * @ngdoc function
  541. * @name angular.isFunction
  542. * @module ng
  543. * @function
  544. *
  545. * @description
  546. * Determines if a reference is a `Function`.
  547. *
  548. * @param {*} value Reference to check.
  549. * @returns {boolean} True if `value` is a `Function`.
  550. */
  551. function isFunction(value){return typeof value === 'function';}
  552. /**
  553. * Determines if a value is a regular expression object.
  554. *
  555. * @private
  556. * @param {*} value Reference to check.
  557. * @returns {boolean} True if `value` is a `RegExp`.
  558. */
  559. function isRegExp(value) {
  560. return toString.call(value) === '[object RegExp]';
  561. }
  562. /**
  563. * Checks if `obj` is a window object.
  564. *
  565. * @private
  566. * @param {*} obj Object to check
  567. * @returns {boolean} True if `obj` is a window obj.
  568. */
  569. function isWindow(obj) {
  570. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  571. }
  572. function isScope(obj) {
  573. return obj && obj.$evalAsync && obj.$watch;
  574. }
  575. function isFile(obj) {
  576. return toString.call(obj) === '[object File]';
  577. }
  578. function isBlob(obj) {
  579. return toString.call(obj) === '[object Blob]';
  580. }
  581. function isBoolean(value) {
  582. return typeof value === 'boolean';
  583. }
  584. var trim = (function() {
  585. // native trim is way faster: http://jsperf.com/angular-trim-test
  586. // but IE doesn't have it... :-(
  587. // TODO: we should move this into IE/ES5 polyfill
  588. if (!String.prototype.trim) {
  589. return function(value) {
  590. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  591. };
  592. }
  593. return function(value) {
  594. return isString(value) ? value.trim() : value;
  595. };
  596. })();
  597. /**
  598. * @ngdoc function
  599. * @name angular.isElement
  600. * @module ng
  601. * @function
  602. *
  603. * @description
  604. * Determines if a reference is a DOM element (or wrapped jQuery element).
  605. *
  606. * @param {*} value Reference to check.
  607. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  608. */
  609. function isElement(node) {
  610. return !!(node &&
  611. (node.nodeName // we are a direct element
  612. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  613. }
  614. /**
  615. * @param str 'key1,key2,...'
  616. * @returns {object} in the form of {key1:true, key2:true, ...}
  617. */
  618. function makeMap(str){
  619. var obj = {}, items = str.split(","), i;
  620. for ( i = 0; i < items.length; i++ )
  621. obj[ items[i] ] = true;
  622. return obj;
  623. }
  624. if (msie < 9) {
  625. nodeName_ = function(element) {
  626. element = element.nodeName ? element : element[0];
  627. return (element.scopeName && element.scopeName != 'HTML')
  628. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  629. };
  630. } else {
  631. nodeName_ = function(element) {
  632. return element.nodeName ? element.nodeName : element[0].nodeName;
  633. };
  634. }
  635. function map(obj, iterator, context) {
  636. var results = [];
  637. forEach(obj, function(value, index, list) {
  638. results.push(iterator.call(context, value, index, list));
  639. });
  640. return results;
  641. }
  642. /**
  643. * @description
  644. * Determines the number of elements in an array, the number of properties an object has, or
  645. * the length of a string.
  646. *
  647. * Note: This function is used to augment the Object type in Angular expressions. See
  648. * {@link angular.Object} for more information about Angular arrays.
  649. *
  650. * @param {Object|Array|string} obj Object, array, or string to inspect.
  651. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  652. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  653. */
  654. function size(obj, ownPropsOnly) {
  655. var count = 0, key;
  656. if (isArray(obj) || isString(obj)) {
  657. return obj.length;
  658. } else if (isObject(obj)){
  659. for (key in obj)
  660. if (!ownPropsOnly || obj.hasOwnProperty(key))
  661. count++;
  662. }
  663. return count;
  664. }
  665. function includes(array, obj) {
  666. return indexOf(array, obj) != -1;
  667. }
  668. function indexOf(array, obj) {
  669. if (array.indexOf) return array.indexOf(obj);
  670. for (var i = 0; i < array.length; i++) {
  671. if (obj === array[i]) return i;
  672. }
  673. return -1;
  674. }
  675. function arrayRemove(array, value) {
  676. var index = indexOf(array, value);
  677. if (index >=0)
  678. array.splice(index, 1);
  679. return value;
  680. }
  681. function isLeafNode (node) {
  682. if (node) {
  683. switch (node.nodeName) {
  684. case "OPTION":
  685. case "PRE":
  686. case "TITLE":
  687. return true;
  688. }
  689. }
  690. return false;
  691. }
  692. /**
  693. * @ngdoc function
  694. * @name angular.copy
  695. * @module ng
  696. * @function
  697. *
  698. * @description
  699. * Creates a deep copy of `source`, which should be an object or an array.
  700. *
  701. * * If no destination is supplied, a copy of the object or array is created.
  702. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  703. * are deleted and then all elements/properties from the source are copied to it.
  704. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  705. * * If `source` is identical to 'destination' an exception will be thrown.
  706. *
  707. * @param {*} source The source that will be used to make a copy.
  708. * Can be any type, including primitives, `null`, and `undefined`.
  709. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  710. * provided, must be of the same type as `source`.
  711. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  712. *
  713. * @example
  714. <example>
  715. <file name="index.html">
  716. <div ng-controller="Controller">
  717. <form novalidate class="simple-form">
  718. Name: <input type="text" ng-model="user.name" /><br />
  719. E-mail: <input type="email" ng-model="user.email" /><br />
  720. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  721. <input type="radio" ng-model="user.gender" value="female" />female<br />
  722. <button ng-click="reset()">RESET</button>
  723. <button ng-click="update(user)">SAVE</button>
  724. </form>
  725. <pre>form = {{user | json}}</pre>
  726. <pre>master = {{master | json}}</pre>
  727. </div>
  728. <script>
  729. function Controller($scope) {
  730. $scope.master= {};
  731. $scope.update = function(user) {
  732. // Example with 1 argument
  733. $scope.master= angular.copy(user);
  734. };
  735. $scope.reset = function() {
  736. // Example with 2 arguments
  737. angular.copy($scope.master, $scope.user);
  738. };
  739. $scope.reset();
  740. }
  741. </script>
  742. </file>
  743. </example>
  744. */
  745. function copy(source, destination){
  746. if (isWindow(source) || isScope(source)) {
  747. throw ngMinErr('cpws',
  748. "Can't copy! Making copies of Window or Scope instances is not supported.");
  749. }
  750. if (!destination) {
  751. destination = source;
  752. if (source) {
  753. if (isArray(source)) {
  754. destination = copy(source, []);
  755. } else if (isDate(source)) {
  756. destination = new Date(source.getTime());
  757. } else if (isRegExp(source)) {
  758. destination = new RegExp(source.source);
  759. } else if (isObject(source)) {
  760. destination = copy(source, {});
  761. }
  762. }
  763. } else {
  764. if (source === destination) throw ngMinErr('cpi',
  765. "Can't copy! Source and destination are identical.");
  766. if (isArray(source)) {
  767. destination.length = 0;
  768. for ( var i = 0; i < source.length; i++) {
  769. destination.push(copy(source[i]));
  770. }
  771. } else {
  772. var h = destination.$$hashKey;
  773. forEach(destination, function(value, key){
  774. delete destination[key];
  775. });
  776. for ( var key in source) {
  777. destination[key] = copy(source[key]);
  778. }
  779. setHashKey(destination,h);
  780. }
  781. }
  782. return destination;
  783. }
  784. /**
  785. * Create a shallow copy of an object
  786. */
  787. function shallowCopy(src, dst) {
  788. dst = dst || {};
  789. for(var key in src) {
  790. // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
  791. // so we don't need to worry about using our custom hasOwnProperty here
  792. if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  793. dst[key] = src[key];
  794. }
  795. }
  796. return dst;
  797. }
  798. /**
  799. * @ngdoc function
  800. * @name angular.equals
  801. * @module ng
  802. * @function
  803. *
  804. * @description
  805. * Determines if two objects or two values are equivalent. Supports value types, regular
  806. * expressions, arrays and objects.
  807. *
  808. * Two objects or values are considered equivalent if at least one of the following is true:
  809. *
  810. * * Both objects or values pass `===` comparison.
  811. * * Both objects or values are of the same type and all of their properties are equal by
  812. * comparing them with `angular.equals`.
  813. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  814. * * Both values represent the same regular expression (In JavasScript,
  815. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  816. * representation matches).
  817. *
  818. * During a property comparison, properties of `function` type and properties with names
  819. * that begin with `$` are ignored.
  820. *
  821. * Scope and DOMWindow objects are being compared only by identify (`===`).
  822. *
  823. * @param {*} o1 Object or value to compare.
  824. * @param {*} o2 Object or value to compare.
  825. * @returns {boolean} True if arguments are equal.
  826. */
  827. function equals(o1, o2) {
  828. if (o1 === o2) return true;
  829. if (o1 === null || o2 === null) return false;
  830. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  831. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  832. if (t1 == t2) {
  833. if (t1 == 'object') {
  834. if (isArray(o1)) {
  835. if (!isArray(o2)) return false;
  836. if ((length = o1.length) == o2.length) {
  837. for(key=0; key<length; key++) {
  838. if (!equals(o1[key], o2[key])) return false;
  839. }
  840. return true;
  841. }
  842. } else if (isDate(o1)) {
  843. return isDate(o2) && o1.getTime() == o2.getTime();
  844. } else if (isRegExp(o1) && isRegExp(o2)) {
  845. return o1.toString() == o2.toString();
  846. } else {
  847. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  848. keySet = {};
  849. for(key in o1) {
  850. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  851. if (!equals(o1[key], o2[key])) return false;
  852. keySet[key] = true;
  853. }
  854. for(key in o2) {
  855. if (!keySet.hasOwnProperty(key) &&
  856. key.charAt(0) !== '$' &&
  857. o2[key] !== undefined &&
  858. !isFunction(o2[key])) return false;
  859. }
  860. return true;
  861. }
  862. }
  863. }
  864. return false;
  865. }
  866. function csp() {
  867. return (document.securityPolicy && document.securityPolicy.isActive) ||
  868. (document.querySelector &&
  869. !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
  870. }
  871. function concat(array1, array2, index) {
  872. return array1.concat(slice.call(array2, index));
  873. }
  874. function sliceArgs(args, startIndex) {
  875. return slice.call(args, startIndex || 0);
  876. }
  877. /* jshint -W101 */
  878. /**
  879. * @ngdoc function
  880. * @name angular.bind
  881. * @module ng
  882. * @function
  883. *
  884. * @description
  885. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  886. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  887. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  888. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  889. *
  890. * @param {Object} self Context which `fn` should be evaluated in.
  891. * @param {function()} fn Function to be bound.
  892. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  893. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  894. */
  895. /* jshint +W101 */
  896. function bind(self, fn) {
  897. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  898. if (isFunction(fn) && !(fn instanceof RegExp)) {
  899. return curryArgs.length
  900. ? function() {
  901. return arguments.length
  902. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  903. : fn.apply(self, curryArgs);
  904. }
  905. : function() {
  906. return arguments.length
  907. ? fn.apply(self, arguments)
  908. : fn.call(self);
  909. };
  910. } else {
  911. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  912. return fn;
  913. }
  914. }
  915. function toJsonReplacer(key, value) {
  916. var val = value;
  917. if (typeof key === 'string' && key.charAt(0) === '$') {
  918. val = undefined;
  919. } else if (isWindow(value)) {
  920. val = '$WINDOW';
  921. } else if (value && document === value) {
  922. val = '$DOCUMENT';
  923. } else if (isScope(value)) {
  924. val = '$SCOPE';
  925. }
  926. return val;
  927. }
  928. /**
  929. * @ngdoc function
  930. * @name angular.toJson
  931. * @module ng
  932. * @function
  933. *
  934. * @description
  935. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  936. * stripped since angular uses this notation internally.
  937. *
  938. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  939. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  940. * @returns {string|undefined} JSON-ified string representing `obj`.
  941. */
  942. function toJson(obj, pretty) {
  943. if (typeof obj === 'undefined') return undefined;
  944. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  945. }
  946. /**
  947. * @ngdoc function
  948. * @name angular.fromJson
  949. * @module ng
  950. * @function
  951. *
  952. * @description
  953. * Deserializes a JSON string.
  954. *
  955. * @param {string} json JSON string to deserialize.
  956. * @returns {Object|Array|string|number} Deserialized thingy.
  957. */
  958. function fromJson(json) {
  959. return isString(json)
  960. ? JSON.parse(json)
  961. : json;
  962. }
  963. function toBoolean(value) {
  964. if (typeof value === 'function') {
  965. value = true;
  966. } else if (value && value.length !== 0) {
  967. var v = lowercase("" + value);
  968. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  969. } else {
  970. value = false;
  971. }
  972. return value;
  973. }
  974. /**
  975. * @returns {string} Returns the string representation of the element.
  976. */
  977. function startingTag(element) {
  978. element = jqLite(element).clone();
  979. try {
  980. // turns out IE does not let you set .html() on elements which
  981. // are not allowed to have children. So we just ignore it.
  982. element.empty();
  983. } catch(e) {}
  984. // As Per DOM Standards
  985. var TEXT_NODE = 3;
  986. var elemHtml = jqLite('<div>').append(element).html();
  987. try {
  988. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  989. elemHtml.
  990. match(/^(<[^>]+>)/)[1].
  991. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  992. } catch(e) {
  993. return lowercase(elemHtml);
  994. }
  995. }
  996. /////////////////////////////////////////////////
  997. /**
  998. * Tries to decode the URI component without throwing an exception.
  999. *
  1000. * @private
  1001. * @param str value potential URI component to check.
  1002. * @returns {boolean} True if `value` can be decoded
  1003. * with the decodeURIComponent function.
  1004. */
  1005. function tryDecodeURIComponent(value) {
  1006. try {
  1007. return decodeURIComponent(value);
  1008. } catch(e) {
  1009. // Ignore any invalid uri component
  1010. }
  1011. }
  1012. /**
  1013. * Parses an escaped url query string into key-value pairs.
  1014. * @returns {Object.<string,boolean|Array>}
  1015. */
  1016. function parseKeyValue(/**string*/keyValue) {
  1017. var obj = {}, key_value, key;
  1018. forEach((keyValue || "").split('&'), function(keyValue){
  1019. if ( keyValue ) {
  1020. key_value = keyValue.split('=');
  1021. key = tryDecodeURIComponent(key_value[0]);
  1022. if ( isDefined(key) ) {
  1023. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1024. if (!obj[key]) {
  1025. obj[key] = val;
  1026. } else if(isArray(obj[key])) {
  1027. obj[key].push(val);
  1028. } else {
  1029. obj[key] = [obj[key],val];
  1030. }
  1031. }
  1032. }
  1033. });
  1034. return obj;
  1035. }
  1036. function toKeyValue(obj) {
  1037. var parts = [];
  1038. forEach(obj, function(value, key) {
  1039. if (isArray(value)) {
  1040. forEach(value, function(arrayValue) {
  1041. parts.push(encodeUriQuery(key, true) +
  1042. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1043. });
  1044. } else {
  1045. parts.push(encodeUriQuery(key, true) +
  1046. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1047. }
  1048. });
  1049. return parts.length ? parts.join('&') : '';
  1050. }
  1051. /**
  1052. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1053. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1054. * segments:
  1055. * segment = *pchar
  1056. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1057. * pct-encoded = "%" HEXDIG HEXDIG
  1058. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1059. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1060. * / "*" / "+" / "," / ";" / "="
  1061. */
  1062. function encodeUriSegment(val) {
  1063. return encodeUriQuery(val, true).
  1064. replace(/%26/gi, '&').
  1065. replace(/%3D/gi, '=').
  1066. replace(/%2B/gi, '+');
  1067. }
  1068. /**
  1069. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1070. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1071. * encoded per http://tools.ietf.org/html/rfc3986:
  1072. * query = *( pchar / "/" / "?" )
  1073. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1074. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1075. * pct-encoded = "%" HEXDIG HEXDIG
  1076. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1077. * / "*" / "+" / "," / ";" / "="
  1078. */
  1079. function encodeUriQuery(val, pctEncodeSpaces) {
  1080. return encodeURIComponent(val).
  1081. replace(/%40/gi, '@').
  1082. replace(/%3A/gi, ':').
  1083. replace(/%24/g, '$').
  1084. replace(/%2C/gi, ',').
  1085. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1086. }
  1087. /**
  1088. * @ngdoc directive
  1089. * @name ngApp
  1090. * @module ng
  1091. *
  1092. * @element ANY
  1093. * @param {angular.Module} ngApp an optional application
  1094. * {@link angular.module module} name to load.
  1095. *
  1096. * @description
  1097. *
  1098. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1099. * designates the **root element** of the application and is typically placed near the root element
  1100. * of the page - e.g. on the `<body>` or `<html>` tags.
  1101. *
  1102. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1103. * found in the document will be used to define the root element to auto-bootstrap as an
  1104. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1105. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1106. *
  1107. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1108. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1109. * should contain the application code needed or have dependencies on other modules that will
  1110. * contain the code. See {@link angular.module} for more information.
  1111. *
  1112. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1113. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1114. * would not be resolved to `3`.
  1115. *
  1116. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1117. *
  1118. <example module="ngAppDemo">
  1119. <file name="index.html">
  1120. <div ng-controller="ngAppDemoController">
  1121. I can add: {{a}} + {{b}} = {{ a+b }}
  1122. </div>
  1123. </file>
  1124. <file name="script.js">
  1125. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1126. $scope.a = 1;
  1127. $scope.b = 2;
  1128. });
  1129. </file>
  1130. </example>
  1131. *
  1132. */
  1133. function angularInit(element, bootstrap) {
  1134. var elements = [element],
  1135. appElement,
  1136. module,
  1137. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1138. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1139. function append(element) {
  1140. element && elements.push(element);
  1141. }
  1142. forEach(names, function(name) {
  1143. names[name] = true;
  1144. append(document.getElementById(name));
  1145. name = name.replace(':', '\\:');
  1146. if (element.querySelectorAll) {
  1147. forEach(element.querySelectorAll('.' + name), append);
  1148. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1149. forEach(element.querySelectorAll('[' + name + ']'), append);
  1150. }
  1151. });
  1152. forEach(elements, function(element) {
  1153. if (!appElement) {
  1154. var className = ' ' + element.className + ' ';
  1155. var match = NG_APP_CLASS_REGEXP.exec(className);
  1156. if (match) {
  1157. appElement = element;
  1158. module = (match[2] || '').replace(/\s+/g, ',');
  1159. } else {
  1160. forEach(element.attributes, function(attr) {
  1161. if (!appElement && names[attr.name]) {
  1162. appElement = element;
  1163. module = attr.value;
  1164. }
  1165. });
  1166. }
  1167. }
  1168. });
  1169. if (appElement) {
  1170. bootstrap(appElement, module ? [module] : []);
  1171. }
  1172. }
  1173. /**
  1174. * @ngdoc function
  1175. * @name angular.bootstrap
  1176. * @module ng
  1177. * @description
  1178. * Use this function to manually start up angular application.
  1179. *
  1180. * See: {@link guide/bootstrap Bootstrap}
  1181. *
  1182. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1183. * They must use {@link ng.directive:ngApp ngApp}.
  1184. *
  1185. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1186. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1187. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1188. * multiple instances of Angular try to work on the DOM.
  1189. *
  1190. * <example name="multi-bootstrap" module="multi-bootstrap">
  1191. * <file name="index.html">
  1192. * <script src="../../../angular.js"></script>
  1193. * <div ng-controller="BrokenTable">
  1194. * <table>
  1195. * <tr>
  1196. * <th ng-repeat="heading in headings">{{heading}}</th>
  1197. * </tr>
  1198. * <tr ng-repeat="filling in fillings">
  1199. * <td ng-repeat="fill in filling">{{fill}}</td>
  1200. * </tr>
  1201. * </table>
  1202. * </div>
  1203. * </file>
  1204. * <file name="controller.js">
  1205. * var app = angular.module('multi-bootstrap', [])
  1206. *
  1207. * .controller('BrokenTable', function($scope) {
  1208. * $scope.headings = ['One', 'Two', 'Three'];
  1209. * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
  1210. * });
  1211. * </file>
  1212. * <file name="protractor.js" type="protractor">
  1213. * it('should only insert one table cell for each item in $scope.fillings', function() {
  1214. * expect(element.all(by.css('td')).count())
  1215. * .toBe(9);
  1216. * });
  1217. * </file>
  1218. * </example>
  1219. *
  1220. * @param {DOMElement} element DOM element which is the root of angular application.
  1221. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1222. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1223. * function that will be invoked by the injector as a run block.
  1224. * See: {@link angular.module modules}
  1225. * @returns {auto.$injector} Returns the newly created injector for this app.
  1226. */
  1227. function bootstrap(element, modules) {
  1228. var doBootstrap = function() {
  1229. element = jqLite(element);
  1230. if (element.injector()) {
  1231. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1232. throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
  1233. }
  1234. modules = modules || [];
  1235. modules.unshift(['$provide', function($provide) {
  1236. $provide.value('$rootElement', element);
  1237. }]);
  1238. modules.unshift('ng');
  1239. var injector = createInjector(modules);
  1240. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1241. function(scope, element, compile, injector, animate) {
  1242. scope.$apply(function() {
  1243. element.data('$injector', injector);
  1244. compile(element)(scope);
  1245. });
  1246. }]
  1247. );
  1248. return injector;
  1249. };
  1250. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1251. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1252. return doBootstrap();
  1253. }
  1254. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1255. angular.resumeBootstrap = function(extraModules) {
  1256. forEach(extraModules, function(module) {
  1257. modules.push(module);
  1258. });
  1259. doBootstrap();
  1260. };
  1261. }
  1262. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1263. function snake_case(name, separator){
  1264. separator = separator || '_';
  1265. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1266. return (pos ? separator : '') + letter.toLowerCase();
  1267. });
  1268. }
  1269. function bindJQuery() {
  1270. // bind to jQuery if present;
  1271. jQuery = window.jQuery;
  1272. // reset to jQuery or default to us.
  1273. if (jQuery) {
  1274. jqLite = jQuery;
  1275. extend(jQuery.fn, {
  1276. scope: JQLitePrototype.scope,
  1277. isolateScope: JQLitePrototype.isolateScope,
  1278. controller: JQLitePrototype.controller,
  1279. injector: JQLitePrototype.injector,
  1280. inheritedData: JQLitePrototype.inheritedData
  1281. });
  1282. // Method signature:
  1283. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1284. jqLitePatchJQueryRemove('remove', true, true, false);
  1285. jqLitePatchJQueryRemove('empty', false, false, false);
  1286. jqLitePatchJQueryRemove('html', false, false, true);
  1287. } else {
  1288. jqLite = JQLite;
  1289. }
  1290. angular.element = jqLite;
  1291. }
  1292. /**
  1293. * throw error if the argument is falsy.
  1294. */
  1295. function assertArg(arg, name, reason) {
  1296. if (!arg) {
  1297. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1298. }
  1299. return arg;
  1300. }
  1301. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1302. if (acceptArrayAnnotation && isArray(arg)) {
  1303. arg = arg[arg.length - 1];
  1304. }
  1305. assertArg(isFunction(arg), name, 'not a function, got ' +
  1306. (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1307. return arg;
  1308. }
  1309. /**
  1310. * throw error if the name given is hasOwnProperty
  1311. * @param {String} name the name to test
  1312. * @param {String} context the context in which the name is used, such as module or directive
  1313. */
  1314. function assertNotHasOwnProperty(name, context) {
  1315. if (name === 'hasOwnProperty') {
  1316. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1317. }
  1318. }
  1319. /**
  1320. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1321. * @param {Object} obj starting object
  1322. * @param {String} path path to traverse
  1323. * @param {boolean} [bindFnToScope=true]
  1324. * @returns {Object} value as accessible by path
  1325. */
  1326. //TODO(misko): this function needs to be removed
  1327. function getter(obj, path, bindFnToScope) {
  1328. if (!path) return obj;
  1329. var keys = path.split('.');
  1330. var key;
  1331. var lastInstance = obj;
  1332. var len = keys.length;
  1333. for (var i = 0; i < len; i++) {
  1334. key = keys[i];
  1335. if (obj) {
  1336. obj = (lastInstance = obj)[key];
  1337. }
  1338. }
  1339. if (!bindFnToScope && isFunction(obj)) {
  1340. return bind(lastInstance, obj);
  1341. }
  1342. return obj;
  1343. }
  1344. /**
  1345. * Return the DOM siblings between the first and last node in the given array.
  1346. * @param {Array} array like object
  1347. * @returns {DOMElement} object containing the elements
  1348. */
  1349. function getBlockElements(nodes) {
  1350. var startNode = nodes[0],
  1351. endNode = nodes[nodes.length - 1];
  1352. if (startNode === endNode) {
  1353. return jqLite(startNode);
  1354. }
  1355. var element = startNode;
  1356. var elements = [element];
  1357. do {
  1358. element = element.nextSibling;
  1359. if (!element) break;
  1360. elements.push(element);
  1361. } while (element !== endNode);
  1362. return jqLite(elements);
  1363. }
  1364. /**
  1365. * @ngdoc type
  1366. * @name angular.Module
  1367. * @module ng
  1368. * @description
  1369. *
  1370. * Interface for configuring angular {@link angular.module modules}.
  1371. */
  1372. function setupModuleLoader(window) {
  1373. var $injectorMinErr = minErr('$injector');
  1374. var ngMinErr = minErr('ng');
  1375. function ensure(obj, name, factory) {
  1376. return obj[name] || (obj[name] = factory());
  1377. }
  1378. var angular = ensure(window, 'angular', Object);
  1379. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1380. angular.$$minErr = angular.$$minErr || minErr;
  1381. return ensure(angular, 'module', function() {
  1382. /** @type {Object.<string, angular.Module>} */
  1383. var modules = {};
  1384. /**
  1385. * @ngdoc function
  1386. * @name angular.module
  1387. * @module ng
  1388. * @description
  1389. *
  1390. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1391. * modules.
  1392. * All modules (angular core or 3rd party) that should be available to an application must be
  1393. * registered using this mechanism.
  1394. *
  1395. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1396. * existing module (the name passed as the first argument to `module`) is retrieved.
  1397. *
  1398. *
  1399. * # Module
  1400. *
  1401. * A module is a collection of services, directives, filters, and configuration information.
  1402. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1403. *
  1404. * ```js
  1405. * // Create a new module
  1406. * var myModule = angular.module('myModule', []);
  1407. *
  1408. * // register a new service
  1409. * myModule.value('appName', 'MyCoolApp');
  1410. *
  1411. * // configure existing services inside initialization blocks.
  1412. * myModule.config(['$locationProvider', function($locationProvider) {
  1413. * // Configure existing providers
  1414. * $locationProvider.hashPrefix('!');
  1415. * }]);
  1416. * ```
  1417. *
  1418. * Then you can create an injector and load your modules like this:
  1419. *
  1420. * ```js
  1421. * var injector = angular.injector(['ng', 'myModule'])
  1422. * ```
  1423. *
  1424. * However it's more likely that you'll just use
  1425. * {@link ng.directive:ngApp ngApp} or
  1426. * {@link angular.bootstrap} to simplify this process for you.
  1427. *
  1428. * @param {!string} name The name of the module to create or retrieve.
  1429. <<<<<* @param {!Array.<string>=} requires If specified then new module is being created. If
  1430. >>>>>* unspecified then the module is being retrieved for further configuration.
  1431. * @param {Function} configFn Optional configuration function for the module. Same as
  1432. * {@link angular.Module#config Module#config()}.
  1433. * @returns {module} new module with the {@link angular.Module} api.
  1434. */
  1435. return function module(name, requires, configFn) {
  1436. var assertNotHasOwnProperty = function(name, context) {
  1437. if (name === 'hasOwnProperty') {
  1438. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1439. }
  1440. };
  1441. assertNotHasOwnProperty(name, 'module');
  1442. if (requires && modules.hasOwnProperty(name)) {
  1443. modules[name] = null;
  1444. }
  1445. return ensure(modules, name, function() {
  1446. if (!requires) {
  1447. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1448. "the module name or forgot to load it. If registering a module ensure that you " +
  1449. "specify the dependencies as the second argument.", name);
  1450. }
  1451. /** @type {!Array.<Array.<*>>} */
  1452. var invokeQueue = [];
  1453. /** @type {!Array.<Function>} */
  1454. var runBlocks = [];
  1455. var config = invokeLater('$injector', 'invoke');
  1456. /** @type {angular.Module} */
  1457. var moduleInstance = {
  1458. // Private state
  1459. _invokeQueue: invokeQueue,
  1460. _runBlocks: runBlocks,
  1461. /**
  1462. * @ngdoc property
  1463. * @name angular.Module#requires
  1464. * @module ng
  1465. * @returns {Array.<string>} List of module names which must be loaded before this module.
  1466. * @description
  1467. * Holds the list of modules which the injector will load before the current module is
  1468. * loaded.
  1469. */
  1470. requires: requires,
  1471. /**
  1472. * @ngdoc property
  1473. * @name angular.Module#name
  1474. * @module ng
  1475. * @returns {string} Name of the module.
  1476. * @description
  1477. */
  1478. name: name,
  1479. /**
  1480. * @ngdoc method
  1481. * @name angular.Module#provider
  1482. * @module ng
  1483. * @param {string} name service name
  1484. * @param {Function} providerType Construction function for creating new instance of the
  1485. * service.
  1486. * @description
  1487. * See {@link auto.$provide#provider $provide.provider()}.
  1488. */
  1489. provider: invokeLater('$provide', 'provider'),
  1490. /**
  1491. * @ngdoc method
  1492. * @name angular.Module#factory
  1493. * @module ng
  1494. * @param {string} name service name
  1495. * @param {Function} providerFunction Function for creating new instance of the service.
  1496. * @description
  1497. * See {@link auto.$provide#factory $provide.factory()}.
  1498. */
  1499. factory: invokeLater('$provide', 'factory'),
  1500. /**
  1501. * @ngdoc method
  1502. * @name angular.Module#service
  1503. * @module ng
  1504. * @param {string} name service name
  1505. * @param {Function} constructor A constructor function that will be instantiated.
  1506. * @description
  1507. * See {@link auto.$provide#service $provide.service()}.
  1508. */
  1509. service: invokeLater('$provide', 'service'),
  1510. /**
  1511. * @ngdoc method
  1512. * @name angular.Module#value
  1513. * @module ng
  1514. * @param {string} name service name
  1515. * @param {*} object Service instance object.
  1516. * @description
  1517. * See {@link auto.$provide#value $provide.value()}.
  1518. */
  1519. value: invokeLater('$provide', 'value'),
  1520. /**
  1521. * @ngdoc method
  1522. * @name angular.Module#constant
  1523. * @module ng
  1524. * @param {string} name constant name
  1525. * @param {*} object Constant value.
  1526. * @description
  1527. * Because the constant are fixed, they get applied before other provide methods.
  1528. * See {@link auto.$provide#constant $provide.constant()}.
  1529. */
  1530. constant: invokeLater('$provide', 'constant', 'unshift'),
  1531. /**
  1532. * @ngdoc method
  1533. * @name angular.Module#animation
  1534. * @module ng
  1535. * @param {string} name animation name
  1536. * @param {Function} animationFactory Factory function for creating new instance of an
  1537. * animation.
  1538. * @description
  1539. *
  1540. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1541. *
  1542. *
  1543. * Defines an animation hook that can be later used with
  1544. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1545. *
  1546. * ```js
  1547. * module.animation('.animation-name', function($inject1, $inject2) {
  1548. * return {
  1549. * eventName : function(element, done) {
  1550. * //code to run the animation
  1551. * //once complete, then run done()
  1552. * return function cancellationFunction(element) {
  1553. * //code to cancel the animation
  1554. * }
  1555. * }
  1556. * }
  1557. * })
  1558. * ```
  1559. *
  1560. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1561. * {@link ngAnimate ngAnimate module} for more information.
  1562. */
  1563. animation: invokeLater('$animateProvider', 'register'),
  1564. /**
  1565. * @ngdoc method
  1566. * @name angular.Module#filter
  1567. * @module ng
  1568. * @param {string} name Filter name.
  1569. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1570. * @description
  1571. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1572. */
  1573. filter: invokeLater('$filterProvider', 'register'),
  1574. /**
  1575. * @ngdoc method
  1576. * @name angular.Module#controller
  1577. * @module ng
  1578. * @param {string|Object} name Controller name, or an object map of controllers where the
  1579. * keys are the names and the values are the constructors.
  1580. * @param {Function} constructor Controller constructor function.
  1581. * @description
  1582. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1583. */
  1584. controller: invokeLater('$controllerProvider', 'register'),
  1585. /**
  1586. * @ngdoc method
  1587. * @name angular.Module#directive
  1588. * @module ng
  1589. * @param {string|Object} name Directive name, or an object map of directives where the
  1590. * keys are the names and the values are the factories.
  1591. * @param {Function} directiveFactory Factory function for creating new instance of
  1592. * directives.
  1593. * @description
  1594. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1595. */
  1596. directive: invokeLater('$compileProvider', 'directive'),
  1597. /**
  1598. * @ngdoc method
  1599. * @name angular.Module#config
  1600. * @module ng
  1601. * @param {Function} configFn Execute this function on module load. Useful for service
  1602. * configuration.
  1603. * @description
  1604. * Use this method to register work which needs to be performed on module loading.
  1605. */
  1606. config: config,
  1607. /**
  1608. * @ngdoc method
  1609. * @name angular.Module#run
  1610. * @module ng
  1611. * @param {Function} initializationFn Execute this function after injector creation.
  1612. * Useful for application initialization.
  1613. * @description
  1614. * Use this method to register work which should be performed when the injector is done
  1615. * loading all modules.
  1616. */
  1617. run: function(block) {
  1618. runBlocks.push(block);
  1619. return this;
  1620. }
  1621. };
  1622. if (configFn) {
  1623. config(configFn);
  1624. }
  1625. return moduleInstance;
  1626. /**
  1627. * @param {string} provider
  1628. * @param {string} method
  1629. * @param {String=} insertMethod
  1630. * @returns {angular.Module}
  1631. */
  1632. function invokeLater(provider, method, insertMethod) {
  1633. return function() {
  1634. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1635. return moduleInstance;
  1636. };
  1637. }
  1638. });
  1639. };
  1640. });
  1641. }
  1642. /* global
  1643. angularModule: true,
  1644. version: true,
  1645. $LocaleProvider,
  1646. $CompileProvider,
  1647. htmlAnchorDirective,
  1648. inputDirective,
  1649. inputDirective,
  1650. formDirective,
  1651. scriptDirective,
  1652. selectDirective,
  1653. styleDirective,
  1654. optionDirective,
  1655. ngBindDirective,
  1656. ngBindHtmlDirective,
  1657. ngBindTemplateDirective,
  1658. ngClassDirective,
  1659. ngClassEvenDirective,
  1660. ngClassOddDirective,
  1661. ngCspDirective,
  1662. ngCloakDirective,
  1663. ngControllerDirective,
  1664. ngFormDirective,
  1665. ngHideDirective,
  1666. ngIfDirective,
  1667. ngIncludeDirective,
  1668. ngIncludeFillContentDirective,
  1669. ngInitDirective,
  1670. ngNonBindableDirective,
  1671. ngPluralizeDirective,
  1672. ngRepeatDirective,
  1673. ngShowDirective,
  1674. ngStyleDirective,
  1675. ngSwitchDirective,
  1676. ngSwitchWhenDirective,
  1677. ngSwitchDefaultDirective,
  1678. ngOptionsDirective,
  1679. ngTranscludeDirective,
  1680. ngModelDirective,
  1681. ngListDirective,
  1682. ngChangeDirective,
  1683. requiredDirective,
  1684. requiredDirective,
  1685. ngValueDirective,
  1686. ngAttributeAliasDirectives,
  1687. ngEventDirectives,
  1688. $AnchorScrollProvider,
  1689. $AnimateProvider,
  1690. $BrowserProvider,
  1691. $CacheFactoryProvider,
  1692. $ControllerProvider,
  1693. $DocumentProvider,
  1694. $ExceptionHandlerProvider,
  1695. $FilterProvider,
  1696. $InterpolateProvider,
  1697. $IntervalProvider,
  1698. $HttpProvider,
  1699. $HttpBackendProvider,
  1700. $LocationProvider,
  1701. $LogProvider,
  1702. $ParseProvider,
  1703. $RootScopeProvider,
  1704. $QProvider,
  1705. $$SanitizeUriProvider,
  1706. $SceProvider,
  1707. $SceDelegateProvider,
  1708. $SnifferProvider,
  1709. $TemplateCacheProvider,
  1710. $TimeoutProvider,
  1711. $$RAFProvider,
  1712. $$AsyncCallbackProvider,
  1713. $WindowProvider
  1714. */
  1715. /**
  1716. * @ngdoc object
  1717. * @name angular.version
  1718. * @module ng
  1719. * @description
  1720. * An object that contains information about the current AngularJS version. This object has the
  1721. * following properties:
  1722. *
  1723. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1724. * - `major` – `{number}` – Major version number, such as "0".
  1725. * - `minor` – `{number}` – Minor version number, such as "9".
  1726. * - `dot` – `{number}` – Dot version number, such as "18".
  1727. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1728. */
  1729. var version = {
  1730. full: '1.2.16', // all of these placeholder strings will be replaced by grunt's
  1731. major: 1, // package task
  1732. minor: 2,
  1733. dot: 16,
  1734. codeName: 'badger-enumeration'
  1735. };
  1736. function publishExternalAPI(angular){
  1737. extend(angular, {
  1738. 'bootstrap': bootstrap,
  1739. 'copy': copy,
  1740. 'extend': extend,
  1741. 'equals': equals,
  1742. 'element': jqLite,
  1743. 'forEach': forEach,
  1744. 'injector': createInjector,
  1745. 'noop':noop,
  1746. 'bind':bind,
  1747. 'toJson': toJson,
  1748. 'fromJson': fromJson,
  1749. 'identity':identity,
  1750. 'isUndefined': isUndefined,
  1751. 'isDefined': isDefined,
  1752. 'isString': isString,
  1753. 'isFunction': isFunction,
  1754. 'isObject': isObject,
  1755. 'isNumber': isNumber,
  1756. 'isElement': isElement,
  1757. 'isArray': isArray,
  1758. 'version': version,
  1759. 'isDate': isDate,
  1760. 'lowercase': lowercase,
  1761. 'uppercase': uppercase,
  1762. 'callbacks': {counter: 0},
  1763. '$$minErr': minErr,
  1764. '$$csp': csp
  1765. });
  1766. angularModule = setupModuleLoader(window);
  1767. try {
  1768. angularModule('ngLocale');
  1769. } catch (e) {
  1770. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1771. }
  1772. angularModule('ng', ['ngLocale'], ['$provide',
  1773. function ngModule($provide) {
  1774. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1775. $provide.provider({
  1776. $$sanitizeUri: $$SanitizeUriProvider
  1777. });
  1778. $provide.provider('$compile', $CompileProvider).
  1779. directive({
  1780. a: htmlAnchorDirective,
  1781. input: inputDirective,
  1782. textarea: inputDirective,
  1783. form: formDirective,
  1784. script: scriptDirective,
  1785. select: selectDirective,
  1786. style: styleDirective,
  1787. option: optionDirective,
  1788. ngBind: ngBindDirective,
  1789. ngBindHtml: ngBindHtmlDirective,
  1790. ngBindTemplate: ngBindTemplateDirective,
  1791. ngClass: ngClassDirective,
  1792. ngClassEven: ngClassEvenDirective,
  1793. ngClassOdd: ngClassOddDirective,
  1794. ngCloak: ngCloakDirective,
  1795. ngController: ngControllerDirective,
  1796. ngForm: ngFormDirective,
  1797. ngHide: ngHideDirective,
  1798. ngIf: ngIfDirective,
  1799. ngInclude: ngIncludeDirective,
  1800. ngInit: ngInitDirective,
  1801. ngNonBindable: ngNonBindableDirective,
  1802. ngPluralize: ngPluralizeDirective,
  1803. ngRepeat: ngRepeatDirective,
  1804. ngShow: ngShowDirective,
  1805. ngStyle: ngStyleDirective,
  1806. ngSwitch: ngSwitchDirective,
  1807. ngSwitchWhen: ngSwitchWhenDirective,
  1808. ngSwitchDefault: ngSwitchDefaultDirective,
  1809. ngOptions: ngOptionsDirective,
  1810. ngTransclude: ngTranscludeDirective,
  1811. ngModel: ngModelDirective,
  1812. ngList: ngListDirective,
  1813. ngChange: ngChangeDirective,
  1814. required: requiredDirective,
  1815. ngRequired: requiredDirective,
  1816. ngValue: ngValueDirective
  1817. }).
  1818. directive({
  1819. ngInclude: ngIncludeFillContentDirective
  1820. }).
  1821. directive(ngAttributeAliasDirectives).
  1822. directive(ngEventDirectives);
  1823. $provide.provider({
  1824. $anchorScroll: $AnchorScrollProvider,
  1825. $animate: $AnimateProvider,
  1826. $browser: $BrowserProvider,
  1827. $cacheFactory: $CacheFactoryProvider,
  1828. $controller: $ControllerProvider,
  1829. $document: $DocumentProvider,
  1830. $exceptionHandler: $ExceptionHandlerProvider,
  1831. $filter: $FilterProvider,
  1832. $interpolate: $InterpolateProvider,
  1833. $interval: $IntervalProvider,
  1834. $http: $HttpProvider,
  1835. $httpBackend: $HttpBackendProvider,
  1836. $location: $LocationProvider,
  1837. $log: $LogProvider,
  1838. $parse: $ParseProvider,
  1839. $rootScope: $RootScopeProvider,
  1840. $q: $QProvider,
  1841. $sce: $SceProvider,
  1842. $sceDelegate: $SceDelegateProvider,
  1843. $sniffer: $SnifferProvider,
  1844. $templateCache: $TemplateCacheProvider,
  1845. $timeout: $TimeoutProvider,
  1846. $window: $WindowProvider,
  1847. $$rAF: $$RAFProvider,
  1848. $$asyncCallback : $$AsyncCallbackProvider
  1849. });
  1850. }
  1851. ]);
  1852. }
  1853. /* global
  1854. -JQLitePrototype,
  1855. -addEventListenerFn,
  1856. -removeEventListenerFn,
  1857. -BOOLEAN_ATTR
  1858. */
  1859. //////////////////////////////////
  1860. //JQLite
  1861. //////////////////////////////////
  1862. /**
  1863. * @ngdoc function
  1864. * @name angular.element
  1865. * @module ng
  1866. * @function
  1867. *
  1868. * @description
  1869. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1870. *
  1871. * If jQuery is available, `angular.element` is an alias for the
  1872. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1873. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1874. *
  1875. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1876. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1877. * commonly needed functionality with the goal of having a very small footprint.</div>
  1878. *
  1879. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1880. *
  1881. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1882. * jqLite; they are never raw DOM references.</div>
  1883. *
  1884. * ## Angular's jqLite
  1885. * jqLite provides only the following jQuery methods:
  1886. *
  1887. * - [`addClass()`](http://api.jquery.com/addClass/)
  1888. * - [`after()`](http://api.jquery.com/after/)
  1889. * - [`append()`](http://api.jquery.com/append/)
  1890. * - [`attr()`](http://api.jquery.com/attr/)
  1891. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  1892. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1893. * - [`clone()`](http://api.jquery.com/clone/)
  1894. * - [`contents()`](http://api.jquery.com/contents/)
  1895. * - [`css()`](http://api.jquery.com/css/)
  1896. * - [`data()`](http://api.jquery.com/data/)
  1897. * - [`empty()`](http://api.jquery.com/empty/)
  1898. * - [`eq()`](http://api.jquery.com/eq/)
  1899. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1900. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1901. * - [`html()`](http://api.jquery.com/html/)
  1902. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1903. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1904. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1905. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1906. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1907. * - [`prepend()`](http://api.jquery.com/prepend/)
  1908. * - [`prop()`](http://api.jquery.com/prop/)
  1909. * - [`ready()`](http://api.jquery.com/ready/)
  1910. * - [`remove()`](http://api.jquery.com/remove/)
  1911. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1912. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1913. * - [`removeData()`](http://api.jquery.com/removeData/)
  1914. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1915. * - [`text()`](http://api.jquery.com/text/)
  1916. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1917. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1918. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  1919. * - [`val()`](http://api.jquery.com/val/)
  1920. * - [`wrap()`](http://api.jquery.com/wrap/)
  1921. *
  1922. * ## jQuery/jqLite Extras
  1923. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1924. *
  1925. * ### Events
  1926. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1927. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1928. * element before it is removed.
  1929. *
  1930. * ### Methods
  1931. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1932. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1933. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1934. * `'ngModel'`).
  1935. * - `injector()` - retrieves the injector of the current element or its parent.
  1936. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  1937. * element or its parent.
  1938. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  1939. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1940. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1941. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  1942. * parent element is reached.
  1943. *
  1944. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  1945. * @returns {Object} jQuery object.
  1946. */
  1947. var jqCache = JQLite.cache = {},
  1948. jqName = JQLite.expando = 'ng-' + new Date().getTime(),
  1949. jqId = 1,
  1950. addEventListenerFn = (window.document.addEventListener
  1951. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  1952. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  1953. removeEventListenerFn = (window.document.removeEventListener
  1954. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  1955. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  1956. /*
  1957. * !!! This is an undocumented "private" function !!!
  1958. */
  1959. var jqData = JQLite._data = function(node) {
  1960. //jQuery always returns an object on cache miss
  1961. return this.cache[node[this.expando]] || {};
  1962. };
  1963. function jqNextId() { return ++jqId; }
  1964. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  1965. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  1966. var jqLiteMinErr = minErr('jqLite');
  1967. /**
  1968. * Converts snake_case to camelCase.
  1969. * Also there is special case for Moz prefix starting with upper case letter.
  1970. * @param name Name to normalize
  1971. */
  1972. function camelCase(name) {
  1973. return name.
  1974. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  1975. return offset ? letter.toUpperCase() : letter;
  1976. }).
  1977. replace(MOZ_HACK_REGEXP, 'Moz$1');
  1978. }
  1979. /////////////////////////////////////////////
  1980. // jQuery mutation patch
  1981. //
  1982. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  1983. // $destroy event on all DOM nodes being removed.
  1984. //
  1985. /////////////////////////////////////////////
  1986. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  1987. var originalJqFn = jQuery.fn[name];
  1988. originalJqFn = originalJqFn.$original || originalJqFn;
  1989. removePatch.$original = originalJqFn;
  1990. jQuery.fn[name] = removePatch;
  1991. function removePatch(param) {
  1992. // jshint -W040
  1993. var list = filterElems && param ? [this.filter(param)] : [this],
  1994. fireEvent = dispatchThis,
  1995. set, setIndex, setLength,
  1996. element, childIndex, childLength, children;
  1997. if (!getterIfNoArguments || param != null) {
  1998. while(list.length) {
  1999. set = list.shift();
  2000. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  2001. element = jqLite(set[setIndex]);
  2002. if (fireEvent) {
  2003. element.triggerHandler('$destroy');
  2004. } else {
  2005. fireEvent = !fireEvent;
  2006. }
  2007. for(childIndex = 0, childLength = (children = element.children()).length;
  2008. childIndex < childLength;
  2009. childIndex++) {
  2010. list.push(jQuery(children[childIndex]));
  2011. }
  2012. }
  2013. }
  2014. }
  2015. return originalJqFn.apply(this, arguments);
  2016. }
  2017. }
  2018. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2019. var HTML_REGEXP = /<|&#?\w+;/;
  2020. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2021. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2022. var wrapMap = {
  2023. 'option': [1, '<select multiple="multiple">', '</select>'],
  2024. 'thead': [1, '<table>', '</table>'],
  2025. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2026. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2027. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2028. '_default': [0, "", ""]
  2029. };
  2030. wrapMap.optgroup = wrapMap.option;
  2031. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2032. wrapMap.th = wrapMap.td;
  2033. function jqLiteIsTextNode(html) {
  2034. return !HTML_REGEXP.test(html);
  2035. }
  2036. function jqLiteBuildFragment(html, context) {
  2037. var elem, tmp, tag, wrap,
  2038. fragment = context.createDocumentFragment(),
  2039. nodes = [], i, j, jj;
  2040. if (jqLiteIsTextNode(html)) {
  2041. // Convert non-html into a text node
  2042. nodes.push(context.createTextNode(html));
  2043. } else {
  2044. tmp = fragment.appendChild(context.createElement('div'));
  2045. // Convert html into DOM nodes
  2046. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2047. wrap = wrapMap[tag] || wrapMap._default;
  2048. tmp.innerHTML = '<div>&#160;</div>' +
  2049. wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2050. tmp.removeChild(tmp.firstChild);
  2051. // Descend through wrappers to the right content
  2052. i = wrap[0];
  2053. while (i--) {
  2054. tmp = tmp.lastChild;
  2055. }
  2056. for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);
  2057. tmp = fragment.firstChild;
  2058. tmp.textContent = "";
  2059. }
  2060. // Remove wrapper from fragment
  2061. fragment.textContent = "";
  2062. fragment.innerHTML = ""; // Clear inner HTML
  2063. return nodes;
  2064. }
  2065. function jqLiteParseHTML(html, context) {
  2066. context = context || document;
  2067. var parsed;
  2068. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2069. return [context.createElement(parsed[1])];
  2070. }
  2071. return jqLiteBuildFragment(html, context);
  2072. }
  2073. /////////////////////////////////////////////
  2074. function JQLite(element) {
  2075. if (element instanceof JQLite) {
  2076. return element;
  2077. }
  2078. if (isString(element)) {
  2079. element = trim(element);
  2080. }
  2081. if (!(this instanceof JQLite)) {
  2082. if (isString(element) && element.charAt(0) != '<') {
  2083. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2084. }
  2085. return new JQLite(element);
  2086. }
  2087. if (isString(element)) {
  2088. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2089. var fragment = jqLite(document.createDocumentFragment());
  2090. fragment.append(this);
  2091. } else {
  2092. jqLiteAddNodes(this, element);
  2093. }
  2094. }
  2095. function jqLiteClone(element) {
  2096. return element.cloneNode(true);
  2097. }
  2098. function jqLiteDealoc(element){
  2099. jqLiteRemoveData(element);
  2100. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  2101. jqLiteDealoc(children[i]);
  2102. }
  2103. }
  2104. function jqLiteOff(element, type, fn, unsupported) {
  2105. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2106. var events = jqLiteExpandoStore(element, 'events'),
  2107. handle = jqLiteExpandoStore(element, 'handle');
  2108. if (!handle) return; //no listeners registered
  2109. if (isUndefined(type)) {
  2110. forEach(events, function(eventHandler, type) {
  2111. removeEventListenerFn(element, type, eventHandler);
  2112. delete events[type];
  2113. });
  2114. } else {
  2115. forEach(type.split(' '), function(type) {
  2116. if (isUndefined(fn)) {
  2117. removeEventListenerFn(element, type, events[type]);
  2118. delete events[type];
  2119. } else {
  2120. arrayRemove(events[type] || [], fn);
  2121. }
  2122. });
  2123. }
  2124. }
  2125. function jqLiteRemoveData(element, name) {
  2126. var expandoId = element[jqName],
  2127. expandoStore = jqCache[expandoId];
  2128. if (expandoStore) {
  2129. if (name) {
  2130. delete jqCache[expandoId].data[name];
  2131. return;
  2132. }
  2133. if (expandoStore.handle) {
  2134. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  2135. jqLiteOff(element);
  2136. }
  2137. delete jqCache[expandoId];
  2138. element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
  2139. }
  2140. }
  2141. function jqLiteExpandoStore(element, key, value) {
  2142. var expandoId = element[jqName],
  2143. expandoStore = jqCache[expandoId || -1];
  2144. if (isDefined(value)) {
  2145. if (!expandoStore) {
  2146. element[jqName] = expandoId = jqNextId();
  2147. expandoStore = jqCache[expandoId] = {};
  2148. }
  2149. expandoStore[key] = value;
  2150. } else {
  2151. return expandoStore && expandoStore[key];
  2152. }
  2153. }
  2154. function jqLiteData(element, key, value) {
  2155. var data = jqLiteExpandoStore(element, 'data'),
  2156. isSetter = isDefined(value),
  2157. keyDefined = !isSetter && isDefined(key),
  2158. isSimpleGetter = keyDefined && !isObject(key);
  2159. if (!data && !isSimpleGetter) {
  2160. jqLiteExpandoStore(element, 'data', data = {});
  2161. }
  2162. if (isSetter) {
  2163. data[key] = value;
  2164. } else {
  2165. if (keyDefined) {
  2166. if (isSimpleGetter) {
  2167. // don't create data in this case.
  2168. return data && data[key];
  2169. } else {
  2170. extend(data, key);
  2171. }
  2172. } else {
  2173. return data;
  2174. }
  2175. }
  2176. }
  2177. function jqLiteHasClass(element, selector) {
  2178. if (!element.getAttribute) return false;
  2179. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2180. indexOf( " " + selector + " " ) > -1);
  2181. }
  2182. function jqLiteRemoveClass(element, cssClasses) {
  2183. if (cssClasses && element.setAttribute) {
  2184. forEach(cssClasses.split(' '), function(cssClass) {
  2185. element.setAttribute('class', trim(
  2186. (" " + (element.getAttribute('class') || '') + " ")
  2187. .replace(/[\n\t]/g, " ")
  2188. .replace(" " + trim(cssClass) + " ", " "))
  2189. );
  2190. });
  2191. }
  2192. }
  2193. function jqLiteAddClass(element, cssClasses) {
  2194. if (cssClasses && element.setAttribute) {
  2195. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2196. .replace(/[\n\t]/g, " ");
  2197. forEach(cssClasses.split(' '), function(cssClass) {
  2198. cssClass = trim(cssClass);
  2199. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2200. existingClasses += cssClass + ' ';
  2201. }
  2202. });
  2203. element.setAttribute('class', trim(existingClasses));
  2204. }
  2205. }
  2206. function jqLiteAddNodes(root, elements) {
  2207. if (elements) {
  2208. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2209. ? elements
  2210. : [ elements ];
  2211. for(var i=0; i < elements.length; i++) {
  2212. root.push(elements[i]);
  2213. }
  2214. }
  2215. }
  2216. function jqLiteController(element, name) {
  2217. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2218. }
  2219. function jqLiteInheritedData(element, name, value) {
  2220. element = jqLite(element);
  2221. // if element is the document object work with the html element instead
  2222. // this makes $(document).scope() possible
  2223. if(element[0].nodeType == 9) {
  2224. element = element.find('html');
  2225. }
  2226. var names = isArray(name) ? name : [name];
  2227. while (element.length) {
  2228. var node = element[0];
  2229. for (var i = 0, ii = names.length; i < ii; i++) {
  2230. if ((value = element.data(names[i])) !== undefined) return value;
  2231. }
  2232. // If dealing with a document fragment node with a host element, and no parent, use the host
  2233. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2234. // to lookup parent controllers.
  2235. element = jqLite(node.parentNode || (node.nodeType === 11 && node.host));
  2236. }
  2237. }
  2238. function jqLiteEmpty(element) {
  2239. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2240. jqLiteDealoc(childNodes[i]);
  2241. }
  2242. while (element.firstChild) {
  2243. element.removeChild(element.firstChild);
  2244. }
  2245. }
  2246. //////////////////////////////////////////
  2247. // Functions which are declared directly.
  2248. //////////////////////////////////////////
  2249. var JQLitePrototype = JQLite.prototype = {
  2250. ready: function(fn) {
  2251. var fired = false;
  2252. function trigger() {
  2253. if (fired) return;
  2254. fired = true;
  2255. fn();
  2256. }
  2257. // check if document already is loaded
  2258. if (document.readyState === 'complete'){
  2259. setTimeout(trigger);
  2260. } else {
  2261. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2262. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2263. // jshint -W064
  2264. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2265. // jshint +W064
  2266. }
  2267. },
  2268. toString: function() {
  2269. var value = [];
  2270. forEach(this, function(e){ value.push('' + e);});
  2271. return '[' + value.join(', ') + ']';
  2272. },
  2273. eq: function(index) {
  2274. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2275. },
  2276. length: 0,
  2277. push: push,
  2278. sort: [].sort,
  2279. splice: [].splice
  2280. };
  2281. //////////////////////////////////////////
  2282. // Functions iterating getter/setters.
  2283. // these functions return self on setter and
  2284. // value on get.
  2285. //////////////////////////////////////////
  2286. var BOOLEAN_ATTR = {};
  2287. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2288. BOOLEAN_ATTR[lowercase(value)] = value;
  2289. });
  2290. var BOOLEAN_ELEMENTS = {};
  2291. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2292. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2293. });
  2294. function getBooleanAttrName(element, name) {
  2295. // check dom last since we will most likely fail on name
  2296. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2297. // booleanAttr is here twice to minimize DOM access
  2298. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2299. }
  2300. forEach({
  2301. data: jqLiteData,
  2302. inheritedData: jqLiteInheritedData,
  2303. scope: function(element) {
  2304. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2305. return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2306. },
  2307. isolateScope: function(element) {
  2308. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2309. return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
  2310. },
  2311. controller: jqLiteController,
  2312. injector: function(element) {
  2313. return jqLiteInheritedData(element, '$injector');
  2314. },
  2315. removeAttr: function(element,name) {
  2316. element.removeAttribute(name);
  2317. },
  2318. hasClass: jqLiteHasClass,
  2319. css: function(element, name, value) {
  2320. name = camelCase(name);
  2321. if (isDefined(value)) {
  2322. element.style[name] = value;
  2323. } else {
  2324. var val;
  2325. if (msie <= 8) {
  2326. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2327. val = element.currentStyle && element.currentStyle[name];
  2328. if (val === '') val = 'auto';
  2329. }
  2330. val = val || element.style[name];
  2331. if (msie <= 8) {
  2332. // jquery weirdness :-/
  2333. val = (val === '') ? undefined : val;
  2334. }
  2335. return val;
  2336. }
  2337. },
  2338. attr: function(element, name, value){
  2339. var lowercasedName = lowercase(name);
  2340. if (BOOLEAN_ATTR[lowercasedName]) {
  2341. if (isDefined(value)) {
  2342. if (!!value) {
  2343. element[name] = true;
  2344. element.setAttribute(name, lowercasedName);
  2345. } else {
  2346. element[name] = false;
  2347. element.removeAttribute(lowercasedName);
  2348. }
  2349. } else {
  2350. return (element[name] ||
  2351. (element.attributes.getNamedItem(name)|| noop).specified)
  2352. ? lowercasedName
  2353. : undefined;
  2354. }
  2355. } else if (isDefined(value)) {
  2356. element.setAttribute(name, value);
  2357. } else if (element.getAttribute) {
  2358. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2359. // some elements (e.g. Document) don't have get attribute, so return undefined
  2360. var ret = element.getAttribute(name, 2);
  2361. // normalize non-existing attributes to undefined (as jQuery)
  2362. return ret === null ? undefined : ret;
  2363. }
  2364. },
  2365. prop: function(element, name, value) {
  2366. if (isDefined(value)) {
  2367. element[name] = value;
  2368. } else {
  2369. return element[name];
  2370. }
  2371. },
  2372. text: (function() {
  2373. var NODE_TYPE_TEXT_PROPERTY = [];
  2374. if (msie < 9) {
  2375. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2376. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2377. } else {
  2378. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2379. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2380. }
  2381. getText.$dv = '';
  2382. return getText;
  2383. function getText(element, value) {
  2384. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2385. if (isUndefined(value)) {
  2386. return textProp ? element[textProp] : '';
  2387. }
  2388. element[textProp] = value;
  2389. }
  2390. })(),
  2391. val: function(element, value) {
  2392. if (isUndefined(value)) {
  2393. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2394. var result = [];
  2395. forEach(element.options, function (option) {
  2396. if (option.selected) {
  2397. result.push(option.value || option.text);
  2398. }
  2399. });
  2400. return result.length === 0 ? null : result;
  2401. }
  2402. return element.value;
  2403. }
  2404. element.value = value;
  2405. },
  2406. html: function(element, value) {
  2407. if (isUndefined(value)) {
  2408. return element.innerHTML;
  2409. }
  2410. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2411. jqLiteDealoc(childNodes[i]);
  2412. }
  2413. element.innerHTML = value;
  2414. },
  2415. empty: jqLiteEmpty
  2416. }, function(fn, name){
  2417. /**
  2418. * Properties: writes return selection, reads return first value
  2419. */
  2420. JQLite.prototype[name] = function(arg1, arg2) {
  2421. var i, key;
  2422. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2423. // in a way that survives minification.
  2424. // jqLiteEmpty takes no arguments but is a setter.
  2425. if (fn !== jqLiteEmpty &&
  2426. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2427. if (isObject(arg1)) {
  2428. // we are a write, but the object properties are the key/values
  2429. for (i = 0; i < this.length; i++) {
  2430. if (fn === jqLiteData) {
  2431. // data() takes the whole object in jQuery
  2432. fn(this[i], arg1);
  2433. } else {
  2434. for (key in arg1) {
  2435. fn(this[i], key, arg1[key]);
  2436. }
  2437. }
  2438. }
  2439. // return self for chaining
  2440. return this;
  2441. } else {
  2442. // we are a read, so read the first child.
  2443. var value = fn.$dv;
  2444. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2445. var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
  2446. for (var j = 0; j < jj; j++) {
  2447. var nodeValue = fn(this[j], arg1, arg2);
  2448. value = value ? value + nodeValue : nodeValue;
  2449. }
  2450. return value;
  2451. }
  2452. } else {
  2453. // we are a write, so apply to all children
  2454. for (i = 0; i < this.length; i++) {
  2455. fn(this[i], arg1, arg2);
  2456. }
  2457. // return self for chaining
  2458. return this;
  2459. }
  2460. };
  2461. });
  2462. function createEventHandler(element, events) {
  2463. var eventHandler = function (event, type) {
  2464. if (!event.preventDefault) {
  2465. event.preventDefault = function() {
  2466. event.returnValue = false; //ie
  2467. };
  2468. }
  2469. if (!event.stopPropagation) {
  2470. event.stopPropagation = function() {
  2471. event.cancelBubble = true; //ie
  2472. };
  2473. }
  2474. if (!event.target) {
  2475. event.target = event.srcElement || document;
  2476. }
  2477. if (isUndefined(event.defaultPrevented)) {
  2478. var prevent = event.preventDefault;
  2479. event.preventDefault = function() {
  2480. event.defaultPrevented = true;
  2481. prevent.call(event);
  2482. };
  2483. event.defaultPrevented = false;
  2484. }
  2485. event.isDefaultPrevented = function() {
  2486. return event.defaultPrevented || event.returnValue === false;
  2487. };
  2488. // Copy event handlers in case event handlers array is modified during execution.
  2489. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2490. forEach(eventHandlersCopy, function(fn) {
  2491. fn.call(element, event);
  2492. });
  2493. // Remove monkey-patched methods (IE),
  2494. // as they would cause memory leaks in IE8.
  2495. if (msie <= 8) {
  2496. // IE7/8 does not allow to delete property on native object
  2497. event.preventDefault = null;
  2498. event.stopPropagation = null;
  2499. event.isDefaultPrevented = null;
  2500. } else {
  2501. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2502. delete event.preventDefault;
  2503. delete event.stopPropagation;
  2504. delete event.isDefaultPrevented;
  2505. }
  2506. };
  2507. eventHandler.elem = element;
  2508. return eventHandler;
  2509. }
  2510. //////////////////////////////////////////
  2511. // Functions iterating traversal.
  2512. // These functions chain results into a single
  2513. // selector.
  2514. //////////////////////////////////////////
  2515. forEach({
  2516. removeData: jqLiteRemoveData,
  2517. dealoc: jqLiteDealoc,
  2518. on: function onFn(element, type, fn, unsupported){
  2519. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2520. var events = jqLiteExpandoStore(element, 'events'),
  2521. handle = jqLiteExpandoStore(element, 'handle');
  2522. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2523. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2524. forEach(type.split(' '), function(type){
  2525. var eventFns = events[type];
  2526. if (!eventFns) {
  2527. if (type == 'mouseenter' || type == 'mouseleave') {
  2528. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2529. function( a, b ) {
  2530. // jshint bitwise: false
  2531. var adown = a.nodeType === 9 ? a.documentElement : a,
  2532. bup = b && b.parentNode;
  2533. return a === bup || !!( bup && bup.nodeType === 1 && (
  2534. adown.contains ?
  2535. adown.contains( bup ) :
  2536. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2537. ));
  2538. } :
  2539. function( a, b ) {
  2540. if ( b ) {
  2541. while ( (b = b.parentNode) ) {
  2542. if ( b === a ) {
  2543. return true;
  2544. }
  2545. }
  2546. }
  2547. return false;
  2548. };
  2549. events[type] = [];
  2550. // Refer to jQuery's implementation of mouseenter & mouseleave
  2551. // Read about mouseenter and mouseleave:
  2552. // http://www.quirksmode.org/js/events_mouse.html#link8
  2553. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2554. onFn(element, eventmap[type], function(event) {
  2555. var target = this, related = event.relatedTarget;
  2556. // For mousenter/leave call the handler if related is outside the target.
  2557. // NB: No relatedTarget if the mouse left/entered the browser window
  2558. if ( !related || (related !== target && !contains(target, related)) ){
  2559. handle(event, type);
  2560. }
  2561. });
  2562. } else {
  2563. addEventListenerFn(element, type, handle);
  2564. events[type] = [];
  2565. }
  2566. eventFns = events[type];
  2567. }
  2568. eventFns.push(fn);
  2569. });
  2570. },
  2571. off: jqLiteOff,
  2572. one: function(element, type, fn) {
  2573. element = jqLite(element);
  2574. //add the listener twice so that when it is called
  2575. //you can remove the original function and still be
  2576. //able to call element.off(ev, fn) normally
  2577. element.on(type, function onFn() {
  2578. element.off(type, fn);
  2579. element.off(type, onFn);
  2580. });
  2581. element.on(type, fn);
  2582. },
  2583. replaceWith: function(element, replaceNode) {
  2584. var index, parent = element.parentNode;
  2585. jqLiteDealoc(element);
  2586. forEach(new JQLite(replaceNode), function(node){
  2587. if (index) {
  2588. parent.insertBefore(node, index.nextSibling);
  2589. } else {
  2590. parent.replaceChild(node, element);
  2591. }
  2592. index = node;
  2593. });
  2594. },
  2595. children: function(element) {
  2596. var children = [];
  2597. forEach(element.childNodes, function(element){
  2598. if (element.nodeType === 1)
  2599. children.push(element);
  2600. });
  2601. return children;
  2602. },
  2603. contents: function(element) {
  2604. return element.contentDocument || element.childNodes || [];
  2605. },
  2606. append: function(element, node) {
  2607. forEach(new JQLite(node), function(child){
  2608. if (element.nodeType === 1 || element.nodeType === 11) {
  2609. element.appendChild(child);
  2610. }
  2611. });
  2612. },
  2613. prepend: function(element, node) {
  2614. if (element.nodeType === 1) {
  2615. var index = element.firstChild;
  2616. forEach(new JQLite(node), function(child){
  2617. element.insertBefore(child, index);
  2618. });
  2619. }
  2620. },
  2621. wrap: function(element, wrapNode) {
  2622. wrapNode = jqLite(wrapNode)[0];
  2623. var parent = element.parentNode;
  2624. if (parent) {
  2625. parent.replaceChild(wrapNode, element);
  2626. }
  2627. wrapNode.appendChild(element);
  2628. },
  2629. remove: function(element) {
  2630. jqLiteDealoc(element);
  2631. var parent = element.parentNode;
  2632. if (parent) parent.removeChild(element);
  2633. },
  2634. after: function(element, newElement) {
  2635. var index = element, parent = element.parentNode;
  2636. forEach(new JQLite(newElement), function(node){
  2637. parent.insertBefore(node, index.nextSibling);
  2638. index = node;
  2639. });
  2640. },
  2641. addClass: jqLiteAddClass,
  2642. removeClass: jqLiteRemoveClass,
  2643. toggleClass: function(element, selector, condition) {
  2644. if (selector) {
  2645. forEach(selector.split(' '), function(className){
  2646. var classCondition = condition;
  2647. if (isUndefined(classCondition)) {
  2648. classCondition = !jqLiteHasClass(element, className);
  2649. }
  2650. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2651. });
  2652. }
  2653. },
  2654. parent: function(element) {
  2655. var parent = element.parentNode;
  2656. return parent && parent.nodeType !== 11 ? parent : null;
  2657. },
  2658. next: function(element) {
  2659. if (element.nextElementSibling) {
  2660. return element.nextElementSibling;
  2661. }
  2662. // IE8 doesn't have nextElementSibling
  2663. var elm = element.nextSibling;
  2664. while (elm != null && elm.nodeType !== 1) {
  2665. elm = elm.nextSibling;
  2666. }
  2667. return elm;
  2668. },
  2669. find: function(element, selector) {
  2670. if (element.getElementsByTagName) {
  2671. return element.getElementsByTagName(selector);
  2672. } else {
  2673. return [];
  2674. }
  2675. },
  2676. clone: jqLiteClone,
  2677. triggerHandler: function(element, eventName, eventData) {
  2678. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2679. eventData = eventData || [];
  2680. var event = [{
  2681. preventDefault: noop,
  2682. stopPropagation: noop
  2683. }];
  2684. forEach(eventFns, function(fn) {
  2685. fn.apply(element, event.concat(eventData));
  2686. });
  2687. }
  2688. }, function(fn, name){
  2689. /**
  2690. * chaining functions
  2691. */
  2692. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2693. var value;
  2694. for(var i=0; i < this.length; i++) {
  2695. if (isUndefined(value)) {
  2696. value = fn(this[i], arg1, arg2, arg3);
  2697. if (isDefined(value)) {
  2698. // any function which returns a value needs to be wrapped
  2699. value = jqLite(value);
  2700. }
  2701. } else {
  2702. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2703. }
  2704. }
  2705. return isDefined(value) ? value : this;
  2706. };
  2707. // bind legacy bind/unbind to on/off
  2708. JQLite.prototype.bind = JQLite.prototype.on;
  2709. JQLite.prototype.unbind = JQLite.prototype.off;
  2710. });
  2711. /**
  2712. * Computes a hash of an 'obj'.
  2713. * Hash of a:
  2714. * string is string
  2715. * number is number as string
  2716. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2717. * that is also assigned to the $$hashKey property of the object.
  2718. *
  2719. * @param obj
  2720. * @returns {string} hash string such that the same input will have the same hash string.
  2721. * The resulting string key is in 'type:hashKey' format.
  2722. */
  2723. function hashKey(obj) {
  2724. var objType = typeof obj,
  2725. key;
  2726. if (objType == 'object' && obj !== null) {
  2727. if (typeof (key = obj.$$hashKey) == 'function') {
  2728. // must invoke on object to keep the right this
  2729. key = obj.$$hashKey();
  2730. } else if (key === undefined) {
  2731. key = obj.$$hashKey = nextUid();
  2732. }
  2733. } else {
  2734. key = obj;
  2735. }
  2736. return objType + ':' + key;
  2737. }
  2738. /**
  2739. * HashMap which can use objects as keys
  2740. */
  2741. function HashMap(array){
  2742. forEach(array, this.put, this);
  2743. }
  2744. HashMap.prototype = {
  2745. /**
  2746. * Store key value pair
  2747. * @param key key to store can be any type
  2748. * @param value value to store can be any type
  2749. */
  2750. put: function(key, value) {
  2751. this[hashKey(key)] = value;
  2752. },
  2753. /**
  2754. * @param key
  2755. * @returns {Object} the value for the key
  2756. */
  2757. get: function(key) {
  2758. return this[hashKey(key)];
  2759. },
  2760. /**
  2761. * Remove the key/value pair
  2762. * @param key
  2763. */
  2764. remove: function(key) {
  2765. var value = this[key = hashKey(key)];
  2766. delete this[key];
  2767. return value;
  2768. }
  2769. };
  2770. /**
  2771. * @ngdoc function
  2772. * @module ng
  2773. * @name angular.injector
  2774. * @function
  2775. *
  2776. * @description
  2777. * Creates an injector function that can be used for retrieving services as well as for
  2778. * dependency injection (see {@link guide/di dependency injection}).
  2779. *
  2780. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2781. * {@link angular.module}. The `ng` module must be explicitly added.
  2782. * @returns {function()} Injector function. See {@link auto.$injector $injector}.
  2783. *
  2784. * @example
  2785. * Typical usage
  2786. * ```js
  2787. * // create an injector
  2788. * var $injector = angular.injector(['ng']);
  2789. *
  2790. * // use the injector to kick off your application
  2791. * // use the type inference to auto inject arguments, or use implicit injection
  2792. * $injector.invoke(function($rootScope, $compile, $document){
  2793. * $compile($document)($rootScope);
  2794. * $rootScope.$digest();
  2795. * });
  2796. * ```
  2797. *
  2798. * Sometimes you want to get access to the injector of a currently running Angular app
  2799. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2800. * application has been bootstrapped. You can do this using extra `injector()` added
  2801. * to JQuery/jqLite elements. See {@link angular.element}.
  2802. *
  2803. * *This is fairly rare but could be the case if a third party library is injecting the
  2804. * markup.*
  2805. *
  2806. * In the following example a new block of HTML containing a `ng-controller`
  2807. * directive is added to the end of the document body by JQuery. We then compile and link
  2808. * it into the current AngularJS scope.
  2809. *
  2810. * ```js
  2811. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2812. * $(document.body).append($div);
  2813. *
  2814. * angular.element(document).injector().invoke(function($compile) {
  2815. * var scope = angular.element($div).scope();
  2816. * $compile($div)(scope);
  2817. * });
  2818. * ```
  2819. */
  2820. /**
  2821. * @ngdoc module
  2822. * @name auto
  2823. * @description
  2824. *
  2825. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2826. */
  2827. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2828. var FN_ARG_SPLIT = /,/;
  2829. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2830. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2831. var $injectorMinErr = minErr('$injector');
  2832. function annotate(fn) {
  2833. var $inject,
  2834. fnText,
  2835. argDecl,
  2836. last;
  2837. if (typeof fn == 'function') {
  2838. if (!($inject = fn.$inject)) {
  2839. $inject = [];
  2840. if (fn.length) {
  2841. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2842. argDecl = fnText.match(FN_ARGS);
  2843. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2844. arg.replace(FN_ARG, function(all, underscore, name){
  2845. $inject.push(name);
  2846. });
  2847. });
  2848. }
  2849. fn.$inject = $inject;
  2850. }
  2851. } else if (isArray(fn)) {
  2852. last = fn.length - 1;
  2853. assertArgFn(fn[last], 'fn');
  2854. $inject = fn.slice(0, last);
  2855. } else {
  2856. assertArgFn(fn, 'fn', true);
  2857. }
  2858. return $inject;
  2859. }
  2860. ///////////////////////////////////////
  2861. /**
  2862. * @ngdoc service
  2863. * @name $injector
  2864. * @function
  2865. *
  2866. * @description
  2867. *
  2868. * `$injector` is used to retrieve object instances as defined by
  2869. * {@link auto.$provide provider}, instantiate types, invoke methods,
  2870. * and load modules.
  2871. *
  2872. * The following always holds true:
  2873. *
  2874. * ```js
  2875. * var $injector = angular.injector();
  2876. * expect($injector.get('$injector')).toBe($injector);
  2877. * expect($injector.invoke(function($injector){
  2878. * return $injector;
  2879. * }).toBe($injector);
  2880. * ```
  2881. *
  2882. * # Injection Function Annotation
  2883. *
  2884. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2885. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2886. *
  2887. * ```js
  2888. * // inferred (only works if code not minified/obfuscated)
  2889. * $injector.invoke(function(serviceA){});
  2890. *
  2891. * // annotated
  2892. * function explicit(serviceA) {};
  2893. * explicit.$inject = ['serviceA'];
  2894. * $injector.invoke(explicit);
  2895. *
  2896. * // inline
  2897. * $injector.invoke(['serviceA', function(serviceA){}]);
  2898. * ```
  2899. *
  2900. * ## Inference
  2901. *
  2902. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2903. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2904. * minification, and obfuscation tools since these tools change the argument names.
  2905. *
  2906. * ## `$inject` Annotation
  2907. * By adding a `$inject` property onto a function the injection parameters can be specified.
  2908. *
  2909. * ## Inline
  2910. * As an array of injection names, where the last item in the array is the function to call.
  2911. */
  2912. /**
  2913. * @ngdoc method
  2914. * @name $injector#get
  2915. *
  2916. * @description
  2917. * Return an instance of the service.
  2918. *
  2919. * @param {string} name The name of the instance to retrieve.
  2920. * @return {*} The instance.
  2921. */
  2922. /**
  2923. * @ngdoc method
  2924. * @name $injector#invoke
  2925. *
  2926. * @description
  2927. * Invoke the method and supply the method arguments from the `$injector`.
  2928. *
  2929. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  2930. * {@link guide/di $inject Annotation} rules.
  2931. * @param {Object=} self The `this` for the invoked method.
  2932. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2933. * object first, before the `$injector` is consulted.
  2934. * @returns {*} the value returned by the invoked `fn` function.
  2935. */
  2936. /**
  2937. * @ngdoc method
  2938. * @name $injector#has
  2939. *
  2940. * @description
  2941. * Allows the user to query if the particular service exist.
  2942. *
  2943. * @param {string} Name of the service to query.
  2944. * @returns {boolean} returns true if injector has given service.
  2945. */
  2946. /**
  2947. * @ngdoc method
  2948. * @name $injector#instantiate
  2949. * @description
  2950. * Create a new instance of JS type. The method takes a constructor function invokes the new
  2951. * operator and supplies all of the arguments to the constructor function as specified by the
  2952. * constructor annotation.
  2953. *
  2954. * @param {Function} Type Annotated constructor function.
  2955. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2956. * object first, before the `$injector` is consulted.
  2957. * @returns {Object} new instance of `Type`.
  2958. */
  2959. /**
  2960. * @ngdoc method
  2961. * @name $injector#annotate
  2962. *
  2963. * @description
  2964. * Returns an array of service names which the function is requesting for injection. This API is
  2965. * used by the injector to determine which services need to be injected into the function when the
  2966. * function is invoked. There are three ways in which the function can be annotated with the needed
  2967. * dependencies.
  2968. *
  2969. * # Argument names
  2970. *
  2971. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  2972. * by converting the function into a string using `toString()` method and extracting the argument
  2973. * names.
  2974. * ```js
  2975. * // Given
  2976. * function MyController($scope, $route) {
  2977. * // ...
  2978. * }
  2979. *
  2980. * // Then
  2981. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  2982. * ```
  2983. *
  2984. * This method does not work with code minification / obfuscation. For this reason the following
  2985. * annotation strategies are supported.
  2986. *
  2987. * # The `$inject` property
  2988. *
  2989. * If a function has an `$inject` property and its value is an array of strings, then the strings
  2990. * represent names of services to be injected into the function.
  2991. * ```js
  2992. * // Given
  2993. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  2994. * // ...
  2995. * }
  2996. * // Define function dependencies
  2997. * MyController['$inject'] = ['$scope', '$route'];
  2998. *
  2999. * // Then
  3000. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3001. * ```
  3002. *
  3003. * # The array notation
  3004. *
  3005. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3006. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3007. * a way that survives minification is a better choice:
  3008. *
  3009. * ```js
  3010. * // We wish to write this (not minification / obfuscation safe)
  3011. * injector.invoke(function($compile, $rootScope) {
  3012. * // ...
  3013. * });
  3014. *
  3015. * // We are forced to write break inlining
  3016. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3017. * // ...
  3018. * };
  3019. * tmpFn.$inject = ['$compile', '$rootScope'];
  3020. * injector.invoke(tmpFn);
  3021. *
  3022. * // To better support inline function the inline annotation is supported
  3023. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3024. * // ...
  3025. * }]);
  3026. *
  3027. * // Therefore
  3028. * expect(injector.annotate(
  3029. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3030. * ).toEqual(['$compile', '$rootScope']);
  3031. * ```
  3032. *
  3033. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3034. * be retrieved as described above.
  3035. *
  3036. * @returns {Array.<string>} The names of the services which the function requires.
  3037. */
  3038. /**
  3039. * @ngdoc object
  3040. * @name $provide
  3041. *
  3042. * @description
  3043. *
  3044. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3045. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3046. * {@link angular.Module}.
  3047. *
  3048. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3049. * factories** are functions which, in turn, are created by a **service provider**.
  3050. * The **service providers** are constructor functions. When instantiated they must contain a
  3051. * property called `$get`, which holds the **service factory** function.
  3052. *
  3053. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3054. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3055. * function to get the instance of the **service**.
  3056. *
  3057. * Often services have no configuration options and there is no need to add methods to the service
  3058. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3059. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3060. * services without specifying a provider.
  3061. *
  3062. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3063. * {@link auto.$injector $injector}
  3064. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3065. * providers and services.
  3066. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3067. * services, not providers.
  3068. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3069. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3070. * given factory function.
  3071. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3072. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3073. * a new object using the given constructor function.
  3074. *
  3075. * See the individual methods for more information and examples.
  3076. */
  3077. /**
  3078. * @ngdoc method
  3079. * @name $provide#provider
  3080. * @description
  3081. *
  3082. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3083. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3084. * service.
  3085. *
  3086. * Service provider names start with the name of the service they provide followed by `Provider`.
  3087. * For example, the {@link ng.$log $log} service has a provider called
  3088. * {@link ng.$logProvider $logProvider}.
  3089. *
  3090. * Service provider objects can have additional methods which allow configuration of the provider
  3091. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3092. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3093. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3094. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3095. * console or not.
  3096. *
  3097. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3098. 'Provider'` key.
  3099. * @param {(Object|function())} provider If the provider is:
  3100. *
  3101. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3102. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3103. * - `Constructor`: a new instance of the provider will be created using
  3104. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3105. *
  3106. * @returns {Object} registered provider instance
  3107. * @example
  3108. *
  3109. * The following example shows how to create a simple event tracking service and register it using
  3110. * {@link auto.$provide#provider $provide.provider()}.
  3111. *
  3112. * ```js
  3113. * // Define the eventTracker provider
  3114. * function EventTrackerProvider() {
  3115. * var trackingUrl = '/track';
  3116. *
  3117. * // A provider method for configuring where the tracked events should been saved
  3118. * this.setTrackingUrl = function(url) {
  3119. * trackingUrl = url;
  3120. * };
  3121. *
  3122. * // The service factory function
  3123. * this.$get = ['$http', function($http) {
  3124. * var trackedEvents = {};
  3125. * return {
  3126. * // Call this to track an event
  3127. * event: function(event) {
  3128. * var count = trackedEvents[event] || 0;
  3129. * count += 1;
  3130. * trackedEvents[event] = count;
  3131. * return count;
  3132. * },
  3133. * // Call this to save the tracked events to the trackingUrl
  3134. * save: function() {
  3135. * $http.post(trackingUrl, trackedEvents);
  3136. * }
  3137. * };
  3138. * }];
  3139. * }
  3140. *
  3141. * describe('eventTracker', function() {
  3142. * var postSpy;
  3143. *
  3144. * beforeEach(module(function($provide) {
  3145. * // Register the eventTracker provider
  3146. * $provide.provider('eventTracker', EventTrackerProvider);
  3147. * }));
  3148. *
  3149. * beforeEach(module(function(eventTrackerProvider) {
  3150. * // Configure eventTracker provider
  3151. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3152. * }));
  3153. *
  3154. * it('tracks events', inject(function(eventTracker) {
  3155. * expect(eventTracker.event('login')).toEqual(1);
  3156. * expect(eventTracker.event('login')).toEqual(2);
  3157. * }));
  3158. *
  3159. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3160. * postSpy = spyOn($http, 'post');
  3161. * eventTracker.event('login');
  3162. * eventTracker.save();
  3163. * expect(postSpy).toHaveBeenCalled();
  3164. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3165. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3166. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3167. * }));
  3168. * });
  3169. * ```
  3170. */
  3171. /**
  3172. * @ngdoc method
  3173. * @name $provide#factory
  3174. * @description
  3175. *
  3176. * Register a **service factory**, which will be called to return the service instance.
  3177. * This is short for registering a service where its provider consists of only a `$get` property,
  3178. * which is the given service factory function.
  3179. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3180. * configure your service in a provider.
  3181. *
  3182. * @param {string} name The name of the instance.
  3183. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3184. * for `$provide.provider(name, {$get: $getFn})`.
  3185. * @returns {Object} registered provider instance
  3186. *
  3187. * @example
  3188. * Here is an example of registering a service
  3189. * ```js
  3190. * $provide.factory('ping', ['$http', function($http) {
  3191. * return function ping() {
  3192. * return $http.send('/ping');
  3193. * };
  3194. * }]);
  3195. * ```
  3196. * You would then inject and use this service like this:
  3197. * ```js
  3198. * someModule.controller('Ctrl', ['ping', function(ping) {
  3199. * ping();
  3200. * }]);
  3201. * ```
  3202. */
  3203. /**
  3204. * @ngdoc method
  3205. * @name $provide#service
  3206. * @description
  3207. *
  3208. * Register a **service constructor**, which will be invoked with `new` to create the service
  3209. * instance.
  3210. * This is short for registering a service where its provider's `$get` property is the service
  3211. * constructor function that will be used to instantiate the service instance.
  3212. *
  3213. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3214. * as a type/class.
  3215. *
  3216. * @param {string} name The name of the instance.
  3217. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3218. * @returns {Object} registered provider instance
  3219. *
  3220. * @example
  3221. * Here is an example of registering a service using
  3222. * {@link auto.$provide#service $provide.service(class)}.
  3223. * ```js
  3224. * var Ping = function($http) {
  3225. * this.$http = $http;
  3226. * };
  3227. *
  3228. * Ping.$inject = ['$http'];
  3229. *
  3230. * Ping.prototype.send = function() {
  3231. * return this.$http.get('/ping');
  3232. * };
  3233. * $provide.service('ping', Ping);
  3234. * ```
  3235. * You would then inject and use this service like this:
  3236. * ```js
  3237. * someModule.controller('Ctrl', ['ping', function(ping) {
  3238. * ping.send();
  3239. * }]);
  3240. * ```
  3241. */
  3242. /**
  3243. * @ngdoc method
  3244. * @name $provide#value
  3245. * @description
  3246. *
  3247. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3248. * number, an array, an object or a function. This is short for registering a service where its
  3249. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3250. * service**.
  3251. *
  3252. * Value services are similar to constant services, except that they cannot be injected into a
  3253. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3254. * an Angular
  3255. * {@link auto.$provide#decorator decorator}.
  3256. *
  3257. * @param {string} name The name of the instance.
  3258. * @param {*} value The value.
  3259. * @returns {Object} registered provider instance
  3260. *
  3261. * @example
  3262. * Here are some examples of creating value services.
  3263. * ```js
  3264. * $provide.value('ADMIN_USER', 'admin');
  3265. *
  3266. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3267. *
  3268. * $provide.value('halfOf', function(value) {
  3269. * return value / 2;
  3270. * });
  3271. * ```
  3272. */
  3273. /**
  3274. * @ngdoc method
  3275. * @name $provide#constant
  3276. * @description
  3277. *
  3278. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3279. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3280. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3281. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3282. *
  3283. * @param {string} name The name of the constant.
  3284. * @param {*} value The constant value.
  3285. * @returns {Object} registered instance
  3286. *
  3287. * @example
  3288. * Here a some examples of creating constants:
  3289. * ```js
  3290. * $provide.constant('SHARD_HEIGHT', 306);
  3291. *
  3292. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3293. *
  3294. * $provide.constant('double', function(value) {
  3295. * return value * 2;
  3296. * });
  3297. * ```
  3298. */
  3299. /**
  3300. * @ngdoc method
  3301. * @name $provide#decorator
  3302. * @description
  3303. *
  3304. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3305. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3306. * service. The object returned by the decorator may be the original service, or a new service
  3307. * object which replaces or wraps and delegates to the original service.
  3308. *
  3309. * @param {string} name The name of the service to decorate.
  3310. * @param {function()} decorator This function will be invoked when the service needs to be
  3311. * instantiated and should return the decorated service instance. The function is called using
  3312. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3313. * Local injection arguments:
  3314. *
  3315. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3316. * decorated or delegated to.
  3317. *
  3318. * @example
  3319. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3320. * calls to {@link ng.$log#error $log.warn()}.
  3321. * ```js
  3322. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3323. * $delegate.warn = $delegate.error;
  3324. * return $delegate;
  3325. * }]);
  3326. * ```
  3327. */
  3328. function createInjector(modulesToLoad) {
  3329. var INSTANTIATING = {},
  3330. providerSuffix = 'Provider',
  3331. path = [],
  3332. loadedModules = new HashMap(),
  3333. providerCache = {
  3334. $provide: {
  3335. provider: supportObject(provider),
  3336. factory: supportObject(factory),
  3337. service: supportObject(service),
  3338. value: supportObject(value),
  3339. constant: supportObject(constant),
  3340. decorator: decorator
  3341. }
  3342. },
  3343. providerInjector = (providerCache.$injector =
  3344. createInternalInjector(providerCache, function() {
  3345. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3346. })),
  3347. instanceCache = {},
  3348. instanceInjector = (instanceCache.$injector =
  3349. createInternalInjector(instanceCache, function(servicename) {
  3350. var provider = providerInjector.get(servicename + providerSuffix);
  3351. return instanceInjector.invoke(provider.$get, provider);
  3352. }));
  3353. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3354. return instanceInjector;
  3355. ////////////////////////////////////
  3356. // $provider
  3357. ////////////////////////////////////
  3358. function supportObject(delegate) {
  3359. return function(key, value) {
  3360. if (isObject(key)) {
  3361. forEach(key, reverseParams(delegate));
  3362. } else {
  3363. return delegate(key, value);
  3364. }
  3365. };
  3366. }
  3367. function provider(name, provider_) {
  3368. assertNotHasOwnProperty(name, 'service');
  3369. if (isFunction(provider_) || isArray(provider_)) {
  3370. provider_ = providerInjector.instantiate(provider_);
  3371. }
  3372. if (!provider_.$get) {
  3373. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3374. }
  3375. return providerCache[name + providerSuffix] = provider_;
  3376. }
  3377. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3378. function service(name, constructor) {
  3379. return factory(name, ['$injector', function($injector) {
  3380. return $injector.instantiate(constructor);
  3381. }]);
  3382. }
  3383. function value(name, val) { return factory(name, valueFn(val)); }
  3384. function constant(name, value) {
  3385. assertNotHasOwnProperty(name, 'constant');
  3386. providerCache[name] = value;
  3387. instanceCache[name] = value;
  3388. }
  3389. function decorator(serviceName, decorFn) {
  3390. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3391. orig$get = origProvider.$get;
  3392. origProvider.$get = function() {
  3393. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3394. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3395. };
  3396. }
  3397. ////////////////////////////////////
  3398. // Module Loading
  3399. ////////////////////////////////////
  3400. function loadModules(modulesToLoad){
  3401. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3402. forEach(modulesToLoad, function(module) {
  3403. if (loadedModules.get(module)) return;
  3404. loadedModules.put(module, true);
  3405. try {
  3406. if (isString(module)) {
  3407. moduleFn = angularModule(module);
  3408. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3409. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3410. var invokeArgs = invokeQueue[i],
  3411. provider = providerInjector.get(invokeArgs[0]);
  3412. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3413. }
  3414. } else if (isFunction(module)) {
  3415. runBlocks.push(providerInjector.invoke(module));
  3416. } else if (isArray(module)) {
  3417. runBlocks.push(providerInjector.invoke(module));
  3418. } else {
  3419. assertArgFn(module, 'module');
  3420. }
  3421. } catch (e) {
  3422. if (isArray(module)) {
  3423. module = module[module.length - 1];
  3424. }
  3425. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3426. // Safari & FF's stack traces don't contain error.message content
  3427. // unlike those of Chrome and IE
  3428. // So if stack doesn't contain message, we create a new string that contains both.
  3429. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3430. /* jshint -W022 */
  3431. e = e.message + '\n' + e.stack;
  3432. }
  3433. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3434. module, e.stack || e.message || e);
  3435. }
  3436. });
  3437. return runBlocks;
  3438. }
  3439. ////////////////////////////////////
  3440. // internal Injector
  3441. ////////////////////////////////////
  3442. function createInternalInjector(cache, factory) {
  3443. function getService(serviceName) {
  3444. if (cache.hasOwnProperty(serviceName)) {
  3445. if (cache[serviceName] === INSTANTIATING) {
  3446. throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
  3447. }
  3448. return cache[serviceName];
  3449. } else {
  3450. try {
  3451. path.unshift(serviceName);
  3452. cache[serviceName] = INSTANTIATING;
  3453. return cache[serviceName] = factory(serviceName);
  3454. } catch (err) {
  3455. if (cache[serviceName] === INSTANTIATING) {
  3456. delete cache[serviceName];
  3457. }
  3458. throw err;
  3459. } finally {
  3460. path.shift();
  3461. }
  3462. }
  3463. }
  3464. function invoke(fn, self, locals){
  3465. var args = [],
  3466. $inject = annotate(fn),
  3467. length, i,
  3468. key;
  3469. for(i = 0, length = $inject.length; i < length; i++) {
  3470. key = $inject[i];
  3471. if (typeof key !== 'string') {
  3472. throw $injectorMinErr('itkn',
  3473. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3474. }
  3475. args.push(
  3476. locals && locals.hasOwnProperty(key)
  3477. ? locals[key]
  3478. : getService(key)
  3479. );
  3480. }
  3481. if (!fn.$inject) {
  3482. // this means that we must be an array.
  3483. fn = fn[length];
  3484. }
  3485. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3486. // #5388
  3487. return fn.apply(self, args);
  3488. }
  3489. function instantiate(Type, locals) {
  3490. var Constructor = function() {},
  3491. instance, returnedValue;
  3492. // Check if Type is annotated and use just the given function at n-1 as parameter
  3493. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3494. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3495. instance = new Constructor();
  3496. returnedValue = invoke(Type, instance, locals);
  3497. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3498. }
  3499. return {
  3500. invoke: invoke,
  3501. instantiate: instantiate,
  3502. get: getService,
  3503. annotate: annotate,
  3504. has: function(name) {
  3505. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3506. }
  3507. };
  3508. }
  3509. }
  3510. /**
  3511. * @ngdoc service
  3512. * @name $anchorScroll
  3513. * @kind function
  3514. * @requires $window
  3515. * @requires $location
  3516. * @requires $rootScope
  3517. *
  3518. * @description
  3519. * When called, it checks current value of `$location.hash()` and scroll to related element,
  3520. * according to rules specified in
  3521. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3522. *
  3523. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3524. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3525. *
  3526. * @example
  3527. <example>
  3528. <file name="index.html">
  3529. <div id="scrollArea" ng-controller="ScrollCtrl">
  3530. <a ng-click="gotoBottom()">Go to bottom</a>
  3531. <a id="bottom"></a> You're at the bottom!
  3532. </div>
  3533. </file>
  3534. <file name="script.js">
  3535. function ScrollCtrl($scope, $location, $anchorScroll) {
  3536. $scope.gotoBottom = function (){
  3537. // set the location.hash to the id of
  3538. // the element you wish to scroll to.
  3539. $location.hash('bottom');
  3540. // call $anchorScroll()
  3541. $anchorScroll();
  3542. };
  3543. }
  3544. </file>
  3545. <file name="style.css">
  3546. #scrollArea {
  3547. height: 350px;
  3548. overflow: auto;
  3549. }
  3550. #bottom {
  3551. display: block;
  3552. margin-top: 2000px;
  3553. }
  3554. </file>
  3555. </example>
  3556. */
  3557. function $AnchorScrollProvider() {
  3558. var autoScrollingEnabled = true;
  3559. this.disableAutoScrolling = function() {
  3560. autoScrollingEnabled = false;
  3561. };
  3562. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3563. var document = $window.document;
  3564. // helper function to get first anchor from a NodeList
  3565. // can't use filter.filter, as it accepts only instances of Array
  3566. // and IE can't convert NodeList to an array using [].slice
  3567. // TODO(vojta): use filter if we change it to accept lists as well
  3568. function getFirstAnchor(list) {
  3569. var result = null;
  3570. forEach(list, function(element) {
  3571. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3572. });
  3573. return result;
  3574. }
  3575. function scroll() {
  3576. var hash = $location.hash(), elm;
  3577. // empty hash, scroll to the top of the page
  3578. if (!hash) $window.scrollTo(0, 0);
  3579. // element with given id
  3580. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3581. // first anchor with given name :-D
  3582. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3583. // no element and hash == 'top', scroll to the top of the page
  3584. else if (hash === 'top') $window.scrollTo(0, 0);
  3585. }
  3586. // does not scroll when user clicks on anchor link that is currently on
  3587. // (no url change, no $location.hash() change), browser native does scroll
  3588. if (autoScrollingEnabled) {
  3589. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3590. function autoScrollWatchAction() {
  3591. $rootScope.$evalAsync(scroll);
  3592. });
  3593. }
  3594. return scroll;
  3595. }];
  3596. }
  3597. var $animateMinErr = minErr('$animate');
  3598. /**
  3599. * @ngdoc provider
  3600. * @name $animateProvider
  3601. *
  3602. * @description
  3603. * Default implementation of $animate that doesn't perform any animations, instead just
  3604. * synchronously performs DOM
  3605. * updates and calls done() callbacks.
  3606. *
  3607. * In order to enable animations the ngAnimate module has to be loaded.
  3608. *
  3609. * To see the functional implementation check out src/ngAnimate/animate.js
  3610. */
  3611. var $AnimateProvider = ['$provide', function($provide) {
  3612. this.$$selectors = {};
  3613. /**
  3614. * @ngdoc method
  3615. * @name $animateProvider#register
  3616. *
  3617. * @description
  3618. * Registers a new injectable animation factory function. The factory function produces the
  3619. * animation object which contains callback functions for each event that is expected to be
  3620. * animated.
  3621. *
  3622. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3623. * must be called once the element animation is complete. If a function is returned then the
  3624. * animation service will use this function to cancel the animation whenever a cancel event is
  3625. * triggered.
  3626. *
  3627. *
  3628. * ```js
  3629. * return {
  3630. * eventFn : function(element, done) {
  3631. * //code to run the animation
  3632. * //once complete, then run done()
  3633. * return function cancellationFunction() {
  3634. * //code to cancel the animation
  3635. * }
  3636. * }
  3637. * }
  3638. * ```
  3639. *
  3640. * @param {string} name The name of the animation.
  3641. * @param {Function} factory The factory function that will be executed to return the animation
  3642. * object.
  3643. */
  3644. this.register = function(name, factory) {
  3645. var key = name + '-animation';
  3646. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3647. "Expecting class selector starting with '.' got '{0}'.", name);
  3648. this.$$selectors[name.substr(1)] = key;
  3649. $provide.factory(key, factory);
  3650. };
  3651. /**
  3652. * @ngdoc method
  3653. * @name $animateProvider#classNameFilter
  3654. *
  3655. * @description
  3656. * Sets and/or returns the CSS class regular expression that is checked when performing
  3657. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3658. * therefore enable $animate to attempt to perform an animation on any element.
  3659. * When setting the classNameFilter value, animations will only be performed on elements
  3660. * that successfully match the filter expression. This in turn can boost performance
  3661. * for low-powered devices as well as applications containing a lot of structural operations.
  3662. * @param {RegExp=} expression The className expression which will be checked against all animations
  3663. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3664. */
  3665. this.classNameFilter = function(expression) {
  3666. if(arguments.length === 1) {
  3667. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3668. }
  3669. return this.$$classNameFilter;
  3670. };
  3671. this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
  3672. function async(fn) {
  3673. fn && $$asyncCallback(fn);
  3674. }
  3675. /**
  3676. *
  3677. * @ngdoc service
  3678. * @name $animate
  3679. * @description The $animate service provides rudimentary DOM manipulation functions to
  3680. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3681. * This service is the core service used by the ngAnimate $animator service which provides
  3682. * high-level animation hooks for CSS and JavaScript.
  3683. *
  3684. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3685. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3686. * manipulation operations.
  3687. *
  3688. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3689. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3690. * page}.
  3691. */
  3692. return {
  3693. /**
  3694. *
  3695. * @ngdoc method
  3696. * @name $animate#enter
  3697. * @function
  3698. * @description Inserts the element into the DOM either after the `after` element or within
  3699. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3700. * @param {DOMElement} element the element which will be inserted into the DOM
  3701. * @param {DOMElement} parent the parent element which will append the element as
  3702. * a child (if the after element is not present)
  3703. * @param {DOMElement} after the sibling element which will append the element
  3704. * after itself
  3705. * @param {Function=} done callback function that will be called after the element has been
  3706. * inserted into the DOM
  3707. */
  3708. enter : function(element, parent, after, done) {
  3709. if (after) {
  3710. after.after(element);
  3711. } else {
  3712. if (!parent || !parent[0]) {
  3713. parent = after.parent();
  3714. }
  3715. parent.append(element);
  3716. }
  3717. async(done);
  3718. },
  3719. /**
  3720. *
  3721. * @ngdoc method
  3722. * @name $animate#leave
  3723. * @function
  3724. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3725. * fired (if provided).
  3726. * @param {DOMElement} element the element which will be removed from the DOM
  3727. * @param {Function=} done callback function that will be called after the element has been
  3728. * removed from the DOM
  3729. */
  3730. leave : function(element, done) {
  3731. element.remove();
  3732. async(done);
  3733. },
  3734. /**
  3735. *
  3736. * @ngdoc method
  3737. * @name $animate#move
  3738. * @function
  3739. * @description Moves the position of the provided element within the DOM to be placed
  3740. * either after the `after` element or inside of the `parent` element. Once complete, the
  3741. * done() callback will be fired (if provided).
  3742. *
  3743. * @param {DOMElement} element the element which will be moved around within the
  3744. * DOM
  3745. * @param {DOMElement} parent the parent element where the element will be
  3746. * inserted into (if the after element is not present)
  3747. * @param {DOMElement} after the sibling element where the element will be
  3748. * positioned next to
  3749. * @param {Function=} done the callback function (if provided) that will be fired after the
  3750. * element has been moved to its new position
  3751. */
  3752. move : function(element, parent, after, done) {
  3753. // Do not remove element before insert. Removing will cause data associated with the
  3754. // element to be dropped. Insert will implicitly do the remove.
  3755. this.enter(element, parent, after, done);
  3756. },
  3757. /**
  3758. *
  3759. * @ngdoc method
  3760. * @name $animate#addClass
  3761. * @function
  3762. * @description Adds the provided className CSS class value to the provided element. Once
  3763. * complete, the done() callback will be fired (if provided).
  3764. * @param {DOMElement} element the element which will have the className value
  3765. * added to it
  3766. * @param {string} className the CSS class which will be added to the element
  3767. * @param {Function=} done the callback function (if provided) that will be fired after the
  3768. * className value has been added to the element
  3769. */
  3770. addClass : function(element, className, done) {
  3771. className = isString(className) ?
  3772. className :
  3773. isArray(className) ? className.join(' ') : '';
  3774. forEach(element, function (element) {
  3775. jqLiteAddClass(element, className);
  3776. });
  3777. async(done);
  3778. },
  3779. /**
  3780. *
  3781. * @ngdoc method
  3782. * @name $animate#removeClass
  3783. * @function
  3784. * @description Removes the provided className CSS class value from the provided element.
  3785. * Once complete, the done() callback will be fired (if provided).
  3786. * @param {DOMElement} element the element which will have the className value
  3787. * removed from it
  3788. * @param {string} className the CSS class which will be removed from the element
  3789. * @param {Function=} done the callback function (if provided) that will be fired after the
  3790. * className value has been removed from the element
  3791. */
  3792. removeClass : function(element, className, done) {
  3793. className = isString(className) ?
  3794. className :
  3795. isArray(className) ? className.join(' ') : '';
  3796. forEach(element, function (element) {
  3797. jqLiteRemoveClass(element, className);
  3798. });
  3799. async(done);
  3800. },
  3801. /**
  3802. *
  3803. * @ngdoc method
  3804. * @name $animate#setClass
  3805. * @function
  3806. * @description Adds and/or removes the given CSS classes to and from the element.
  3807. * Once complete, the done() callback will be fired (if provided).
  3808. * @param {DOMElement} element the element which will it's CSS classes changed
  3809. * removed from it
  3810. * @param {string} add the CSS classes which will be added to the element
  3811. * @param {string} remove the CSS class which will be removed from the element
  3812. * @param {Function=} done the callback function (if provided) that will be fired after the
  3813. * CSS classes have been set on the element
  3814. */
  3815. setClass : function(element, add, remove, done) {
  3816. forEach(element, function (element) {
  3817. jqLiteAddClass(element, add);
  3818. jqLiteRemoveClass(element, remove);
  3819. });
  3820. async(done);
  3821. },
  3822. enabled : noop
  3823. };
  3824. }];
  3825. }];
  3826. function $$AsyncCallbackProvider(){
  3827. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  3828. return $$rAF.supported
  3829. ? function(fn) { return $$rAF(fn); }
  3830. : function(fn) {
  3831. return $timeout(fn, 0, false);
  3832. };
  3833. }];
  3834. }
  3835. /**
  3836. * ! This is a private undocumented service !
  3837. *
  3838. * @name $browser
  3839. * @requires $log
  3840. * @description
  3841. * This object has two goals:
  3842. *
  3843. * - hide all the global state in the browser caused by the window object
  3844. * - abstract away all the browser specific features and inconsistencies
  3845. *
  3846. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3847. * service, which can be used for convenient testing of the application without the interaction with
  3848. * the real browser apis.
  3849. */
  3850. /**
  3851. * @param {object} window The global window object.
  3852. * @param {object} document jQuery wrapped document.
  3853. * @param {function()} XHR XMLHttpRequest constructor.
  3854. * @param {object} $log console.log or an object with the same interface.
  3855. * @param {object} $sniffer $sniffer service
  3856. */
  3857. function Browser(window, document, $log, $sniffer) {
  3858. var self = this,
  3859. rawDocument = document[0],
  3860. location = window.location,
  3861. history = window.history,
  3862. setTimeout = window.setTimeout,
  3863. clearTimeout = window.clearTimeout,
  3864. pendingDeferIds = {};
  3865. self.isMock = false;
  3866. var outstandingRequestCount = 0;
  3867. var outstandingRequestCallbacks = [];
  3868. // TODO(vojta): remove this temporary api
  3869. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3870. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3871. /**
  3872. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3873. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3874. */
  3875. function completeOutstandingRequest(fn) {
  3876. try {
  3877. fn.apply(null, sliceArgs(arguments, 1));
  3878. } finally {
  3879. outstandingRequestCount--;
  3880. if (outstandingRequestCount === 0) {
  3881. while(outstandingRequestCallbacks.length) {
  3882. try {
  3883. outstandingRequestCallbacks.pop()();
  3884. } catch (e) {
  3885. $log.error(e);
  3886. }
  3887. }
  3888. }
  3889. }
  3890. }
  3891. /**
  3892. * @private
  3893. * Note: this method is used only by scenario runner
  3894. * TODO(vojta): prefix this method with $$ ?
  3895. * @param {function()} callback Function that will be called when no outstanding request
  3896. */
  3897. self.notifyWhenNoOutstandingRequests = function(callback) {
  3898. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3899. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3900. // regular poller would result in flaky tests.
  3901. forEach(pollFns, function(pollFn){ pollFn(); });
  3902. if (outstandingRequestCount === 0) {
  3903. callback();
  3904. } else {
  3905. outstandingRequestCallbacks.push(callback);
  3906. }
  3907. };
  3908. //////////////////////////////////////////////////////////////
  3909. // Poll Watcher API
  3910. //////////////////////////////////////////////////////////////
  3911. var pollFns = [],
  3912. pollTimeout;
  3913. /**
  3914. * @name $browser#addPollFn
  3915. *
  3916. * @param {function()} fn Poll function to add
  3917. *
  3918. * @description
  3919. * Adds a function to the list of functions that poller periodically executes,
  3920. * and starts polling if not started yet.
  3921. *
  3922. * @returns {function()} the added function
  3923. */
  3924. self.addPollFn = function(fn) {
  3925. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  3926. pollFns.push(fn);
  3927. return fn;
  3928. };
  3929. /**
  3930. * @param {number} interval How often should browser call poll functions (ms)
  3931. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  3932. *
  3933. * @description
  3934. * Configures the poller to run in the specified intervals, using the specified
  3935. * setTimeout fn and kicks it off.
  3936. */
  3937. function startPoller(interval, setTimeout) {
  3938. (function check() {
  3939. forEach(pollFns, function(pollFn){ pollFn(); });
  3940. pollTimeout = setTimeout(check, interval);
  3941. })();
  3942. }
  3943. //////////////////////////////////////////////////////////////
  3944. // URL API
  3945. //////////////////////////////////////////////////////////////
  3946. var lastBrowserUrl = location.href,
  3947. baseElement = document.find('base'),
  3948. newLocation = null;
  3949. /**
  3950. * @name $browser#url
  3951. *
  3952. * @description
  3953. * GETTER:
  3954. * Without any argument, this method just returns current value of location.href.
  3955. *
  3956. * SETTER:
  3957. * With at least one argument, this method sets url to new value.
  3958. * If html5 history api supported, pushState/replaceState is used, otherwise
  3959. * location.href/location.replace is used.
  3960. * Returns its own instance to allow chaining
  3961. *
  3962. * NOTE: this api is intended for use only by the $location service. Please use the
  3963. * {@link ng.$location $location service} to change url.
  3964. *
  3965. * @param {string} url New url (when used as setter)
  3966. * @param {boolean=} replace Should new url replace current history record ?
  3967. */
  3968. self.url = function(url, replace) {
  3969. // Android Browser BFCache causes location, history reference to become stale.
  3970. if (location !== window.location) location = window.location;
  3971. if (history !== window.history) history = window.history;
  3972. // setter
  3973. if (url) {
  3974. if (lastBrowserUrl == url) return;
  3975. lastBrowserUrl = url;
  3976. if ($sniffer.history) {
  3977. if (replace) history.replaceState(null, '', url);
  3978. else {
  3979. history.pushState(null, '', url);
  3980. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  3981. baseElement.attr('href', baseElement.attr('href'));
  3982. }
  3983. } else {
  3984. newLocation = url;
  3985. if (replace) {
  3986. location.replace(url);
  3987. } else {
  3988. location.href = url;
  3989. }
  3990. }
  3991. return self;
  3992. // getter
  3993. } else {
  3994. // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
  3995. // methods not updating location.href synchronously.
  3996. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  3997. return newLocation || location.href.replace(/%27/g,"'");
  3998. }
  3999. };
  4000. var urlChangeListeners = [],
  4001. urlChangeInit = false;
  4002. function fireUrlChange() {
  4003. newLocation = null;
  4004. if (lastBrowserUrl == self.url()) return;
  4005. lastBrowserUrl = self.url();
  4006. forEach(urlChangeListeners, function(listener) {
  4007. listener(self.url());
  4008. });
  4009. }
  4010. /**
  4011. * @name $browser#onUrlChange
  4012. *
  4013. * @description
  4014. * Register callback function that will be called, when url changes.
  4015. *
  4016. * It's only called when the url is changed from outside of angular:
  4017. * - user types different url into address bar
  4018. * - user clicks on history (forward/back) button
  4019. * - user clicks on a link
  4020. *
  4021. * It's not called when url is changed by $browser.url() method
  4022. *
  4023. * The listener gets called with new url as parameter.
  4024. *
  4025. * NOTE: this api is intended for use only by the $location service. Please use the
  4026. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4027. *
  4028. * @param {function(string)} listener Listener function to be called when url changes.
  4029. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4030. */
  4031. self.onUrlChange = function(callback) {
  4032. // TODO(vojta): refactor to use node's syntax for events
  4033. if (!urlChangeInit) {
  4034. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4035. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4036. // changed by push/replaceState
  4037. // html5 history api - popstate event
  4038. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  4039. // hashchange event
  4040. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  4041. // polling
  4042. else self.addPollFn(fireUrlChange);
  4043. urlChangeInit = true;
  4044. }
  4045. urlChangeListeners.push(callback);
  4046. return callback;
  4047. };
  4048. //////////////////////////////////////////////////////////////
  4049. // Misc API
  4050. //////////////////////////////////////////////////////////////
  4051. /**
  4052. * @name $browser#baseHref
  4053. *
  4054. * @description
  4055. * Returns current <base href>
  4056. * (always relative - without domain)
  4057. *
  4058. * @returns {string} The current base href
  4059. */
  4060. self.baseHref = function() {
  4061. var href = baseElement.attr('href');
  4062. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4063. };
  4064. //////////////////////////////////////////////////////////////
  4065. // Cookies API
  4066. //////////////////////////////////////////////////////////////
  4067. var lastCookies = {};
  4068. var lastCookieString = '';
  4069. var cookiePath = self.baseHref();
  4070. /**
  4071. * @name $browser#cookies
  4072. *
  4073. * @param {string=} name Cookie name
  4074. * @param {string=} value Cookie value
  4075. *
  4076. * @description
  4077. * The cookies method provides a 'private' low level access to browser cookies.
  4078. * It is not meant to be used directly, use the $cookie service instead.
  4079. *
  4080. * The return values vary depending on the arguments that the method was called with as follows:
  4081. *
  4082. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4083. * it
  4084. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4085. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4086. * way)
  4087. *
  4088. * @returns {Object} Hash of all cookies (if called without any parameter)
  4089. */
  4090. self.cookies = function(name, value) {
  4091. /* global escape: false, unescape: false */
  4092. var cookieLength, cookieArray, cookie, i, index;
  4093. if (name) {
  4094. if (value === undefined) {
  4095. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  4096. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4097. } else {
  4098. if (isString(value)) {
  4099. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  4100. ';path=' + cookiePath).length + 1;
  4101. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4102. // - 300 cookies
  4103. // - 20 cookies per unique domain
  4104. // - 4096 bytes per cookie
  4105. if (cookieLength > 4096) {
  4106. $log.warn("Cookie '"+ name +
  4107. "' possibly not set or overflowed because it was too large ("+
  4108. cookieLength + " > 4096 bytes)!");
  4109. }
  4110. }
  4111. }
  4112. } else {
  4113. if (rawDocument.cookie !== lastCookieString) {
  4114. lastCookieString = rawDocument.cookie;
  4115. cookieArray = lastCookieString.split("; ");
  4116. lastCookies = {};
  4117. for (i = 0; i < cookieArray.length; i++) {
  4118. cookie = cookieArray[i];
  4119. index = cookie.indexOf('=');
  4120. if (index > 0) { //ignore nameless cookies
  4121. name = unescape(cookie.substring(0, index));
  4122. // the first value that is seen for a cookie is the most
  4123. // specific one. values for the same cookie name that
  4124. // follow are for less specific paths.
  4125. if (lastCookies[name] === undefined) {
  4126. lastCookies[name] = unescape(cookie.substring(index + 1));
  4127. }
  4128. }
  4129. }
  4130. }
  4131. return lastCookies;
  4132. }
  4133. };
  4134. /**
  4135. * @name $browser#defer
  4136. * @param {function()} fn A function, who's execution should be deferred.
  4137. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4138. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4139. *
  4140. * @description
  4141. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4142. *
  4143. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4144. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4145. * via `$browser.defer.flush()`.
  4146. *
  4147. */
  4148. self.defer = function(fn, delay) {
  4149. var timeoutId;
  4150. outstandingRequestCount++;
  4151. timeoutId = setTimeout(function() {
  4152. delete pendingDeferIds[timeoutId];
  4153. completeOutstandingRequest(fn);
  4154. }, delay || 0);
  4155. pendingDeferIds[timeoutId] = true;
  4156. return timeoutId;
  4157. };
  4158. /**
  4159. * @name $browser#defer.cancel
  4160. *
  4161. * @description
  4162. * Cancels a deferred task identified with `deferId`.
  4163. *
  4164. * @param {*} deferId Token returned by the `$browser.defer` function.
  4165. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4166. * canceled.
  4167. */
  4168. self.defer.cancel = function(deferId) {
  4169. if (pendingDeferIds[deferId]) {
  4170. delete pendingDeferIds[deferId];
  4171. clearTimeout(deferId);
  4172. completeOutstandingRequest(noop);
  4173. return true;
  4174. }
  4175. return false;
  4176. };
  4177. }
  4178. function $BrowserProvider(){
  4179. this.$get = ['$window', '$log', '$sniffer', '$document',
  4180. function( $window, $log, $sniffer, $document){
  4181. return new Browser($window, $document, $log, $sniffer);
  4182. }];
  4183. }
  4184. /**
  4185. * @ngdoc service
  4186. * @name $cacheFactory
  4187. *
  4188. * @description
  4189. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4190. * them.
  4191. *
  4192. * ```js
  4193. *
  4194. * var cache = $cacheFactory('cacheId');
  4195. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4196. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4197. *
  4198. * cache.put("key", "value");
  4199. * cache.put("another key", "another value");
  4200. *
  4201. * // We've specified no options on creation
  4202. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4203. *
  4204. * ```
  4205. *
  4206. *
  4207. * @param {string} cacheId Name or id of the newly created cache.
  4208. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4209. *
  4210. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4211. *
  4212. * @returns {object} Newly created cache object with the following set of methods:
  4213. *
  4214. * - `{object}` `info()` — Returns id, size, and options of cache.
  4215. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4216. * it.
  4217. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4218. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4219. * - `{void}` `removeAll()` — Removes all cached values.
  4220. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4221. *
  4222. * @example
  4223. <example module="cacheExampleApp">
  4224. <file name="index.html">
  4225. <div ng-controller="CacheController">
  4226. <input ng-model="newCacheKey" placeholder="Key">
  4227. <input ng-model="newCacheValue" placeholder="Value">
  4228. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4229. <p ng-if="keys.length">Cached Values</p>
  4230. <div ng-repeat="key in keys">
  4231. <span ng-bind="key"></span>
  4232. <span>: </span>
  4233. <b ng-bind="cache.get(key)"></b>
  4234. </div>
  4235. <p>Cache Info</p>
  4236. <div ng-repeat="(key, value) in cache.info()">
  4237. <span ng-bind="key"></span>
  4238. <span>: </span>
  4239. <b ng-bind="value"></b>
  4240. </div>
  4241. </div>
  4242. </file>
  4243. <file name="script.js">
  4244. angular.module('cacheExampleApp', []).
  4245. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4246. $scope.keys = [];
  4247. $scope.cache = $cacheFactory('cacheId');
  4248. $scope.put = function(key, value) {
  4249. $scope.cache.put(key, value);
  4250. $scope.keys.push(key);
  4251. };
  4252. }]);
  4253. </file>
  4254. <file name="style.css">
  4255. p {
  4256. margin: 10px 0 3px;
  4257. }
  4258. </file>
  4259. </example>
  4260. */
  4261. function $CacheFactoryProvider() {
  4262. this.$get = function() {
  4263. var caches = {};
  4264. function cacheFactory(cacheId, options) {
  4265. if (cacheId in caches) {
  4266. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4267. }
  4268. var size = 0,
  4269. stats = extend({}, options, {id: cacheId}),
  4270. data = {},
  4271. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4272. lruHash = {},
  4273. freshEnd = null,
  4274. staleEnd = null;
  4275. /**
  4276. * @ngdoc type
  4277. * @name $cacheFactory.Cache
  4278. *
  4279. * @description
  4280. * A cache object used to store and retrieve data, primarily used by
  4281. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4282. * templates and other data.
  4283. *
  4284. * ```js
  4285. * angular.module('superCache')
  4286. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4287. * return $cacheFactory('super-cache');
  4288. * }]);
  4289. * ```
  4290. *
  4291. * Example test:
  4292. *
  4293. * ```js
  4294. * it('should behave like a cache', inject(function(superCache) {
  4295. * superCache.put('key', 'value');
  4296. * superCache.put('another key', 'another value');
  4297. *
  4298. * expect(superCache.info()).toEqual({
  4299. * id: 'super-cache',
  4300. * size: 2
  4301. * });
  4302. *
  4303. * superCache.remove('another key');
  4304. * expect(superCache.get('another key')).toBeUndefined();
  4305. *
  4306. * superCache.removeAll();
  4307. * expect(superCache.info()).toEqual({
  4308. * id: 'super-cache',
  4309. * size: 0
  4310. * });
  4311. * }));
  4312. * ```
  4313. */
  4314. return caches[cacheId] = {
  4315. /**
  4316. * @ngdoc method
  4317. * @name $cacheFactory.Cache#put
  4318. * @function
  4319. *
  4320. * @description
  4321. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4322. * retrieved later, and incrementing the size of the cache if the key was not already
  4323. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4324. * entries from the set.
  4325. *
  4326. * It will not insert undefined values into the cache.
  4327. *
  4328. * @param {string} key the key under which the cached data is stored.
  4329. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4330. * will not be stored.
  4331. * @returns {*} the value stored.
  4332. */
  4333. put: function(key, value) {
  4334. if (capacity < Number.MAX_VALUE) {
  4335. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4336. refresh(lruEntry);
  4337. }
  4338. if (isUndefined(value)) return;
  4339. if (!(key in data)) size++;
  4340. data[key] = value;
  4341. if (size > capacity) {
  4342. this.remove(staleEnd.key);
  4343. }
  4344. return value;
  4345. },
  4346. /**
  4347. * @ngdoc method
  4348. * @name $cacheFactory.Cache#get
  4349. * @function
  4350. *
  4351. * @description
  4352. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4353. *
  4354. * @param {string} key the key of the data to be retrieved
  4355. * @returns {*} the value stored.
  4356. */
  4357. get: function(key) {
  4358. if (capacity < Number.MAX_VALUE) {
  4359. var lruEntry = lruHash[key];
  4360. if (!lruEntry) return;
  4361. refresh(lruEntry);
  4362. }
  4363. return data[key];
  4364. },
  4365. /**
  4366. * @ngdoc method
  4367. * @name $cacheFactory.Cache#remove
  4368. * @function
  4369. *
  4370. * @description
  4371. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4372. *
  4373. * @param {string} key the key of the entry to be removed
  4374. */
  4375. remove: function(key) {
  4376. if (capacity < Number.MAX_VALUE) {
  4377. var lruEntry = lruHash[key];
  4378. if (!lruEntry) return;
  4379. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4380. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4381. link(lruEntry.n,lruEntry.p);
  4382. delete lruHash[key];
  4383. }
  4384. delete data[key];
  4385. size--;
  4386. },
  4387. /**
  4388. * @ngdoc method
  4389. * @name $cacheFactory.Cache#removeAll
  4390. * @function
  4391. *
  4392. * @description
  4393. * Clears the cache object of any entries.
  4394. */
  4395. removeAll: function() {
  4396. data = {};
  4397. size = 0;
  4398. lruHash = {};
  4399. freshEnd = staleEnd = null;
  4400. },
  4401. /**
  4402. * @ngdoc method
  4403. * @name $cacheFactory.Cache#destroy
  4404. * @function
  4405. *
  4406. * @description
  4407. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4408. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4409. */
  4410. destroy: function() {
  4411. data = null;
  4412. stats = null;
  4413. lruHash = null;
  4414. delete caches[cacheId];
  4415. },
  4416. /**
  4417. * @ngdoc method
  4418. * @name $cacheFactory.Cache#info
  4419. * @function
  4420. *
  4421. * @description
  4422. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4423. *
  4424. * @returns {object} an object with the following properties:
  4425. * <ul>
  4426. * <li>**id**: the id of the cache instance</li>
  4427. * <li>**size**: the number of entries kept in the cache instance</li>
  4428. * <li>**...**: any additional properties from the options object when creating the
  4429. * cache.</li>
  4430. * </ul>
  4431. */
  4432. info: function() {
  4433. return extend({}, stats, {size: size});
  4434. }
  4435. };
  4436. /**
  4437. * makes the `entry` the freshEnd of the LRU linked list
  4438. */
  4439. function refresh(entry) {
  4440. if (entry != freshEnd) {
  4441. if (!staleEnd) {
  4442. staleEnd = entry;
  4443. } else if (staleEnd == entry) {
  4444. staleEnd = entry.n;
  4445. }
  4446. link(entry.n, entry.p);
  4447. link(entry, freshEnd);
  4448. freshEnd = entry;
  4449. freshEnd.n = null;
  4450. }
  4451. }
  4452. /**
  4453. * bidirectionally links two entries of the LRU linked list
  4454. */
  4455. function link(nextEntry, prevEntry) {
  4456. if (nextEntry != prevEntry) {
  4457. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4458. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4459. }
  4460. }
  4461. }
  4462. /**
  4463. * @ngdoc method
  4464. * @name $cacheFactory#info
  4465. *
  4466. * @description
  4467. * Get information about all the of the caches that have been created
  4468. *
  4469. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4470. */
  4471. cacheFactory.info = function() {
  4472. var info = {};
  4473. forEach(caches, function(cache, cacheId) {
  4474. info[cacheId] = cache.info();
  4475. });
  4476. return info;
  4477. };
  4478. /**
  4479. * @ngdoc method
  4480. * @name $cacheFactory#get
  4481. *
  4482. * @description
  4483. * Get access to a cache object by the `cacheId` used when it was created.
  4484. *
  4485. * @param {string} cacheId Name or id of a cache to access.
  4486. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4487. */
  4488. cacheFactory.get = function(cacheId) {
  4489. return caches[cacheId];
  4490. };
  4491. return cacheFactory;
  4492. };
  4493. }
  4494. /**
  4495. * @ngdoc service
  4496. * @name $templateCache
  4497. *
  4498. * @description
  4499. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4500. * can load templates directly into the cache in a `script` tag, or by consuming the
  4501. * `$templateCache` service directly.
  4502. *
  4503. * Adding via the `script` tag:
  4504. *
  4505. * ```html
  4506. * <script type="text/ng-template" id="templateId.html">
  4507. * <p>This is the content of the template</p>
  4508. * </script>
  4509. * ```
  4510. *
  4511. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4512. * the document, but it must be below the `ng-app` definition.
  4513. *
  4514. * Adding via the $templateCache service:
  4515. *
  4516. * ```js
  4517. * var myApp = angular.module('myApp', []);
  4518. * myApp.run(function($templateCache) {
  4519. * $templateCache.put('templateId.html', 'This is the content of the template');
  4520. * });
  4521. * ```
  4522. *
  4523. * To retrieve the template later, simply use it in your HTML:
  4524. * ```html
  4525. * <div ng-include=" 'templateId.html' "></div>
  4526. * ```
  4527. *
  4528. * or get it via Javascript:
  4529. * ```js
  4530. * $templateCache.get('templateId.html')
  4531. * ```
  4532. *
  4533. * See {@link ng.$cacheFactory $cacheFactory}.
  4534. *
  4535. */
  4536. function $TemplateCacheProvider() {
  4537. this.$get = ['$cacheFactory', function($cacheFactory) {
  4538. return $cacheFactory('templates');
  4539. }];
  4540. }
  4541. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4542. *
  4543. * DOM-related variables:
  4544. *
  4545. * - "node" - DOM Node
  4546. * - "element" - DOM Element or Node
  4547. * - "$node" or "$element" - jqLite-wrapped node or element
  4548. *
  4549. *
  4550. * Compiler related stuff:
  4551. *
  4552. * - "linkFn" - linking fn of a single directive
  4553. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4554. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4555. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4556. */
  4557. /**
  4558. * @ngdoc service
  4559. * @name $compile
  4560. * @function
  4561. *
  4562. * @description
  4563. * Compiles an HTML string or DOM into a template and produces a template function, which
  4564. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4565. *
  4566. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4567. * {@link ng.$compileProvider#directive directives}.
  4568. *
  4569. * <div class="alert alert-warning">
  4570. * **Note:** This document is an in-depth reference of all directive options.
  4571. * For a gentle introduction to directives with examples of common use cases,
  4572. * see the {@link guide/directive directive guide}.
  4573. * </div>
  4574. *
  4575. * ## Comprehensive Directive API
  4576. *
  4577. * There are many different options for a directive.
  4578. *
  4579. * The difference resides in the return value of the factory function.
  4580. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4581. * or just the `postLink` function (all other properties will have the default values).
  4582. *
  4583. * <div class="alert alert-success">
  4584. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4585. * </div>
  4586. *
  4587. * Here's an example directive declared with a Directive Definition Object:
  4588. *
  4589. * ```js
  4590. * var myModule = angular.module(...);
  4591. *
  4592. * myModule.directive('directiveName', function factory(injectables) {
  4593. * var directiveDefinitionObject = {
  4594. * priority: 0,
  4595. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4596. * // or
  4597. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4598. * replace: false,
  4599. * transclude: false,
  4600. * restrict: 'A',
  4601. * scope: false,
  4602. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4603. * controllerAs: 'stringAlias',
  4604. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4605. * compile: function compile(tElement, tAttrs, transclude) {
  4606. * return {
  4607. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4608. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4609. * }
  4610. * // or
  4611. * // return function postLink( ... ) { ... }
  4612. * },
  4613. * // or
  4614. * // link: {
  4615. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4616. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4617. * // }
  4618. * // or
  4619. * // link: function postLink( ... ) { ... }
  4620. * };
  4621. * return directiveDefinitionObject;
  4622. * });
  4623. * ```
  4624. *
  4625. * <div class="alert alert-warning">
  4626. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4627. * </div>
  4628. *
  4629. * Therefore the above can be simplified as:
  4630. *
  4631. * ```js
  4632. * var myModule = angular.module(...);
  4633. *
  4634. * myModule.directive('directiveName', function factory(injectables) {
  4635. * var directiveDefinitionObject = {
  4636. * link: function postLink(scope, iElement, iAttrs) { ... }
  4637. * };
  4638. * return directiveDefinitionObject;
  4639. * // or
  4640. * // return function postLink(scope, iElement, iAttrs) { ... }
  4641. * });
  4642. * ```
  4643. *
  4644. *
  4645. *
  4646. * ### Directive Definition Object
  4647. *
  4648. * The directive definition object provides instructions to the {@link ng.$compile
  4649. * compiler}. The attributes are:
  4650. *
  4651. * #### `priority`
  4652. * When there are multiple directives defined on a single DOM element, sometimes it
  4653. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4654. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4655. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4656. * are also run in priority order, but post-link functions are run in reverse order. The order
  4657. * of directives with the same priority is undefined. The default priority is `0`.
  4658. *
  4659. * #### `terminal`
  4660. * If set to true then the current `priority` will be the last set of directives
  4661. * which will execute (any directives at the current priority will still execute
  4662. * as the order of execution on same `priority` is undefined).
  4663. *
  4664. * #### `scope`
  4665. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4666. * same element request a new scope, only one new scope is created. The new scope rule does not
  4667. * apply for the root of the template since the root of the template always gets a new scope.
  4668. *
  4669. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4670. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4671. * when creating reusable components, which should not accidentally read or modify data in the
  4672. * parent scope.
  4673. *
  4674. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4675. * derived from the parent scope. These local properties are useful for aliasing values for
  4676. * templates. Locals definition is a hash of local scope property to its source:
  4677. *
  4678. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4679. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4680. * attribute name is assumed to be the same as the local name.
  4681. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4682. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4683. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4684. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4685. * component scope).
  4686. *
  4687. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4688. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4689. * name is specified then the attribute name is assumed to be the same as the local name.
  4690. * Given `<widget my-attr="parentModel">` and widget definition of
  4691. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4692. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4693. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4694. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4695. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4696. *
  4697. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4698. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4699. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4700. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4701. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4702. * pass data from the isolated scope via an expression and to the parent scope, this can be
  4703. * done by passing a map of local variable names and values into the expression wrapper fn.
  4704. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4705. * by calling the `localFn` as `localFn({amount: 22})`.
  4706. *
  4707. *
  4708. *
  4709. * #### `controller`
  4710. * Controller constructor function. The controller is instantiated before the
  4711. * pre-linking phase and it is shared with other directives (see
  4712. * `require` attribute). This allows the directives to communicate with each other and augment
  4713. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4714. *
  4715. * * `$scope` - Current scope associated with the element
  4716. * * `$element` - Current element
  4717. * * `$attrs` - Current attributes object for the element
  4718. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4719. * The scope can be overridden by an optional first argument.
  4720. * `function([scope], cloneLinkingFn)`.
  4721. *
  4722. *
  4723. * #### `require`
  4724. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4725. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4726. * injected argument will be an array in corresponding order. If no such directive can be
  4727. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4728. *
  4729. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4730. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4731. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  4732. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  4733. * `link` fn if not found.
  4734. *
  4735. *
  4736. * #### `controllerAs`
  4737. * Controller alias at the directive scope. An alias for the controller so it
  4738. * can be referenced at the directive template. The directive needs to define a scope for this
  4739. * configuration to be used. Useful in the case when directive is used as component.
  4740. *
  4741. *
  4742. * #### `restrict`
  4743. * String of subset of `EACM` which restricts the directive to a specific directive
  4744. * declaration style. If omitted, the default (attributes only) is used.
  4745. *
  4746. * * `E` - Element name: `<my-directive></my-directive>`
  4747. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4748. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4749. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4750. *
  4751. *
  4752. * #### `template`
  4753. * replace the current element with the contents of the HTML. The replacement process
  4754. * migrates all of the attributes / classes from the old element to the new one. See the
  4755. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4756. * Directives Guide} for an example.
  4757. *
  4758. * You can specify `template` as a string representing the template or as a function which takes
  4759. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  4760. * returns a string value representing the template.
  4761. *
  4762. *
  4763. * #### `templateUrl`
  4764. * Same as `template` but the template is loaded from the specified URL. Because
  4765. * the template loading is asynchronous the compilation/linking is suspended until the template
  4766. * is loaded.
  4767. *
  4768. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4769. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4770. * a string value representing the url. In either case, the template URL is passed through {@link
  4771. * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4772. *
  4773. *
  4774. * #### `replace`
  4775. * specify where the template should be inserted. Defaults to `false`.
  4776. *
  4777. * * `true` - the template will replace the current element.
  4778. * * `false` - the template will replace the contents of the current element.
  4779. *
  4780. *
  4781. * #### `transclude`
  4782. * compile the content of the element and make it available to the directive.
  4783. * Typically used with {@link ng.directive:ngTransclude
  4784. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4785. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4786. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4787. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4788. * be bound to the parent (pre-`isolate`) scope.
  4789. *
  4790. * * `true` - transclude the content of the directive.
  4791. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  4792. *
  4793. *
  4794. * #### `compile`
  4795. *
  4796. * ```js
  4797. * function compile(tElement, tAttrs, transclude) { ... }
  4798. * ```
  4799. *
  4800. * The compile function deals with transforming the template DOM. Since most directives do not do
  4801. * template transformation, it is not used often. Examples that require compile functions are
  4802. * directives that transform template DOM, such as {@link
  4803. * api/ng.directive:ngRepeat ngRepeat}, or load the contents
  4804. * asynchronously, such as {@link ngRoute.directive:ngView ngView}. The
  4805. * compile function takes the following arguments.
  4806. *
  4807. * * `tElement` - template element - The element where the directive has been declared. It is
  4808. * safe to do template transformation on the element and child elements only.
  4809. *
  4810. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4811. * between all directive compile functions.
  4812. *
  4813. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4814. *
  4815. * <div class="alert alert-warning">
  4816. * **Note:** The template instance and the link instance may be different objects if the template has
  4817. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4818. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4819. * should be done in a linking function rather than in a compile function.
  4820. * </div>
  4821. * <div class="alert alert-warning">
  4822. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  4823. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  4824. * stack overflow errors.
  4825. *
  4826. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  4827. * a directive's template instead of relying on automatic template compilation via `template` or
  4828. * `templateUrl` declaration or manual compilation inside the compile function.
  4829. * </div>
  4830. *
  4831. * <div class="alert alert-error">
  4832. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4833. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4834. * to the link function instead.
  4835. * </div>
  4836. * A compile function can have a return value which can be either a function or an object.
  4837. *
  4838. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4839. * `link` property of the config object when the compile function is empty.
  4840. *
  4841. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4842. * control when a linking function should be called during the linking phase. See info about
  4843. * pre-linking and post-linking functions below.
  4844. *
  4845. *
  4846. * #### `link`
  4847. * This property is used only if the `compile` property is not defined.
  4848. *
  4849. * ```js
  4850. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4851. * ```
  4852. *
  4853. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4854. * executed after the template has been cloned. This is where most of the directive logic will be
  4855. * put.
  4856. *
  4857. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  4858. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  4859. *
  4860. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4861. * manipulate the children of the element only in `postLink` function since the children have
  4862. * already been linked.
  4863. *
  4864. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4865. * between all directive linking functions.
  4866. *
  4867. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4868. * element defines a controller. The controller is shared among all the directives, which allows
  4869. * the directives to use the controllers as a communication channel.
  4870. *
  4871. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4872. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4873. * parameter of directive controllers.
  4874. * `function([scope], cloneLinkingFn)`.
  4875. *
  4876. *
  4877. * #### Pre-linking function
  4878. *
  4879. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  4880. * compiler linking function will fail to locate the correct elements for linking.
  4881. *
  4882. * #### Post-linking function
  4883. *
  4884. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  4885. *
  4886. * <a name="Attributes"></a>
  4887. * ### Attributes
  4888. *
  4889. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  4890. * `link()` or `compile()` functions. It has a variety of uses.
  4891. *
  4892. * accessing *Normalized attribute names:*
  4893. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  4894. * the attributes object allows for normalized access to
  4895. * the attributes.
  4896. *
  4897. * * *Directive inter-communication:* All directives share the same instance of the attributes
  4898. * object which allows the directives to use the attributes object as inter directive
  4899. * communication.
  4900. *
  4901. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  4902. * allowing other directives to read the interpolated value.
  4903. *
  4904. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  4905. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  4906. * the only way to easily get the actual value because during the linking phase the interpolation
  4907. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  4908. *
  4909. * ```js
  4910. * function linkingFn(scope, elm, attrs, ctrl) {
  4911. * // get the attribute value
  4912. * console.log(attrs.ngModel);
  4913. *
  4914. * // change the attribute
  4915. * attrs.$set('ngModel', 'new value');
  4916. *
  4917. * // observe changes to interpolated attribute
  4918. * attrs.$observe('ngModel', function(value) {
  4919. * console.log('ngModel has changed value to ' + value);
  4920. * });
  4921. * }
  4922. * ```
  4923. *
  4924. * Below is an example using `$compileProvider`.
  4925. *
  4926. * <div class="alert alert-warning">
  4927. * **Note**: Typically directives are registered with `module.directive`. The example below is
  4928. * to illustrate how `$compile` works.
  4929. * </div>
  4930. *
  4931. <example module="compile">
  4932. <file name="index.html">
  4933. <script>
  4934. angular.module('compile', [], function($compileProvider) {
  4935. // configure new 'compile' directive by passing a directive
  4936. // factory function. The factory function injects the '$compile'
  4937. $compileProvider.directive('compile', function($compile) {
  4938. // directive factory creates a link function
  4939. return function(scope, element, attrs) {
  4940. scope.$watch(
  4941. function(scope) {
  4942. // watch the 'compile' expression for changes
  4943. return scope.$eval(attrs.compile);
  4944. },
  4945. function(value) {
  4946. // when the 'compile' expression changes
  4947. // assign it into the current DOM
  4948. element.html(value);
  4949. // compile the new DOM and link it to the current
  4950. // scope.
  4951. // NOTE: we only compile .childNodes so that
  4952. // we don't get into infinite loop compiling ourselves
  4953. $compile(element.contents())(scope);
  4954. }
  4955. );
  4956. };
  4957. })
  4958. });
  4959. function Ctrl($scope) {
  4960. $scope.name = 'Angular';
  4961. $scope.html = 'Hello {{name}}';
  4962. }
  4963. </script>
  4964. <div ng-controller="Ctrl">
  4965. <input ng-model="name"> <br>
  4966. <textarea ng-model="html"></textarea> <br>
  4967. <div compile="html"></div>
  4968. </div>
  4969. </file>
  4970. <file name="protractor.js" type="protractor">
  4971. it('should auto compile', function() {
  4972. var textarea = $('textarea');
  4973. var output = $('div[compile]');
  4974. // The initial state reads 'Hello Angular'.
  4975. expect(output.getText()).toBe('Hello Angular');
  4976. textarea.clear();
  4977. textarea.sendKeys('{{name}}!');
  4978. expect(output.getText()).toBe('Angular!');
  4979. });
  4980. </file>
  4981. </example>
  4982. *
  4983. *
  4984. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  4985. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  4986. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  4987. * root element(s), not their children)
  4988. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  4989. * (a DOM element/tree) to a scope. Where:
  4990. *
  4991. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  4992. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  4993. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  4994. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  4995. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  4996. *
  4997. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  4998. * * `scope` - is the current scope with which the linking function is working with.
  4999. *
  5000. * Calling the linking function returns the element of the template. It is either the original
  5001. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5002. *
  5003. * After linking the view is not updated until after a call to $digest which typically is done by
  5004. * Angular automatically.
  5005. *
  5006. * If you need access to the bound view, there are two ways to do it:
  5007. *
  5008. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5009. * before you send them to the compiler and keep this reference around.
  5010. * ```js
  5011. * var element = $compile('<p>{{total}}</p>')(scope);
  5012. * ```
  5013. *
  5014. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5015. * example would not point to the clone, but rather to the original template that was cloned. In
  5016. * this case, you can access the clone via the cloneAttachFn:
  5017. * ```js
  5018. * var templateElement = angular.element('<p>{{total}}</p>'),
  5019. * scope = ....;
  5020. *
  5021. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5022. * //attach the clone to DOM document at the right place
  5023. * });
  5024. *
  5025. * //now we have reference to the cloned DOM via `clonedElement`
  5026. * ```
  5027. *
  5028. *
  5029. * For information on how the compiler works, see the
  5030. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5031. */
  5032. var $compileMinErr = minErr('$compile');
  5033. /**
  5034. * @ngdoc provider
  5035. * @name $compileProvider
  5036. * @function
  5037. *
  5038. * @description
  5039. */
  5040. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5041. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5042. var hasDirectives = {},
  5043. Suffix = 'Directive',
  5044. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
  5045. CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
  5046. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5047. // The assumption is that future DOM event attribute names will begin with
  5048. // 'on' and be composed of only English letters.
  5049. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5050. /**
  5051. * @ngdoc method
  5052. * @name $compileProvider#directive
  5053. * @function
  5054. *
  5055. * @description
  5056. * Register a new directive with the compiler.
  5057. *
  5058. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5059. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5060. * names and the values are the factories.
  5061. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5062. * {@link guide/directive} for more info.
  5063. * @returns {ng.$compileProvider} Self for chaining.
  5064. */
  5065. this.directive = function registerDirective(name, directiveFactory) {
  5066. assertNotHasOwnProperty(name, 'directive');
  5067. if (isString(name)) {
  5068. assertArg(directiveFactory, 'directiveFactory');
  5069. if (!hasDirectives.hasOwnProperty(name)) {
  5070. hasDirectives[name] = [];
  5071. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5072. function($injector, $exceptionHandler) {
  5073. var directives = [];
  5074. forEach(hasDirectives[name], function(directiveFactory, index) {
  5075. try {
  5076. var directive = $injector.invoke(directiveFactory);
  5077. if (isFunction(directive)) {
  5078. directive = { compile: valueFn(directive) };
  5079. } else if (!directive.compile && directive.link) {
  5080. directive.compile = valueFn(directive.link);
  5081. }
  5082. directive.priority = directive.priority || 0;
  5083. directive.index = index;
  5084. directive.name = directive.name || name;
  5085. directive.require = directive.require || (directive.controller && directive.name);
  5086. directive.restrict = directive.restrict || 'A';
  5087. directives.push(directive);
  5088. } catch (e) {
  5089. $exceptionHandler(e);
  5090. }
  5091. });
  5092. return directives;
  5093. }]);
  5094. }
  5095. hasDirectives[name].push(directiveFactory);
  5096. } else {
  5097. forEach(name, reverseParams(registerDirective));
  5098. }
  5099. return this;
  5100. };
  5101. /**
  5102. * @ngdoc method
  5103. * @name $compileProvider#aHrefSanitizationWhitelist
  5104. * @function
  5105. *
  5106. * @description
  5107. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5108. * urls during a[href] sanitization.
  5109. *
  5110. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5111. *
  5112. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5113. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5114. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5115. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5116. *
  5117. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5118. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5119. * chaining otherwise.
  5120. */
  5121. this.aHrefSanitizationWhitelist = function(regexp) {
  5122. if (isDefined(regexp)) {
  5123. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5124. return this;
  5125. } else {
  5126. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5127. }
  5128. };
  5129. /**
  5130. * @ngdoc method
  5131. * @name $compileProvider#imgSrcSanitizationWhitelist
  5132. * @function
  5133. *
  5134. * @description
  5135. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5136. * urls during img[src] sanitization.
  5137. *
  5138. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5139. *
  5140. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5141. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5142. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5143. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5144. *
  5145. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5146. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5147. * chaining otherwise.
  5148. */
  5149. this.imgSrcSanitizationWhitelist = function(regexp) {
  5150. if (isDefined(regexp)) {
  5151. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5152. return this;
  5153. } else {
  5154. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5155. }
  5156. };
  5157. this.$get = [
  5158. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  5159. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5160. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  5161. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5162. var Attributes = function(element, attr) {
  5163. this.$$element = element;
  5164. this.$attr = attr || {};
  5165. };
  5166. Attributes.prototype = {
  5167. $normalize: directiveNormalize,
  5168. /**
  5169. * @ngdoc method
  5170. * @name $compile.directive.Attributes#$addClass
  5171. * @function
  5172. *
  5173. * @description
  5174. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5175. * are enabled then an animation will be triggered for the class addition.
  5176. *
  5177. * @param {string} classVal The className value that will be added to the element
  5178. */
  5179. $addClass : function(classVal) {
  5180. if(classVal && classVal.length > 0) {
  5181. $animate.addClass(this.$$element, classVal);
  5182. }
  5183. },
  5184. /**
  5185. * @ngdoc method
  5186. * @name $compile.directive.Attributes#$removeClass
  5187. * @function
  5188. *
  5189. * @description
  5190. * Removes the CSS class value specified by the classVal parameter from the element. If
  5191. * animations are enabled then an animation will be triggered for the class removal.
  5192. *
  5193. * @param {string} classVal The className value that will be removed from the element
  5194. */
  5195. $removeClass : function(classVal) {
  5196. if(classVal && classVal.length > 0) {
  5197. $animate.removeClass(this.$$element, classVal);
  5198. }
  5199. },
  5200. /**
  5201. * @ngdoc method
  5202. * @name $compile.directive.Attributes#$updateClass
  5203. * @function
  5204. *
  5205. * @description
  5206. * Adds and removes the appropriate CSS class values to the element based on the difference
  5207. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5208. *
  5209. * @param {string} newClasses The current CSS className value
  5210. * @param {string} oldClasses The former CSS className value
  5211. */
  5212. $updateClass : function(newClasses, oldClasses) {
  5213. var toAdd = tokenDifference(newClasses, oldClasses);
  5214. var toRemove = tokenDifference(oldClasses, newClasses);
  5215. if(toAdd.length === 0) {
  5216. $animate.removeClass(this.$$element, toRemove);
  5217. } else if(toRemove.length === 0) {
  5218. $animate.addClass(this.$$element, toAdd);
  5219. } else {
  5220. $animate.setClass(this.$$element, toAdd, toRemove);
  5221. }
  5222. },
  5223. /**
  5224. * Set a normalized attribute on the element in a way such that all directives
  5225. * can share the attribute. This function properly handles boolean attributes.
  5226. * @param {string} key Normalized key. (ie ngAttribute)
  5227. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5228. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5229. * Defaults to true.
  5230. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5231. */
  5232. $set: function(key, value, writeAttr, attrName) {
  5233. // TODO: decide whether or not to throw an error if "class"
  5234. //is set through this function since it may cause $updateClass to
  5235. //become unstable.
  5236. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5237. normalizedVal,
  5238. nodeName;
  5239. if (booleanKey) {
  5240. this.$$element.prop(key, value);
  5241. attrName = booleanKey;
  5242. }
  5243. this[key] = value;
  5244. // translate normalized key to actual key
  5245. if (attrName) {
  5246. this.$attr[key] = attrName;
  5247. } else {
  5248. attrName = this.$attr[key];
  5249. if (!attrName) {
  5250. this.$attr[key] = attrName = snake_case(key, '-');
  5251. }
  5252. }
  5253. nodeName = nodeName_(this.$$element);
  5254. // sanitize a[href] and img[src] values
  5255. if ((nodeName === 'A' && key === 'href') ||
  5256. (nodeName === 'IMG' && key === 'src')) {
  5257. this[key] = value = $$sanitizeUri(value, key === 'src');
  5258. }
  5259. if (writeAttr !== false) {
  5260. if (value === null || value === undefined) {
  5261. this.$$element.removeAttr(attrName);
  5262. } else {
  5263. this.$$element.attr(attrName, value);
  5264. }
  5265. }
  5266. // fire observers
  5267. var $$observers = this.$$observers;
  5268. $$observers && forEach($$observers[key], function(fn) {
  5269. try {
  5270. fn(value);
  5271. } catch (e) {
  5272. $exceptionHandler(e);
  5273. }
  5274. });
  5275. },
  5276. /**
  5277. * @ngdoc method
  5278. * @name $compile.directive.Attributes#$observe
  5279. * @function
  5280. *
  5281. * @description
  5282. * Observes an interpolated attribute.
  5283. *
  5284. * The observer function will be invoked once during the next `$digest` following
  5285. * compilation. The observer is then invoked whenever the interpolated value
  5286. * changes.
  5287. *
  5288. * @param {string} key Normalized key. (ie ngAttribute) .
  5289. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5290. the interpolated value of the attribute changes.
  5291. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5292. * @returns {function()} the `fn` parameter.
  5293. */
  5294. $observe: function(key, fn) {
  5295. var attrs = this,
  5296. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5297. listeners = ($$observers[key] || ($$observers[key] = []));
  5298. listeners.push(fn);
  5299. $rootScope.$evalAsync(function() {
  5300. if (!listeners.$$inter) {
  5301. // no one registered attribute interpolation function, so lets call it manually
  5302. fn(attrs[key]);
  5303. }
  5304. });
  5305. return fn;
  5306. }
  5307. };
  5308. var startSymbol = $interpolate.startSymbol(),
  5309. endSymbol = $interpolate.endSymbol(),
  5310. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5311. ? identity
  5312. : function denormalizeTemplate(template) {
  5313. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5314. },
  5315. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5316. return compile;
  5317. //================================
  5318. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5319. previousCompileContext) {
  5320. if (!($compileNodes instanceof jqLite)) {
  5321. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5322. // modify it.
  5323. $compileNodes = jqLite($compileNodes);
  5324. }
  5325. // We can not compile top level text elements since text nodes can be merged and we will
  5326. // not be able to attach scope data to them, so we will wrap them in <span>
  5327. forEach($compileNodes, function(node, index){
  5328. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5329. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5330. }
  5331. });
  5332. var compositeLinkFn =
  5333. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5334. maxPriority, ignoreDirective, previousCompileContext);
  5335. safeAddClass($compileNodes, 'ng-scope');
  5336. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  5337. assertArg(scope, 'scope');
  5338. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5339. // and sometimes changes the structure of the DOM.
  5340. var $linkNode = cloneConnectFn
  5341. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5342. : $compileNodes;
  5343. forEach(transcludeControllers, function(instance, name) {
  5344. $linkNode.data('$' + name + 'Controller', instance);
  5345. });
  5346. // Attach scope only to non-text nodes.
  5347. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5348. var node = $linkNode[i],
  5349. nodeType = node.nodeType;
  5350. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5351. $linkNode.eq(i).data('$scope', scope);
  5352. }
  5353. }
  5354. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5355. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  5356. return $linkNode;
  5357. };
  5358. }
  5359. function safeAddClass($element, className) {
  5360. try {
  5361. $element.addClass(className);
  5362. } catch(e) {
  5363. // ignore, since it means that we are trying to set class on
  5364. // SVG element, where class name is read-only.
  5365. }
  5366. }
  5367. /**
  5368. * Compile function matches each node in nodeList against the directives. Once all directives
  5369. * for a particular node are collected their compile functions are executed. The compile
  5370. * functions return values - the linking functions - are combined into a composite linking
  5371. * function, which is the a linking function for the node.
  5372. *
  5373. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5374. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5375. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5376. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5377. * the rootElement must be set the jqLite collection of the compile root. This is
  5378. * needed so that the jqLite collection items can be replaced with widgets.
  5379. * @param {number=} maxPriority Max directive priority.
  5380. * @returns {Function} A composite linking function of all of the matched directives or null.
  5381. */
  5382. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5383. previousCompileContext) {
  5384. var linkFns = [],
  5385. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5386. for (var i = 0; i < nodeList.length; i++) {
  5387. attrs = new Attributes();
  5388. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5389. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5390. ignoreDirective);
  5391. nodeLinkFn = (directives.length)
  5392. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5393. null, [], [], previousCompileContext)
  5394. : null;
  5395. if (nodeLinkFn && nodeLinkFn.scope) {
  5396. safeAddClass(jqLite(nodeList[i]), 'ng-scope');
  5397. }
  5398. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5399. !(childNodes = nodeList[i].childNodes) ||
  5400. !childNodes.length)
  5401. ? null
  5402. : compileNodes(childNodes,
  5403. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  5404. linkFns.push(nodeLinkFn, childLinkFn);
  5405. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5406. //use the previous context only for the first element in the virtual group
  5407. previousCompileContext = null;
  5408. }
  5409. // return a linking function if we have found anything, null otherwise
  5410. return linkFnFound ? compositeLinkFn : null;
  5411. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  5412. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  5413. // copy nodeList so that linking doesn't break due to live list updates.
  5414. var nodeListLength = nodeList.length,
  5415. stableNodeList = new Array(nodeListLength);
  5416. for (i = 0; i < nodeListLength; i++) {
  5417. stableNodeList[i] = nodeList[i];
  5418. }
  5419. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5420. node = stableNodeList[n];
  5421. nodeLinkFn = linkFns[i++];
  5422. childLinkFn = linkFns[i++];
  5423. $node = jqLite(node);
  5424. if (nodeLinkFn) {
  5425. if (nodeLinkFn.scope) {
  5426. childScope = scope.$new();
  5427. $node.data('$scope', childScope);
  5428. } else {
  5429. childScope = scope;
  5430. }
  5431. childTranscludeFn = nodeLinkFn.transclude;
  5432. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  5433. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  5434. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  5435. );
  5436. } else {
  5437. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  5438. }
  5439. } else if (childLinkFn) {
  5440. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  5441. }
  5442. }
  5443. }
  5444. }
  5445. function createBoundTranscludeFn(scope, transcludeFn) {
  5446. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  5447. var scopeCreated = false;
  5448. if (!transcludedScope) {
  5449. transcludedScope = scope.$new();
  5450. transcludedScope.$$transcluded = true;
  5451. scopeCreated = true;
  5452. }
  5453. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  5454. if (scopeCreated) {
  5455. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  5456. }
  5457. return clone;
  5458. };
  5459. }
  5460. /**
  5461. * Looks for directives on the given node and adds them to the directive collection which is
  5462. * sorted.
  5463. *
  5464. * @param node Node to search.
  5465. * @param directives An array to which the directives are added to. This array is sorted before
  5466. * the function returns.
  5467. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5468. * @param {number=} maxPriority Max directive priority.
  5469. */
  5470. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5471. var nodeType = node.nodeType,
  5472. attrsMap = attrs.$attr,
  5473. match,
  5474. className;
  5475. switch(nodeType) {
  5476. case 1: /* Element */
  5477. // use the node name: <directive>
  5478. addDirective(directives,
  5479. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5480. // iterate over the attributes
  5481. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  5482. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5483. var attrStartName = false;
  5484. var attrEndName = false;
  5485. attr = nAttrs[j];
  5486. if (!msie || msie >= 8 || attr.specified) {
  5487. name = attr.name;
  5488. // support ngAttr attribute binding
  5489. ngAttrName = directiveNormalize(name);
  5490. if (NG_ATTR_BINDING.test(ngAttrName)) {
  5491. name = snake_case(ngAttrName.substr(6), '-');
  5492. }
  5493. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5494. if (ngAttrName === directiveNName + 'Start') {
  5495. attrStartName = name;
  5496. attrEndName = name.substr(0, name.length - 5) + 'end';
  5497. name = name.substr(0, name.length - 6);
  5498. }
  5499. nName = directiveNormalize(name.toLowerCase());
  5500. attrsMap[nName] = name;
  5501. attrs[nName] = value = trim(attr.value);
  5502. if (getBooleanAttrName(node, nName)) {
  5503. attrs[nName] = true; // presence means true
  5504. }
  5505. addAttrInterpolateDirective(node, directives, value, nName);
  5506. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5507. attrEndName);
  5508. }
  5509. }
  5510. // use class as directive
  5511. className = node.className;
  5512. if (isString(className) && className !== '') {
  5513. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5514. nName = directiveNormalize(match[2]);
  5515. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5516. attrs[nName] = trim(match[3]);
  5517. }
  5518. className = className.substr(match.index + match[0].length);
  5519. }
  5520. }
  5521. break;
  5522. case 3: /* Text Node */
  5523. addTextInterpolateDirective(directives, node.nodeValue);
  5524. break;
  5525. case 8: /* Comment */
  5526. try {
  5527. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5528. if (match) {
  5529. nName = directiveNormalize(match[1]);
  5530. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5531. attrs[nName] = trim(match[2]);
  5532. }
  5533. }
  5534. } catch (e) {
  5535. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5536. // comment's node value.
  5537. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5538. }
  5539. break;
  5540. }
  5541. directives.sort(byPriority);
  5542. return directives;
  5543. }
  5544. /**
  5545. * Given a node with an directive-start it collects all of the siblings until it finds
  5546. * directive-end.
  5547. * @param node
  5548. * @param attrStart
  5549. * @param attrEnd
  5550. * @returns {*}
  5551. */
  5552. function groupScan(node, attrStart, attrEnd) {
  5553. var nodes = [];
  5554. var depth = 0;
  5555. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5556. var startNode = node;
  5557. do {
  5558. if (!node) {
  5559. throw $compileMinErr('uterdir',
  5560. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5561. attrStart, attrEnd);
  5562. }
  5563. if (node.nodeType == 1 /** Element **/) {
  5564. if (node.hasAttribute(attrStart)) depth++;
  5565. if (node.hasAttribute(attrEnd)) depth--;
  5566. }
  5567. nodes.push(node);
  5568. node = node.nextSibling;
  5569. } while (depth > 0);
  5570. } else {
  5571. nodes.push(node);
  5572. }
  5573. return jqLite(nodes);
  5574. }
  5575. /**
  5576. * Wrapper for linking function which converts normal linking function into a grouped
  5577. * linking function.
  5578. * @param linkFn
  5579. * @param attrStart
  5580. * @param attrEnd
  5581. * @returns {Function}
  5582. */
  5583. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5584. return function(scope, element, attrs, controllers, transcludeFn) {
  5585. element = groupScan(element[0], attrStart, attrEnd);
  5586. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5587. };
  5588. }
  5589. /**
  5590. * Once the directives have been collected, their compile functions are executed. This method
  5591. * is responsible for inlining directive templates as well as terminating the application
  5592. * of the directives if the terminal directive has been reached.
  5593. *
  5594. * @param {Array} directives Array of collected directives to execute their compile function.
  5595. * this needs to be pre-sorted by priority order.
  5596. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5597. * @param {Object} templateAttrs The shared attribute function
  5598. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5599. * scope argument is auto-generated to the new
  5600. * child of the transcluded parent scope.
  5601. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5602. * argument has the root jqLite array so that we can replace nodes
  5603. * on it.
  5604. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5605. * compiling the transclusion.
  5606. * @param {Array.<Function>} preLinkFns
  5607. * @param {Array.<Function>} postLinkFns
  5608. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5609. * node
  5610. * @returns {Function} linkFn
  5611. */
  5612. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5613. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5614. previousCompileContext) {
  5615. previousCompileContext = previousCompileContext || {};
  5616. var terminalPriority = -Number.MAX_VALUE,
  5617. newScopeDirective,
  5618. controllerDirectives = previousCompileContext.controllerDirectives,
  5619. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5620. templateDirective = previousCompileContext.templateDirective,
  5621. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5622. hasTranscludeDirective = false,
  5623. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5624. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5625. directive,
  5626. directiveName,
  5627. $template,
  5628. replaceDirective = originalReplaceDirective,
  5629. childTranscludeFn = transcludeFn,
  5630. linkFn,
  5631. directiveValue;
  5632. // executes all directives on the current element
  5633. for(var i = 0, ii = directives.length; i < ii; i++) {
  5634. directive = directives[i];
  5635. var attrStart = directive.$$start;
  5636. var attrEnd = directive.$$end;
  5637. // collect multiblock sections
  5638. if (attrStart) {
  5639. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5640. }
  5641. $template = undefined;
  5642. if (terminalPriority > directive.priority) {
  5643. break; // prevent further processing of directives
  5644. }
  5645. if (directiveValue = directive.scope) {
  5646. newScopeDirective = newScopeDirective || directive;
  5647. // skip the check for directives with async templates, we'll check the derived sync
  5648. // directive when the template arrives
  5649. if (!directive.templateUrl) {
  5650. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5651. $compileNode);
  5652. if (isObject(directiveValue)) {
  5653. newIsolateScopeDirective = directive;
  5654. }
  5655. }
  5656. }
  5657. directiveName = directive.name;
  5658. if (!directive.templateUrl && directive.controller) {
  5659. directiveValue = directive.controller;
  5660. controllerDirectives = controllerDirectives || {};
  5661. assertNoDuplicate("'" + directiveName + "' controller",
  5662. controllerDirectives[directiveName], directive, $compileNode);
  5663. controllerDirectives[directiveName] = directive;
  5664. }
  5665. if (directiveValue = directive.transclude) {
  5666. hasTranscludeDirective = true;
  5667. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5668. // This option should only be used by directives that know how to safely handle element transclusion,
  5669. // where the transcluded nodes are added or replaced after linking.
  5670. if (!directive.$$tlb) {
  5671. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5672. nonTlbTranscludeDirective = directive;
  5673. }
  5674. if (directiveValue == 'element') {
  5675. hasElementTranscludeDirective = true;
  5676. terminalPriority = directive.priority;
  5677. $template = groupScan(compileNode, attrStart, attrEnd);
  5678. $compileNode = templateAttrs.$$element =
  5679. jqLite(document.createComment(' ' + directiveName + ': ' +
  5680. templateAttrs[directiveName] + ' '));
  5681. compileNode = $compileNode[0];
  5682. replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
  5683. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5684. replaceDirective && replaceDirective.name, {
  5685. // Don't pass in:
  5686. // - controllerDirectives - otherwise we'll create duplicates controllers
  5687. // - newIsolateScopeDirective or templateDirective - combining templates with
  5688. // element transclusion doesn't make sense.
  5689. //
  5690. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5691. // on the same element more than once.
  5692. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5693. });
  5694. } else {
  5695. $template = jqLite(jqLiteClone(compileNode)).contents();
  5696. $compileNode.empty(); // clear contents
  5697. childTranscludeFn = compile($template, transcludeFn);
  5698. }
  5699. }
  5700. if (directive.template) {
  5701. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5702. templateDirective = directive;
  5703. directiveValue = (isFunction(directive.template))
  5704. ? directive.template($compileNode, templateAttrs)
  5705. : directive.template;
  5706. directiveValue = denormalizeTemplate(directiveValue);
  5707. if (directive.replace) {
  5708. replaceDirective = directive;
  5709. if (jqLiteIsTextNode(directiveValue)) {
  5710. $template = [];
  5711. } else {
  5712. $template = jqLite(directiveValue);
  5713. }
  5714. compileNode = $template[0];
  5715. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5716. throw $compileMinErr('tplrt',
  5717. "Template for directive '{0}' must have exactly one root element. {1}",
  5718. directiveName, '');
  5719. }
  5720. replaceWith(jqCollection, $compileNode, compileNode);
  5721. var newTemplateAttrs = {$attr: {}};
  5722. // combine directives from the original node and from the template:
  5723. // - take the array of directives for this element
  5724. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5725. // - collect directives from the template and sort them by priority
  5726. // - combine directives as: processed + template + unprocessed
  5727. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5728. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5729. if (newIsolateScopeDirective) {
  5730. markDirectivesAsIsolate(templateDirectives);
  5731. }
  5732. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5733. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5734. ii = directives.length;
  5735. } else {
  5736. $compileNode.html(directiveValue);
  5737. }
  5738. }
  5739. if (directive.templateUrl) {
  5740. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5741. templateDirective = directive;
  5742. if (directive.replace) {
  5743. replaceDirective = directive;
  5744. }
  5745. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5746. templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
  5747. controllerDirectives: controllerDirectives,
  5748. newIsolateScopeDirective: newIsolateScopeDirective,
  5749. templateDirective: templateDirective,
  5750. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5751. });
  5752. ii = directives.length;
  5753. } else if (directive.compile) {
  5754. try {
  5755. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5756. if (isFunction(linkFn)) {
  5757. addLinkFns(null, linkFn, attrStart, attrEnd);
  5758. } else if (linkFn) {
  5759. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5760. }
  5761. } catch (e) {
  5762. $exceptionHandler(e, startingTag($compileNode));
  5763. }
  5764. }
  5765. if (directive.terminal) {
  5766. nodeLinkFn.terminal = true;
  5767. terminalPriority = Math.max(terminalPriority, directive.priority);
  5768. }
  5769. }
  5770. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5771. nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
  5772. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5773. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5774. return nodeLinkFn;
  5775. ////////////////////
  5776. function addLinkFns(pre, post, attrStart, attrEnd) {
  5777. if (pre) {
  5778. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5779. pre.require = directive.require;
  5780. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5781. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5782. }
  5783. preLinkFns.push(pre);
  5784. }
  5785. if (post) {
  5786. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5787. post.require = directive.require;
  5788. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5789. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5790. }
  5791. postLinkFns.push(post);
  5792. }
  5793. }
  5794. function getControllers(require, $element, elementControllers) {
  5795. var value, retrievalMethod = 'data', optional = false;
  5796. if (isString(require)) {
  5797. while((value = require.charAt(0)) == '^' || value == '?') {
  5798. require = require.substr(1);
  5799. if (value == '^') {
  5800. retrievalMethod = 'inheritedData';
  5801. }
  5802. optional = optional || value == '?';
  5803. }
  5804. value = null;
  5805. if (elementControllers && retrievalMethod === 'data') {
  5806. value = elementControllers[require];
  5807. }
  5808. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5809. if (!value && !optional) {
  5810. throw $compileMinErr('ctreq',
  5811. "Controller '{0}', required by directive '{1}', can't be found!",
  5812. require, directiveName);
  5813. }
  5814. return value;
  5815. } else if (isArray(require)) {
  5816. value = [];
  5817. forEach(require, function(require) {
  5818. value.push(getControllers(require, $element, elementControllers));
  5819. });
  5820. }
  5821. return value;
  5822. }
  5823. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5824. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5825. if (compileNode === linkNode) {
  5826. attrs = templateAttrs;
  5827. } else {
  5828. attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5829. }
  5830. $element = attrs.$$element;
  5831. if (newIsolateScopeDirective) {
  5832. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5833. var $linkNode = jqLite(linkNode);
  5834. isolateScope = scope.$new(true);
  5835. if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5836. $linkNode.data('$isolateScope', isolateScope) ;
  5837. } else {
  5838. $linkNode.data('$isolateScopeNoTemplate', isolateScope);
  5839. }
  5840. safeAddClass($linkNode, 'ng-isolate-scope');
  5841. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5842. var match = definition.match(LOCAL_REGEXP) || [],
  5843. attrName = match[3] || scopeName,
  5844. optional = (match[2] == '?'),
  5845. mode = match[1], // @, =, or &
  5846. lastValue,
  5847. parentGet, parentSet, compare;
  5848. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5849. switch (mode) {
  5850. case '@':
  5851. attrs.$observe(attrName, function(value) {
  5852. isolateScope[scopeName] = value;
  5853. });
  5854. attrs.$$observers[attrName].$$scope = scope;
  5855. if( attrs[attrName] ) {
  5856. // If the attribute has been provided then we trigger an interpolation to ensure
  5857. // the value is there for use in the link fn
  5858. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5859. }
  5860. break;
  5861. case '=':
  5862. if (optional && !attrs[attrName]) {
  5863. return;
  5864. }
  5865. parentGet = $parse(attrs[attrName]);
  5866. if (parentGet.literal) {
  5867. compare = equals;
  5868. } else {
  5869. compare = function(a,b) { return a === b; };
  5870. }
  5871. parentSet = parentGet.assign || function() {
  5872. // reset the change, or we will throw this exception on every $digest
  5873. lastValue = isolateScope[scopeName] = parentGet(scope);
  5874. throw $compileMinErr('nonassign',
  5875. "Expression '{0}' used with directive '{1}' is non-assignable!",
  5876. attrs[attrName], newIsolateScopeDirective.name);
  5877. };
  5878. lastValue = isolateScope[scopeName] = parentGet(scope);
  5879. isolateScope.$watch(function parentValueWatch() {
  5880. var parentValue = parentGet(scope);
  5881. if (!compare(parentValue, isolateScope[scopeName])) {
  5882. // we are out of sync and need to copy
  5883. if (!compare(parentValue, lastValue)) {
  5884. // parent changed and it has precedence
  5885. isolateScope[scopeName] = parentValue;
  5886. } else {
  5887. // if the parent can be assigned then do so
  5888. parentSet(scope, parentValue = isolateScope[scopeName]);
  5889. }
  5890. }
  5891. return lastValue = parentValue;
  5892. }, null, parentGet.literal);
  5893. break;
  5894. case '&':
  5895. parentGet = $parse(attrs[attrName]);
  5896. isolateScope[scopeName] = function(locals) {
  5897. return parentGet(scope, locals);
  5898. };
  5899. break;
  5900. default:
  5901. throw $compileMinErr('iscp',
  5902. "Invalid isolate scope definition for directive '{0}'." +
  5903. " Definition: {... {1}: '{2}' ...}",
  5904. newIsolateScopeDirective.name, scopeName, definition);
  5905. }
  5906. });
  5907. }
  5908. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  5909. if (controllerDirectives) {
  5910. forEach(controllerDirectives, function(directive) {
  5911. var locals = {
  5912. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  5913. $element: $element,
  5914. $attrs: attrs,
  5915. $transclude: transcludeFn
  5916. }, controllerInstance;
  5917. controller = directive.controller;
  5918. if (controller == '@') {
  5919. controller = attrs[directive.name];
  5920. }
  5921. controllerInstance = $controller(controller, locals);
  5922. // For directives with element transclusion the element is a comment,
  5923. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  5924. // clean up (http://bugs.jquery.com/ticket/8335).
  5925. // Instead, we save the controllers for the element in a local hash and attach to .data
  5926. // later, once we have the actual element.
  5927. elementControllers[directive.name] = controllerInstance;
  5928. if (!hasElementTranscludeDirective) {
  5929. $element.data('$' + directive.name + 'Controller', controllerInstance);
  5930. }
  5931. if (directive.controllerAs) {
  5932. locals.$scope[directive.controllerAs] = controllerInstance;
  5933. }
  5934. });
  5935. }
  5936. // PRELINKING
  5937. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  5938. try {
  5939. linkFn = preLinkFns[i];
  5940. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5941. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5942. } catch (e) {
  5943. $exceptionHandler(e, startingTag($element));
  5944. }
  5945. }
  5946. // RECURSION
  5947. // We only pass the isolate scope, if the isolate directive has a template,
  5948. // otherwise the child elements do not belong to the isolate directive.
  5949. var scopeToChild = scope;
  5950. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  5951. scopeToChild = isolateScope;
  5952. }
  5953. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  5954. // POSTLINKING
  5955. for(i = postLinkFns.length - 1; i >= 0; i--) {
  5956. try {
  5957. linkFn = postLinkFns[i];
  5958. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5959. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5960. } catch (e) {
  5961. $exceptionHandler(e, startingTag($element));
  5962. }
  5963. }
  5964. // This is the function that is injected as `$transclude`.
  5965. function controllersBoundTransclude(scope, cloneAttachFn) {
  5966. var transcludeControllers;
  5967. // no scope passed
  5968. if (arguments.length < 2) {
  5969. cloneAttachFn = scope;
  5970. scope = undefined;
  5971. }
  5972. if (hasElementTranscludeDirective) {
  5973. transcludeControllers = elementControllers;
  5974. }
  5975. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  5976. }
  5977. }
  5978. }
  5979. function markDirectivesAsIsolate(directives) {
  5980. // mark all directives as needing isolate scope.
  5981. for (var j = 0, jj = directives.length; j < jj; j++) {
  5982. directives[j] = inherit(directives[j], {$$isolateScope: true});
  5983. }
  5984. }
  5985. /**
  5986. * looks up the directive and decorates it with exception handling and proper parameters. We
  5987. * call this the boundDirective.
  5988. *
  5989. * @param {string} name name of the directive to look up.
  5990. * @param {string} location The directive must be found in specific format.
  5991. * String containing any of theses characters:
  5992. *
  5993. * * `E`: element name
  5994. * * `A': attribute
  5995. * * `C`: class
  5996. * * `M`: comment
  5997. * @returns {boolean} true if directive was added.
  5998. */
  5999. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6000. endAttrName) {
  6001. if (name === ignoreDirective) return null;
  6002. var match = null;
  6003. if (hasDirectives.hasOwnProperty(name)) {
  6004. for(var directive, directives = $injector.get(name + Suffix),
  6005. i = 0, ii = directives.length; i<ii; i++) {
  6006. try {
  6007. directive = directives[i];
  6008. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6009. directive.restrict.indexOf(location) != -1) {
  6010. if (startAttrName) {
  6011. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6012. }
  6013. tDirectives.push(directive);
  6014. match = directive;
  6015. }
  6016. } catch(e) { $exceptionHandler(e); }
  6017. }
  6018. }
  6019. return match;
  6020. }
  6021. /**
  6022. * When the element is replaced with HTML template then the new attributes
  6023. * on the template need to be merged with the existing attributes in the DOM.
  6024. * The desired effect is to have both of the attributes present.
  6025. *
  6026. * @param {object} dst destination attributes (original DOM)
  6027. * @param {object} src source attributes (from the directive template)
  6028. */
  6029. function mergeTemplateAttributes(dst, src) {
  6030. var srcAttr = src.$attr,
  6031. dstAttr = dst.$attr,
  6032. $element = dst.$$element;
  6033. // reapply the old attributes to the new element
  6034. forEach(dst, function(value, key) {
  6035. if (key.charAt(0) != '$') {
  6036. if (src[key]) {
  6037. value += (key === 'style' ? ';' : ' ') + src[key];
  6038. }
  6039. dst.$set(key, value, true, srcAttr[key]);
  6040. }
  6041. });
  6042. // copy the new attributes on the old attrs object
  6043. forEach(src, function(value, key) {
  6044. if (key == 'class') {
  6045. safeAddClass($element, value);
  6046. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6047. } else if (key == 'style') {
  6048. $element.attr('style', $element.attr('style') + ';' + value);
  6049. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6050. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6051. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6052. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6053. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6054. dst[key] = value;
  6055. dstAttr[key] = srcAttr[key];
  6056. }
  6057. });
  6058. }
  6059. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6060. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6061. var linkQueue = [],
  6062. afterTemplateNodeLinkFn,
  6063. afterTemplateChildLinkFn,
  6064. beforeTemplateCompileNode = $compileNode[0],
  6065. origAsyncDirective = directives.shift(),
  6066. // The fact that we have to copy and patch the directive seems wrong!
  6067. derivedSyncDirective = extend({}, origAsyncDirective, {
  6068. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6069. }),
  6070. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6071. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6072. : origAsyncDirective.templateUrl;
  6073. $compileNode.empty();
  6074. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6075. success(function(content) {
  6076. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6077. content = denormalizeTemplate(content);
  6078. if (origAsyncDirective.replace) {
  6079. if (jqLiteIsTextNode(content)) {
  6080. $template = [];
  6081. } else {
  6082. $template = jqLite(content);
  6083. }
  6084. compileNode = $template[0];
  6085. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6086. throw $compileMinErr('tplrt',
  6087. "Template for directive '{0}' must have exactly one root element. {1}",
  6088. origAsyncDirective.name, templateUrl);
  6089. }
  6090. tempTemplateAttrs = {$attr: {}};
  6091. replaceWith($rootElement, $compileNode, compileNode);
  6092. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6093. if (isObject(origAsyncDirective.scope)) {
  6094. markDirectivesAsIsolate(templateDirectives);
  6095. }
  6096. directives = templateDirectives.concat(directives);
  6097. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6098. } else {
  6099. compileNode = beforeTemplateCompileNode;
  6100. $compileNode.html(content);
  6101. }
  6102. directives.unshift(derivedSyncDirective);
  6103. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6104. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6105. previousCompileContext);
  6106. forEach($rootElement, function(node, i) {
  6107. if (node == compileNode) {
  6108. $rootElement[i] = $compileNode[0];
  6109. }
  6110. });
  6111. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6112. while(linkQueue.length) {
  6113. var scope = linkQueue.shift(),
  6114. beforeTemplateLinkNode = linkQueue.shift(),
  6115. linkRootElement = linkQueue.shift(),
  6116. boundTranscludeFn = linkQueue.shift(),
  6117. linkNode = $compileNode[0];
  6118. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6119. var oldClasses = beforeTemplateLinkNode.className;
  6120. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6121. origAsyncDirective.replace)) {
  6122. // it was cloned therefore we have to clone as well.
  6123. linkNode = jqLiteClone(compileNode);
  6124. }
  6125. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6126. // Copy in CSS classes from original node
  6127. safeAddClass(jqLite(linkNode), oldClasses);
  6128. }
  6129. if (afterTemplateNodeLinkFn.transclude) {
  6130. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
  6131. } else {
  6132. childBoundTranscludeFn = boundTranscludeFn;
  6133. }
  6134. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6135. childBoundTranscludeFn);
  6136. }
  6137. linkQueue = null;
  6138. }).
  6139. error(function(response, code, headers, config) {
  6140. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6141. });
  6142. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6143. if (linkQueue) {
  6144. linkQueue.push(scope);
  6145. linkQueue.push(node);
  6146. linkQueue.push(rootElement);
  6147. linkQueue.push(boundTranscludeFn);
  6148. } else {
  6149. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
  6150. }
  6151. };
  6152. }
  6153. /**
  6154. * Sorting function for bound directives.
  6155. */
  6156. function byPriority(a, b) {
  6157. var diff = b.priority - a.priority;
  6158. if (diff !== 0) return diff;
  6159. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6160. return a.index - b.index;
  6161. }
  6162. function assertNoDuplicate(what, previousDirective, directive, element) {
  6163. if (previousDirective) {
  6164. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6165. previousDirective.name, directive.name, what, startingTag(element));
  6166. }
  6167. }
  6168. function addTextInterpolateDirective(directives, text) {
  6169. var interpolateFn = $interpolate(text, true);
  6170. if (interpolateFn) {
  6171. directives.push({
  6172. priority: 0,
  6173. compile: valueFn(function textInterpolateLinkFn(scope, node) {
  6174. var parent = node.parent(),
  6175. bindings = parent.data('$binding') || [];
  6176. bindings.push(interpolateFn);
  6177. safeAddClass(parent.data('$binding', bindings), 'ng-binding');
  6178. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6179. node[0].nodeValue = value;
  6180. });
  6181. })
  6182. });
  6183. }
  6184. }
  6185. function getTrustedContext(node, attrNormalizedName) {
  6186. if (attrNormalizedName == "srcdoc") {
  6187. return $sce.HTML;
  6188. }
  6189. var tag = nodeName_(node);
  6190. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6191. if (attrNormalizedName == "xlinkHref" ||
  6192. (tag == "FORM" && attrNormalizedName == "action") ||
  6193. (tag != "IMG" && (attrNormalizedName == "src" ||
  6194. attrNormalizedName == "ngSrc"))) {
  6195. return $sce.RESOURCE_URL;
  6196. }
  6197. }
  6198. function addAttrInterpolateDirective(node, directives, value, name) {
  6199. var interpolateFn = $interpolate(value, true);
  6200. // no interpolation found -> ignore
  6201. if (!interpolateFn) return;
  6202. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6203. throw $compileMinErr("selmulti",
  6204. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6205. startingTag(node));
  6206. }
  6207. directives.push({
  6208. priority: 100,
  6209. compile: function() {
  6210. return {
  6211. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6212. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6213. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6214. throw $compileMinErr('nodomevents',
  6215. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6216. "ng- versions (such as ng-click instead of onclick) instead.");
  6217. }
  6218. // we need to interpolate again, in case the attribute value has been updated
  6219. // (e.g. by another directive's compile function)
  6220. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6221. // if attribute was updated so that there is no interpolation going on we don't want to
  6222. // register any observers
  6223. if (!interpolateFn) return;
  6224. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6225. // actual attr value
  6226. attr[name] = interpolateFn(scope);
  6227. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6228. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6229. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6230. //special case for class attribute addition + removal
  6231. //so that class changes can tap into the animation
  6232. //hooks provided by the $animate service. Be sure to
  6233. //skip animations when the first digest occurs (when
  6234. //both the new and the old values are the same) since
  6235. //the CSS classes are the non-interpolated values
  6236. if(name === 'class' && newValue != oldValue) {
  6237. attr.$updateClass(newValue, oldValue);
  6238. } else {
  6239. attr.$set(name, newValue);
  6240. }
  6241. });
  6242. }
  6243. };
  6244. }
  6245. });
  6246. }
  6247. /**
  6248. * This is a special jqLite.replaceWith, which can replace items which
  6249. * have no parents, provided that the containing jqLite collection is provided.
  6250. *
  6251. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6252. * in the root of the tree.
  6253. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6254. * the shell, but replace its DOM node reference.
  6255. * @param {Node} newNode The new DOM node.
  6256. */
  6257. function replaceWith($rootElement, elementsToRemove, newNode) {
  6258. var firstElementToRemove = elementsToRemove[0],
  6259. removeCount = elementsToRemove.length,
  6260. parent = firstElementToRemove.parentNode,
  6261. i, ii;
  6262. if ($rootElement) {
  6263. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6264. if ($rootElement[i] == firstElementToRemove) {
  6265. $rootElement[i++] = newNode;
  6266. for (var j = i, j2 = j + removeCount - 1,
  6267. jj = $rootElement.length;
  6268. j < jj; j++, j2++) {
  6269. if (j2 < jj) {
  6270. $rootElement[j] = $rootElement[j2];
  6271. } else {
  6272. delete $rootElement[j];
  6273. }
  6274. }
  6275. $rootElement.length -= removeCount - 1;
  6276. break;
  6277. }
  6278. }
  6279. }
  6280. if (parent) {
  6281. parent.replaceChild(newNode, firstElementToRemove);
  6282. }
  6283. var fragment = document.createDocumentFragment();
  6284. fragment.appendChild(firstElementToRemove);
  6285. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6286. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6287. var element = elementsToRemove[k];
  6288. jqLite(element).remove(); // must do this way to clean up expando
  6289. fragment.appendChild(element);
  6290. delete elementsToRemove[k];
  6291. }
  6292. elementsToRemove[0] = newNode;
  6293. elementsToRemove.length = 1;
  6294. }
  6295. function cloneAndAnnotateFn(fn, annotation) {
  6296. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6297. }
  6298. }];
  6299. }
  6300. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6301. /**
  6302. * Converts all accepted directives format into proper directive name.
  6303. * All of these will become 'myDirective':
  6304. * my:Directive
  6305. * my-directive
  6306. * x-my-directive
  6307. * data-my:directive
  6308. *
  6309. * Also there is special case for Moz prefix starting with upper case letter.
  6310. * @param name Name to normalize
  6311. */
  6312. function directiveNormalize(name) {
  6313. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6314. }
  6315. /**
  6316. * @ngdoc type
  6317. * @name $compile.directive.Attributes
  6318. *
  6319. * @description
  6320. * A shared object between directive compile / linking functions which contains normalized DOM
  6321. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6322. * needed since all of these are treated as equivalent in Angular:
  6323. *
  6324. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6325. */
  6326. /**
  6327. * @ngdoc property
  6328. * @name $compile.directive.Attributes#$attr
  6329. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  6330. * needed to do reverse lookup from normalized name back to actual name.
  6331. */
  6332. /**
  6333. * @ngdoc method
  6334. * @name $compile.directive.Attributes#$set
  6335. * @function
  6336. *
  6337. * @description
  6338. * Set DOM element attribute value.
  6339. *
  6340. *
  6341. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6342. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6343. * property to the original name.
  6344. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6345. */
  6346. /**
  6347. * Closure compiler type information
  6348. */
  6349. function nodesetLinkingFn(
  6350. /* angular.Scope */ scope,
  6351. /* NodeList */ nodeList,
  6352. /* Element */ rootElement,
  6353. /* function(Function) */ boundTranscludeFn
  6354. ){}
  6355. function directiveLinkingFn(
  6356. /* nodesetLinkingFn */ nodesetLinkingFn,
  6357. /* angular.Scope */ scope,
  6358. /* Node */ node,
  6359. /* Element */ rootElement,
  6360. /* function(Function) */ boundTranscludeFn
  6361. ){}
  6362. function tokenDifference(str1, str2) {
  6363. var values = '',
  6364. tokens1 = str1.split(/\s+/),
  6365. tokens2 = str2.split(/\s+/);
  6366. outer:
  6367. for(var i = 0; i < tokens1.length; i++) {
  6368. var token = tokens1[i];
  6369. for(var j = 0; j < tokens2.length; j++) {
  6370. if(token == tokens2[j]) continue outer;
  6371. }
  6372. values += (values.length > 0 ? ' ' : '') + token;
  6373. }
  6374. return values;
  6375. }
  6376. /**
  6377. * @ngdoc provider
  6378. * @name $controllerProvider
  6379. * @description
  6380. * The {@link ng.$controller $controller service} is used by Angular to create new
  6381. * controllers.
  6382. *
  6383. * This provider allows controller registration via the
  6384. * {@link ng.$controllerProvider#register register} method.
  6385. */
  6386. function $ControllerProvider() {
  6387. var controllers = {},
  6388. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6389. /**
  6390. * @ngdoc method
  6391. * @name $controllerProvider#register
  6392. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6393. * the names and the values are the constructors.
  6394. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6395. * annotations in the array notation).
  6396. */
  6397. this.register = function(name, constructor) {
  6398. assertNotHasOwnProperty(name, 'controller');
  6399. if (isObject(name)) {
  6400. extend(controllers, name);
  6401. } else {
  6402. controllers[name] = constructor;
  6403. }
  6404. };
  6405. this.$get = ['$injector', '$window', function($injector, $window) {
  6406. /**
  6407. * @ngdoc service
  6408. * @name $controller
  6409. * @requires $injector
  6410. *
  6411. * @param {Function|string} constructor If called with a function then it's considered to be the
  6412. * controller constructor function. Otherwise it's considered to be a string which is used
  6413. * to retrieve the controller constructor using the following steps:
  6414. *
  6415. * * check if a controller with given name is registered via `$controllerProvider`
  6416. * * check if evaluating the string on the current scope returns a constructor
  6417. * * check `window[constructor]` on the global `window` object
  6418. *
  6419. * @param {Object} locals Injection locals for Controller.
  6420. * @return {Object} Instance of given controller.
  6421. *
  6422. * @description
  6423. * `$controller` service is responsible for instantiating controllers.
  6424. *
  6425. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6426. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6427. */
  6428. return function(expression, locals) {
  6429. var instance, match, constructor, identifier;
  6430. if(isString(expression)) {
  6431. match = expression.match(CNTRL_REG),
  6432. constructor = match[1],
  6433. identifier = match[3];
  6434. expression = controllers.hasOwnProperty(constructor)
  6435. ? controllers[constructor]
  6436. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6437. assertArgFn(expression, constructor, true);
  6438. }
  6439. instance = $injector.instantiate(expression, locals);
  6440. if (identifier) {
  6441. if (!(locals && typeof locals.$scope == 'object')) {
  6442. throw minErr('$controller')('noscp',
  6443. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6444. constructor || expression.name, identifier);
  6445. }
  6446. locals.$scope[identifier] = instance;
  6447. }
  6448. return instance;
  6449. };
  6450. }];
  6451. }
  6452. /**
  6453. * @ngdoc service
  6454. * @name $document
  6455. * @requires $window
  6456. *
  6457. * @description
  6458. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6459. *
  6460. * @example
  6461. <example>
  6462. <file name="index.html">
  6463. <div ng-controller="MainCtrl">
  6464. <p>$document title: <b ng-bind="title"></b></p>
  6465. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6466. </div>
  6467. </file>
  6468. <file name="script.js">
  6469. function MainCtrl($scope, $document) {
  6470. $scope.title = $document[0].title;
  6471. $scope.windowTitle = angular.element(window.document)[0].title;
  6472. }
  6473. </file>
  6474. </example>
  6475. */
  6476. function $DocumentProvider(){
  6477. this.$get = ['$window', function(window){
  6478. return jqLite(window.document);
  6479. }];
  6480. }
  6481. /**
  6482. * @ngdoc service
  6483. * @name $exceptionHandler
  6484. * @requires ng.$log
  6485. *
  6486. * @description
  6487. * Any uncaught exception in angular expressions is delegated to this service.
  6488. * The default implementation simply delegates to `$log.error` which logs it into
  6489. * the browser console.
  6490. *
  6491. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6492. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6493. *
  6494. * ## Example:
  6495. *
  6496. * ```js
  6497. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6498. * return function (exception, cause) {
  6499. * exception.message += ' (caused by "' + cause + '")';
  6500. * throw exception;
  6501. * };
  6502. * });
  6503. * ```
  6504. *
  6505. * This example will override the normal action of `$exceptionHandler`, to make angular
  6506. * exceptions fail hard when they happen, instead of just logging to the console.
  6507. *
  6508. * @param {Error} exception Exception associated with the error.
  6509. * @param {string=} cause optional information about the context in which
  6510. * the error was thrown.
  6511. *
  6512. */
  6513. function $ExceptionHandlerProvider() {
  6514. this.$get = ['$log', function($log) {
  6515. return function(exception, cause) {
  6516. $log.error.apply($log, arguments);
  6517. };
  6518. }];
  6519. }
  6520. /**
  6521. * Parse headers into key value object
  6522. *
  6523. * @param {string} headers Raw headers as a string
  6524. * @returns {Object} Parsed headers as key value object
  6525. */
  6526. function parseHeaders(headers) {
  6527. var parsed = {}, key, val, i;
  6528. if (!headers) return parsed;
  6529. forEach(headers.split('\n'), function(line) {
  6530. i = line.indexOf(':');
  6531. key = lowercase(trim(line.substr(0, i)));
  6532. val = trim(line.substr(i + 1));
  6533. if (key) {
  6534. if (parsed[key]) {
  6535. parsed[key] += ', ' + val;
  6536. } else {
  6537. parsed[key] = val;
  6538. }
  6539. }
  6540. });
  6541. return parsed;
  6542. }
  6543. /**
  6544. * Returns a function that provides access to parsed headers.
  6545. *
  6546. * Headers are lazy parsed when first requested.
  6547. * @see parseHeaders
  6548. *
  6549. * @param {(string|Object)} headers Headers to provide access to.
  6550. * @returns {function(string=)} Returns a getter function which if called with:
  6551. *
  6552. * - if called with single an argument returns a single header value or null
  6553. * - if called with no arguments returns an object containing all headers.
  6554. */
  6555. function headersGetter(headers) {
  6556. var headersObj = isObject(headers) ? headers : undefined;
  6557. return function(name) {
  6558. if (!headersObj) headersObj = parseHeaders(headers);
  6559. if (name) {
  6560. return headersObj[lowercase(name)] || null;
  6561. }
  6562. return headersObj;
  6563. };
  6564. }
  6565. /**
  6566. * Chain all given functions
  6567. *
  6568. * This function is used for both request and response transforming
  6569. *
  6570. * @param {*} data Data to transform.
  6571. * @param {function(string=)} headers Http headers getter fn.
  6572. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6573. * @returns {*} Transformed data.
  6574. */
  6575. function transformData(data, headers, fns) {
  6576. if (isFunction(fns))
  6577. return fns(data, headers);
  6578. forEach(fns, function(fn) {
  6579. data = fn(data, headers);
  6580. });
  6581. return data;
  6582. }
  6583. function isSuccess(status) {
  6584. return 200 <= status && status < 300;
  6585. }
  6586. function $HttpProvider() {
  6587. var JSON_START = /^\s*(\[|\{[^\{])/,
  6588. JSON_END = /[\}\]]\s*$/,
  6589. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6590. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6591. var defaults = this.defaults = {
  6592. // transform incoming response data
  6593. transformResponse: [function(data) {
  6594. if (isString(data)) {
  6595. // strip json vulnerability protection prefix
  6596. data = data.replace(PROTECTION_PREFIX, '');
  6597. if (JSON_START.test(data) && JSON_END.test(data))
  6598. data = fromJson(data);
  6599. }
  6600. return data;
  6601. }],
  6602. // transform outgoing request data
  6603. transformRequest: [function(d) {
  6604. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6605. }],
  6606. // default headers
  6607. headers: {
  6608. common: {
  6609. 'Accept': 'application/json, text/plain, */*'
  6610. },
  6611. post: copy(CONTENT_TYPE_APPLICATION_JSON),
  6612. put: copy(CONTENT_TYPE_APPLICATION_JSON),
  6613. patch: copy(CONTENT_TYPE_APPLICATION_JSON)
  6614. },
  6615. xsrfCookieName: 'XSRF-TOKEN',
  6616. xsrfHeaderName: 'X-XSRF-TOKEN'
  6617. };
  6618. /**
  6619. * Are ordered by request, i.e. they are applied in the same order as the
  6620. * array, on request, but reverse order, on response.
  6621. */
  6622. var interceptorFactories = this.interceptors = [];
  6623. /**
  6624. * For historical reasons, response interceptors are ordered by the order in which
  6625. * they are applied to the response. (This is the opposite of interceptorFactories)
  6626. */
  6627. var responseInterceptorFactories = this.responseInterceptors = [];
  6628. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6629. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6630. var defaultCache = $cacheFactory('$http');
  6631. /**
  6632. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6633. * The reversal is needed so that we can build up the interception chain around the
  6634. * server request.
  6635. */
  6636. var reversedInterceptors = [];
  6637. forEach(interceptorFactories, function(interceptorFactory) {
  6638. reversedInterceptors.unshift(isString(interceptorFactory)
  6639. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6640. });
  6641. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6642. var responseFn = isString(interceptorFactory)
  6643. ? $injector.get(interceptorFactory)
  6644. : $injector.invoke(interceptorFactory);
  6645. /**
  6646. * Response interceptors go before "around" interceptors (no real reason, just
  6647. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6648. * the splice.
  6649. */
  6650. reversedInterceptors.splice(index, 0, {
  6651. response: function(response) {
  6652. return responseFn($q.when(response));
  6653. },
  6654. responseError: function(response) {
  6655. return responseFn($q.reject(response));
  6656. }
  6657. });
  6658. });
  6659. /**
  6660. * @ngdoc service
  6661. * @kind function
  6662. * @name $http
  6663. * @requires ng.$httpBackend
  6664. * @requires $cacheFactory
  6665. * @requires $rootScope
  6666. * @requires $q
  6667. * @requires $injector
  6668. *
  6669. * @description
  6670. * The `$http` service is a core Angular service that facilitates communication with the remote
  6671. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6672. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6673. *
  6674. * For unit testing applications that use `$http` service, see
  6675. * {@link ngMock.$httpBackend $httpBackend mock}.
  6676. *
  6677. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6678. * $resource} service.
  6679. *
  6680. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6681. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6682. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6683. *
  6684. *
  6685. * # General usage
  6686. * The `$http` service is a function which takes a single argument — a configuration object —
  6687. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6688. * with two $http specific methods: `success` and `error`.
  6689. *
  6690. * ```js
  6691. * $http({method: 'GET', url: '/someUrl'}).
  6692. * success(function(data, status, headers, config) {
  6693. * // this callback will be called asynchronously
  6694. * // when the response is available
  6695. * }).
  6696. * error(function(data, status, headers, config) {
  6697. * // called asynchronously if an error occurs
  6698. * // or server returns response with an error status.
  6699. * });
  6700. * ```
  6701. *
  6702. * Since the returned value of calling the $http function is a `promise`, you can also use
  6703. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6704. * an object representing the response. See the API signature and type info below for more
  6705. * details.
  6706. *
  6707. * A response status code between 200 and 299 is considered a success status and
  6708. * will result in the success callback being called. Note that if the response is a redirect,
  6709. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6710. * called for such responses.
  6711. *
  6712. * # Writing Unit Tests that use $http
  6713. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6714. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6715. * request using trained responses.
  6716. *
  6717. * ```
  6718. * $httpBackend.expectGET(...);
  6719. * $http.get(...);
  6720. * $httpBackend.flush();
  6721. * ```
  6722. *
  6723. * # Shortcut methods
  6724. *
  6725. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6726. * request data must be passed in for POST/PUT requests.
  6727. *
  6728. * ```js
  6729. * $http.get('/someUrl').success(successCallback);
  6730. * $http.post('/someUrl', data).success(successCallback);
  6731. * ```
  6732. *
  6733. * Complete list of shortcut methods:
  6734. *
  6735. * - {@link ng.$http#get $http.get}
  6736. * - {@link ng.$http#head $http.head}
  6737. * - {@link ng.$http#post $http.post}
  6738. * - {@link ng.$http#put $http.put}
  6739. * - {@link ng.$http#delete $http.delete}
  6740. * - {@link ng.$http#jsonp $http.jsonp}
  6741. *
  6742. *
  6743. * # Setting HTTP Headers
  6744. *
  6745. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6746. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6747. * object, which currently contains this default configuration:
  6748. *
  6749. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6750. * - `Accept: application/json, text/plain, * / *`
  6751. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6752. * - `Content-Type: application/json`
  6753. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6754. * - `Content-Type: application/json`
  6755. *
  6756. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6757. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6758. * with the lowercased HTTP method name as the key, e.g.
  6759. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6760. *
  6761. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6762. * fashion. For example:
  6763. *
  6764. * ```
  6765. * module.run(function($http) {
  6766. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6767. * });
  6768. * ```
  6769. *
  6770. * In addition, you can supply a `headers` property in the config object passed when
  6771. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6772. *
  6773. *
  6774. * # Transforming Requests and Responses
  6775. *
  6776. * Both requests and responses can be transformed using transform functions. By default, Angular
  6777. * applies these transformations:
  6778. *
  6779. * Request transformations:
  6780. *
  6781. * - If the `data` property of the request configuration object contains an object, serialize it
  6782. * into JSON format.
  6783. *
  6784. * Response transformations:
  6785. *
  6786. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6787. * - If JSON response is detected, deserialize it using a JSON parser.
  6788. *
  6789. * To globally augment or override the default transforms, modify the
  6790. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6791. * properties. These properties are by default an array of transform functions, which allows you
  6792. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6793. * also decide to completely override any default transformations by assigning your
  6794. * transformation functions to these properties directly without the array wrapper. These defaults
  6795. * are again available on the $http factory at run-time, which may be useful if you have run-time
  6796. * services you wish to be involved in your transformations.
  6797. *
  6798. * Similarly, to locally override the request/response transforms, augment the
  6799. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6800. * into `$http`.
  6801. *
  6802. *
  6803. * # Caching
  6804. *
  6805. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6806. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6807. * When the cache is enabled, `$http` stores the response from the server in the specified
  6808. * cache. The next time the same request is made, the response is served from the cache without
  6809. * sending a request to the server.
  6810. *
  6811. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6812. * the same way that real requests are.
  6813. *
  6814. * If there are multiple GET requests for the same URL that should be cached using the same
  6815. * cache, but the cache is not populated yet, only one request to the server will be made and
  6816. * the remaining requests will be fulfilled using the response from the first request.
  6817. *
  6818. * You can change the default cache to a new object (built with
  6819. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  6820. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  6821. * their `cache` property to `true` will now use this cache object.
  6822. *
  6823. * If you set the default cache to `false` then only requests that specify their own custom
  6824. * cache object will be cached.
  6825. *
  6826. * # Interceptors
  6827. *
  6828. * Before you start creating interceptors, be sure to understand the
  6829. * {@link ng.$q $q and deferred/promise APIs}.
  6830. *
  6831. * For purposes of global error handling, authentication, or any kind of synchronous or
  6832. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  6833. * able to intercept requests before they are handed to the server and
  6834. * responses before they are handed over to the application code that
  6835. * initiated these requests. The interceptors leverage the {@link ng.$q
  6836. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  6837. *
  6838. * The interceptors are service factories that are registered with the `$httpProvider` by
  6839. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  6840. * injected with dependencies (if specified) and returns the interceptor.
  6841. *
  6842. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  6843. *
  6844. * * `request`: interceptors get called with http `config` object. The function is free to
  6845. * modify the `config` or create a new one. The function needs to return the `config`
  6846. * directly or as a promise.
  6847. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  6848. * resolved with a rejection.
  6849. * * `response`: interceptors get called with http `response` object. The function is free to
  6850. * modify the `response` or create a new one. The function needs to return the `response`
  6851. * directly or as a promise.
  6852. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  6853. * resolved with a rejection.
  6854. *
  6855. *
  6856. * ```js
  6857. * // register the interceptor as a service
  6858. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6859. * return {
  6860. * // optional method
  6861. * 'request': function(config) {
  6862. * // do something on success
  6863. * return config || $q.when(config);
  6864. * },
  6865. *
  6866. * // optional method
  6867. * 'requestError': function(rejection) {
  6868. * // do something on error
  6869. * if (canRecover(rejection)) {
  6870. * return responseOrNewPromise
  6871. * }
  6872. * return $q.reject(rejection);
  6873. * },
  6874. *
  6875. *
  6876. *
  6877. * // optional method
  6878. * 'response': function(response) {
  6879. * // do something on success
  6880. * return response || $q.when(response);
  6881. * },
  6882. *
  6883. * // optional method
  6884. * 'responseError': function(rejection) {
  6885. * // do something on error
  6886. * if (canRecover(rejection)) {
  6887. * return responseOrNewPromise
  6888. * }
  6889. * return $q.reject(rejection);
  6890. * }
  6891. * };
  6892. * });
  6893. *
  6894. * $httpProvider.interceptors.push('myHttpInterceptor');
  6895. *
  6896. *
  6897. * // alternatively, register the interceptor via an anonymous factory
  6898. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  6899. * return {
  6900. * 'request': function(config) {
  6901. * // same as above
  6902. * },
  6903. *
  6904. * 'response': function(response) {
  6905. * // same as above
  6906. * }
  6907. * };
  6908. * });
  6909. * ```
  6910. *
  6911. * # Response interceptors (DEPRECATED)
  6912. *
  6913. * Before you start creating interceptors, be sure to understand the
  6914. * {@link ng.$q $q and deferred/promise APIs}.
  6915. *
  6916. * For purposes of global error handling, authentication or any kind of synchronous or
  6917. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  6918. * responses for http requests before they are handed over to the application code that
  6919. * initiated these requests. The response interceptors leverage the {@link ng.$q
  6920. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  6921. *
  6922. * The interceptors are service factories that are registered with the $httpProvider by
  6923. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  6924. * injected with dependencies (if specified) and returns the interceptor — a function that
  6925. * takes a {@link ng.$q promise} and returns the original or a new promise.
  6926. *
  6927. * ```js
  6928. * // register the interceptor as a service
  6929. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6930. * return function(promise) {
  6931. * return promise.then(function(response) {
  6932. * // do something on success
  6933. * return response;
  6934. * }, function(response) {
  6935. * // do something on error
  6936. * if (canRecover(response)) {
  6937. * return responseOrNewPromise
  6938. * }
  6939. * return $q.reject(response);
  6940. * });
  6941. * }
  6942. * });
  6943. *
  6944. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  6945. *
  6946. *
  6947. * // register the interceptor via an anonymous factory
  6948. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  6949. * return function(promise) {
  6950. * // same as above
  6951. * }
  6952. * });
  6953. * ```
  6954. *
  6955. *
  6956. * # Security Considerations
  6957. *
  6958. * When designing web applications, consider security threats from:
  6959. *
  6960. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  6961. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  6962. *
  6963. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  6964. * pre-configured with strategies that address these issues, but for this to work backend server
  6965. * cooperation is required.
  6966. *
  6967. * ## JSON Vulnerability Protection
  6968. *
  6969. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  6970. * allows third party website to turn your JSON resource URL into
  6971. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  6972. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  6973. * Angular will automatically strip the prefix before processing it as JSON.
  6974. *
  6975. * For example if your server needs to return:
  6976. * ```js
  6977. * ['one','two']
  6978. * ```
  6979. *
  6980. * which is vulnerable to attack, your server can return:
  6981. * ```js
  6982. * )]}',
  6983. * ['one','two']
  6984. * ```
  6985. *
  6986. * Angular will strip the prefix, before processing the JSON.
  6987. *
  6988. *
  6989. * ## Cross Site Request Forgery (XSRF) Protection
  6990. *
  6991. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  6992. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  6993. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  6994. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  6995. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  6996. * the XHR came from JavaScript running on your domain. The header will not be set for
  6997. * cross-domain requests.
  6998. *
  6999. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7000. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7001. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7002. * that only JavaScript running on your domain could have sent the request. The token must be
  7003. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7004. * making up its own tokens). We recommend that the token is a digest of your site's
  7005. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
  7006. * for added security.
  7007. *
  7008. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7009. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7010. * or the per-request config object.
  7011. *
  7012. *
  7013. * @param {object} config Object describing the request to be made and how it should be
  7014. * processed. The object has following properties:
  7015. *
  7016. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7017. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7018. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7019. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7020. * JSONified.
  7021. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7022. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7023. * HTTP headers to send to the server. If the return value of a function is null, the
  7024. * header will not be sent.
  7025. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7026. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7027. * - **transformRequest** –
  7028. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7029. * transform function or an array of such functions. The transform function takes the http
  7030. * request body and headers and returns its transformed (typically serialized) version.
  7031. * - **transformResponse** –
  7032. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7033. * transform function or an array of such functions. The transform function takes the http
  7034. * response body and headers and returns its transformed (typically deserialized) version.
  7035. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7036. * GET request, otherwise if a cache instance built with
  7037. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7038. * caching.
  7039. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7040. * that should abort the request when resolved.
  7041. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
  7042. * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5
  7043. * for more information.
  7044. * - **responseType** - `{string}` - see
  7045. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7046. *
  7047. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7048. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7049. * method takes two arguments a success and an error callback which will be called with a
  7050. * response object. The `success` and `error` methods take a single argument - a function that
  7051. * will be called when the request succeeds or fails respectively. The arguments passed into
  7052. * these functions are destructured representation of the response object passed into the
  7053. * `then` method. The response object has these properties:
  7054. *
  7055. * - **data** – `{string|Object}` – The response body transformed with the transform
  7056. * functions.
  7057. * - **status** – `{number}` – HTTP status code of the response.
  7058. * - **headers** – `{function([headerName])}` – Header getter function.
  7059. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7060. * - **statusText** – `{string}` – HTTP status text of the response.
  7061. *
  7062. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7063. * requests. This is primarily meant to be used for debugging purposes.
  7064. *
  7065. *
  7066. * @example
  7067. <example>
  7068. <file name="index.html">
  7069. <div ng-controller="FetchCtrl">
  7070. <select ng-model="method">
  7071. <option>GET</option>
  7072. <option>JSONP</option>
  7073. </select>
  7074. <input type="text" ng-model="url" size="80"/>
  7075. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7076. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7077. <button id="samplejsonpbtn"
  7078. ng-click="updateModel('JSONP',
  7079. 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7080. Sample JSONP
  7081. </button>
  7082. <button id="invalidjsonpbtn"
  7083. ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7084. Invalid JSONP
  7085. </button>
  7086. <pre>http status code: {{status}}</pre>
  7087. <pre>http response data: {{data}}</pre>
  7088. </div>
  7089. </file>
  7090. <file name="script.js">
  7091. function FetchCtrl($scope, $http, $templateCache) {
  7092. $scope.method = 'GET';
  7093. $scope.url = 'http-hello.html';
  7094. $scope.fetch = function() {
  7095. $scope.code = null;
  7096. $scope.response = null;
  7097. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7098. success(function(data, status) {
  7099. $scope.status = status;
  7100. $scope.data = data;
  7101. }).
  7102. error(function(data, status) {
  7103. $scope.data = data || "Request failed";
  7104. $scope.status = status;
  7105. });
  7106. };
  7107. $scope.updateModel = function(method, url) {
  7108. $scope.method = method;
  7109. $scope.url = url;
  7110. };
  7111. }
  7112. </file>
  7113. <file name="http-hello.html">
  7114. Hello, $http!
  7115. </file>
  7116. <file name="protractor.js" type="protractor">
  7117. var status = element(by.binding('status'));
  7118. var data = element(by.binding('data'));
  7119. var fetchBtn = element(by.id('fetchbtn'));
  7120. var sampleGetBtn = element(by.id('samplegetbtn'));
  7121. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7122. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7123. it('should make an xhr GET request', function() {
  7124. sampleGetBtn.click();
  7125. fetchBtn.click();
  7126. expect(status.getText()).toMatch('200');
  7127. expect(data.getText()).toMatch(/Hello, \$http!/);
  7128. });
  7129. it('should make a JSONP request to angularjs.org', function() {
  7130. sampleJsonpBtn.click();
  7131. fetchBtn.click();
  7132. expect(status.getText()).toMatch('200');
  7133. expect(data.getText()).toMatch(/Super Hero!/);
  7134. });
  7135. it('should make JSONP request to invalid URL and invoke the error handler',
  7136. function() {
  7137. invalidJsonpBtn.click();
  7138. fetchBtn.click();
  7139. expect(status.getText()).toMatch('0');
  7140. expect(data.getText()).toMatch('Request failed');
  7141. });
  7142. </file>
  7143. </example>
  7144. */
  7145. function $http(requestConfig) {
  7146. var config = {
  7147. method: 'get',
  7148. transformRequest: defaults.transformRequest,
  7149. transformResponse: defaults.transformResponse
  7150. };
  7151. var headers = mergeHeaders(requestConfig);
  7152. extend(config, requestConfig);
  7153. config.headers = headers;
  7154. config.method = uppercase(config.method);
  7155. var xsrfValue = urlIsSameOrigin(config.url)
  7156. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7157. : undefined;
  7158. if (xsrfValue) {
  7159. headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7160. }
  7161. var serverRequest = function(config) {
  7162. headers = config.headers;
  7163. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7164. // strip content-type if data is undefined
  7165. if (isUndefined(config.data)) {
  7166. forEach(headers, function(value, header) {
  7167. if (lowercase(header) === 'content-type') {
  7168. delete headers[header];
  7169. }
  7170. });
  7171. }
  7172. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7173. config.withCredentials = defaults.withCredentials;
  7174. }
  7175. // send request
  7176. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7177. };
  7178. var chain = [serverRequest, undefined];
  7179. var promise = $q.when(config);
  7180. // apply interceptors
  7181. forEach(reversedInterceptors, function(interceptor) {
  7182. if (interceptor.request || interceptor.requestError) {
  7183. chain.unshift(interceptor.request, interceptor.requestError);
  7184. }
  7185. if (interceptor.response || interceptor.responseError) {
  7186. chain.push(interceptor.response, interceptor.responseError);
  7187. }
  7188. });
  7189. while(chain.length) {
  7190. var thenFn = chain.shift();
  7191. var rejectFn = chain.shift();
  7192. promise = promise.then(thenFn, rejectFn);
  7193. }
  7194. promise.success = function(fn) {
  7195. promise.then(function(response) {
  7196. fn(response.data, response.status, response.headers, config);
  7197. });
  7198. return promise;
  7199. };
  7200. promise.error = function(fn) {
  7201. promise.then(null, function(response) {
  7202. fn(response.data, response.status, response.headers, config);
  7203. });
  7204. return promise;
  7205. };
  7206. return promise;
  7207. function transformResponse(response) {
  7208. // make a copy since the response must be cacheable
  7209. var resp = extend({}, response, {
  7210. data: transformData(response.data, response.headers, config.transformResponse)
  7211. });
  7212. return (isSuccess(response.status))
  7213. ? resp
  7214. : $q.reject(resp);
  7215. }
  7216. function mergeHeaders(config) {
  7217. var defHeaders = defaults.headers,
  7218. reqHeaders = extend({}, config.headers),
  7219. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7220. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7221. // execute if header value is function
  7222. execHeaders(defHeaders);
  7223. execHeaders(reqHeaders);
  7224. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7225. defaultHeadersIteration:
  7226. for (defHeaderName in defHeaders) {
  7227. lowercaseDefHeaderName = lowercase(defHeaderName);
  7228. for (reqHeaderName in reqHeaders) {
  7229. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7230. continue defaultHeadersIteration;
  7231. }
  7232. }
  7233. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7234. }
  7235. return reqHeaders;
  7236. function execHeaders(headers) {
  7237. var headerContent;
  7238. forEach(headers, function(headerFn, header) {
  7239. if (isFunction(headerFn)) {
  7240. headerContent = headerFn();
  7241. if (headerContent != null) {
  7242. headers[header] = headerContent;
  7243. } else {
  7244. delete headers[header];
  7245. }
  7246. }
  7247. });
  7248. }
  7249. }
  7250. }
  7251. $http.pendingRequests = [];
  7252. /**
  7253. * @ngdoc method
  7254. * @name $http#get
  7255. *
  7256. * @description
  7257. * Shortcut method to perform `GET` request.
  7258. *
  7259. * @param {string} url Relative or absolute URL specifying the destination of the request
  7260. * @param {Object=} config Optional configuration object
  7261. * @returns {HttpPromise} Future object
  7262. */
  7263. /**
  7264. * @ngdoc method
  7265. * @name $http#delete
  7266. *
  7267. * @description
  7268. * Shortcut method to perform `DELETE` request.
  7269. *
  7270. * @param {string} url Relative or absolute URL specifying the destination of the request
  7271. * @param {Object=} config Optional configuration object
  7272. * @returns {HttpPromise} Future object
  7273. */
  7274. /**
  7275. * @ngdoc method
  7276. * @name $http#head
  7277. *
  7278. * @description
  7279. * Shortcut method to perform `HEAD` request.
  7280. *
  7281. * @param {string} url Relative or absolute URL specifying the destination of the request
  7282. * @param {Object=} config Optional configuration object
  7283. * @returns {HttpPromise} Future object
  7284. */
  7285. /**
  7286. * @ngdoc method
  7287. * @name $http#jsonp
  7288. *
  7289. * @description
  7290. * Shortcut method to perform `JSONP` request.
  7291. *
  7292. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7293. * Should contain `JSON_CALLBACK` string.
  7294. * @param {Object=} config Optional configuration object
  7295. * @returns {HttpPromise} Future object
  7296. */
  7297. createShortMethods('get', 'delete', 'head', 'jsonp');
  7298. /**
  7299. * @ngdoc method
  7300. * @name $http#post
  7301. *
  7302. * @description
  7303. * Shortcut method to perform `POST` request.
  7304. *
  7305. * @param {string} url Relative or absolute URL specifying the destination of the request
  7306. * @param {*} data Request content
  7307. * @param {Object=} config Optional configuration object
  7308. * @returns {HttpPromise} Future object
  7309. */
  7310. /**
  7311. * @ngdoc method
  7312. * @name $http#put
  7313. *
  7314. * @description
  7315. * Shortcut method to perform `PUT` request.
  7316. *
  7317. * @param {string} url Relative or absolute URL specifying the destination of the request
  7318. * @param {*} data Request content
  7319. * @param {Object=} config Optional configuration object
  7320. * @returns {HttpPromise} Future object
  7321. */
  7322. createShortMethodsWithData('post', 'put');
  7323. /**
  7324. * @ngdoc property
  7325. * @name $http#defaults
  7326. *
  7327. * @description
  7328. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7329. * default headers, withCredentials as well as request and response transformations.
  7330. *
  7331. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7332. */
  7333. $http.defaults = defaults;
  7334. return $http;
  7335. function createShortMethods(names) {
  7336. forEach(arguments, function(name) {
  7337. $http[name] = function(url, config) {
  7338. return $http(extend(config || {}, {
  7339. method: name,
  7340. url: url
  7341. }));
  7342. };
  7343. });
  7344. }
  7345. function createShortMethodsWithData(name) {
  7346. forEach(arguments, function(name) {
  7347. $http[name] = function(url, data, config) {
  7348. return $http(extend(config || {}, {
  7349. method: name,
  7350. url: url,
  7351. data: data
  7352. }));
  7353. };
  7354. });
  7355. }
  7356. /**
  7357. * Makes the request.
  7358. *
  7359. * !!! ACCESSES CLOSURE VARS:
  7360. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7361. */
  7362. function sendReq(config, reqData, reqHeaders) {
  7363. var deferred = $q.defer(),
  7364. promise = deferred.promise,
  7365. cache,
  7366. cachedResp,
  7367. url = buildUrl(config.url, config.params);
  7368. $http.pendingRequests.push(config);
  7369. promise.then(removePendingReq, removePendingReq);
  7370. if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
  7371. cache = isObject(config.cache) ? config.cache
  7372. : isObject(defaults.cache) ? defaults.cache
  7373. : defaultCache;
  7374. }
  7375. if (cache) {
  7376. cachedResp = cache.get(url);
  7377. if (isDefined(cachedResp)) {
  7378. if (cachedResp.then) {
  7379. // cached request has already been sent, but there is no response yet
  7380. cachedResp.then(removePendingReq, removePendingReq);
  7381. return cachedResp;
  7382. } else {
  7383. // serving from cache
  7384. if (isArray(cachedResp)) {
  7385. resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]), cachedResp[3]);
  7386. } else {
  7387. resolvePromise(cachedResp, 200, {}, 'OK');
  7388. }
  7389. }
  7390. } else {
  7391. // put the promise for the non-transformed response into cache as a placeholder
  7392. cache.put(url, promise);
  7393. }
  7394. }
  7395. // if we won't have the response in cache, send the request to the backend
  7396. if (isUndefined(cachedResp)) {
  7397. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7398. config.withCredentials, config.responseType);
  7399. }
  7400. return promise;
  7401. /**
  7402. * Callback registered to $httpBackend():
  7403. * - caches the response if desired
  7404. * - resolves the raw $http promise
  7405. * - calls $apply
  7406. */
  7407. function done(status, response, headersString, statusText) {
  7408. if (cache) {
  7409. if (isSuccess(status)) {
  7410. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7411. } else {
  7412. // remove promise from the cache
  7413. cache.remove(url);
  7414. }
  7415. }
  7416. resolvePromise(response, status, headersString, statusText);
  7417. if (!$rootScope.$$phase) $rootScope.$apply();
  7418. }
  7419. /**
  7420. * Resolves the raw $http promise.
  7421. */
  7422. function resolvePromise(response, status, headers, statusText) {
  7423. // normalize internal statuses to 0
  7424. status = Math.max(status, 0);
  7425. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7426. data: response,
  7427. status: status,
  7428. headers: headersGetter(headers),
  7429. config: config,
  7430. statusText : statusText
  7431. });
  7432. }
  7433. function removePendingReq() {
  7434. var idx = indexOf($http.pendingRequests, config);
  7435. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7436. }
  7437. }
  7438. function buildUrl(url, params) {
  7439. if (!params) return url;
  7440. var parts = [];
  7441. forEachSorted(params, function(value, key) {
  7442. if (value === null || isUndefined(value)) return;
  7443. if (!isArray(value)) value = [value];
  7444. forEach(value, function(v) {
  7445. if (isObject(v)) {
  7446. v = toJson(v);
  7447. }
  7448. parts.push(encodeUriQuery(key) + '=' +
  7449. encodeUriQuery(v));
  7450. });
  7451. });
  7452. if(parts.length > 0) {
  7453. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7454. }
  7455. return url;
  7456. }
  7457. }];
  7458. }
  7459. function createXhr(method) {
  7460. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7461. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7462. //if it is available
  7463. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7464. !window.XMLHttpRequest)) {
  7465. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7466. } else if (window.XMLHttpRequest) {
  7467. return new window.XMLHttpRequest();
  7468. }
  7469. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7470. }
  7471. /**
  7472. * @ngdoc service
  7473. * @name $httpBackend
  7474. * @requires $window
  7475. * @requires $document
  7476. *
  7477. * @description
  7478. * HTTP backend used by the {@link ng.$http service} that delegates to
  7479. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7480. *
  7481. * You should never need to use this service directly, instead use the higher-level abstractions:
  7482. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7483. *
  7484. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7485. * $httpBackend} which can be trained with responses.
  7486. */
  7487. function $HttpBackendProvider() {
  7488. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7489. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7490. }];
  7491. }
  7492. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7493. var ABORTED = -1;
  7494. // TODO(vojta): fix the signature
  7495. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7496. var status;
  7497. $browser.$$incOutstandingRequestCount();
  7498. url = url || $browser.url();
  7499. if (lowercase(method) == 'jsonp') {
  7500. var callbackId = '_' + (callbacks.counter++).toString(36);
  7501. callbacks[callbackId] = function(data) {
  7502. callbacks[callbackId].data = data;
  7503. };
  7504. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7505. function() {
  7506. if (callbacks[callbackId].data) {
  7507. completeRequest(callback, 200, callbacks[callbackId].data);
  7508. } else {
  7509. completeRequest(callback, status || -2);
  7510. }
  7511. callbacks[callbackId] = angular.noop;
  7512. });
  7513. } else {
  7514. var xhr = createXhr(method);
  7515. xhr.open(method, url, true);
  7516. forEach(headers, function(value, key) {
  7517. if (isDefined(value)) {
  7518. xhr.setRequestHeader(key, value);
  7519. }
  7520. });
  7521. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7522. // response is in the cache. the promise api will ensure that to the app code the api is
  7523. // always async
  7524. xhr.onreadystatechange = function() {
  7525. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7526. // xhrs that are resolved while the app is in the background (see #5426).
  7527. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7528. // continuing
  7529. //
  7530. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7531. // Safari respectively.
  7532. if (xhr && xhr.readyState == 4) {
  7533. var responseHeaders = null,
  7534. response = null;
  7535. if(status !== ABORTED) {
  7536. responseHeaders = xhr.getAllResponseHeaders();
  7537. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7538. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7539. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7540. }
  7541. completeRequest(callback,
  7542. status || xhr.status,
  7543. response,
  7544. responseHeaders,
  7545. xhr.statusText || '');
  7546. }
  7547. };
  7548. if (withCredentials) {
  7549. xhr.withCredentials = true;
  7550. }
  7551. if (responseType) {
  7552. try {
  7553. xhr.responseType = responseType;
  7554. } catch (e) {
  7555. // WebKit added support for the json responseType value on 09/03/2013
  7556. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7557. // known to throw when setting the value "json" as the response type. Other older
  7558. // browsers implementing the responseType
  7559. //
  7560. // The json response type can be ignored if not supported, because JSON payloads are
  7561. // parsed on the client-side regardless.
  7562. if (responseType !== 'json') {
  7563. throw e;
  7564. }
  7565. }
  7566. }
  7567. xhr.send(post || null);
  7568. }
  7569. if (timeout > 0) {
  7570. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7571. } else if (timeout && timeout.then) {
  7572. timeout.then(timeoutRequest);
  7573. }
  7574. function timeoutRequest() {
  7575. status = ABORTED;
  7576. jsonpDone && jsonpDone();
  7577. xhr && xhr.abort();
  7578. }
  7579. function completeRequest(callback, status, response, headersString, statusText) {
  7580. // cancel timeout and subsequent timeout promise resolution
  7581. timeoutId && $browserDefer.cancel(timeoutId);
  7582. jsonpDone = xhr = null;
  7583. // fix status code when it is 0 (0 status is undocumented).
  7584. // Occurs when accessing file resources or on Android 4.1 stock browser
  7585. // while retrieving files from application cache.
  7586. if (status === 0) {
  7587. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7588. }
  7589. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7590. status = status === 1223 ? 204 : status;
  7591. statusText = statusText || '';
  7592. callback(status, response, headersString, statusText);
  7593. $browser.$$completeOutstandingRequest(noop);
  7594. }
  7595. };
  7596. function jsonpReq(url, done) {
  7597. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7598. // - fetches local scripts via XHR and evals them
  7599. // - adds and immediately removes script elements from the document
  7600. var script = rawDocument.createElement('script'),
  7601. doneWrapper = function() {
  7602. script.onreadystatechange = script.onload = script.onerror = null;
  7603. rawDocument.body.removeChild(script);
  7604. if (done) done();
  7605. };
  7606. script.type = 'text/javascript';
  7607. script.src = url;
  7608. if (msie && msie <= 8) {
  7609. script.onreadystatechange = function() {
  7610. if (/loaded|complete/.test(script.readyState)) {
  7611. doneWrapper();
  7612. }
  7613. };
  7614. } else {
  7615. script.onload = script.onerror = function() {
  7616. doneWrapper();
  7617. };
  7618. }
  7619. rawDocument.body.appendChild(script);
  7620. return doneWrapper;
  7621. }
  7622. }
  7623. var $interpolateMinErr = minErr('$interpolate');
  7624. /**
  7625. * @ngdoc provider
  7626. * @name $interpolateProvider
  7627. * @function
  7628. *
  7629. * @description
  7630. *
  7631. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7632. *
  7633. * @example
  7634. <example module="customInterpolationApp">
  7635. <file name="index.html">
  7636. <script>
  7637. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7638. customInterpolationApp.config(function($interpolateProvider) {
  7639. $interpolateProvider.startSymbol('//');
  7640. $interpolateProvider.endSymbol('//');
  7641. });
  7642. customInterpolationApp.controller('DemoController', function DemoController() {
  7643. this.label = "This binding is brought you by // interpolation symbols.";
  7644. });
  7645. </script>
  7646. <div ng-app="App" ng-controller="DemoController as demo">
  7647. //demo.label//
  7648. </div>
  7649. </file>
  7650. <file name="protractor.js" type="protractor">
  7651. it('should interpolate binding with custom symbols', function() {
  7652. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7653. });
  7654. </file>
  7655. </example>
  7656. */
  7657. function $InterpolateProvider() {
  7658. var startSymbol = '{{';
  7659. var endSymbol = '}}';
  7660. /**
  7661. * @ngdoc method
  7662. * @name $interpolateProvider#startSymbol
  7663. * @description
  7664. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7665. *
  7666. * @param {string=} value new value to set the starting symbol to.
  7667. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7668. */
  7669. this.startSymbol = function(value){
  7670. if (value) {
  7671. startSymbol = value;
  7672. return this;
  7673. } else {
  7674. return startSymbol;
  7675. }
  7676. };
  7677. /**
  7678. * @ngdoc method
  7679. * @name $interpolateProvider#endSymbol
  7680. * @description
  7681. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7682. *
  7683. * @param {string=} value new value to set the ending symbol to.
  7684. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7685. */
  7686. this.endSymbol = function(value){
  7687. if (value) {
  7688. endSymbol = value;
  7689. return this;
  7690. } else {
  7691. return endSymbol;
  7692. }
  7693. };
  7694. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7695. var startSymbolLength = startSymbol.length,
  7696. endSymbolLength = endSymbol.length;
  7697. /**
  7698. * @ngdoc service
  7699. * @name $interpolate
  7700. * @function
  7701. *
  7702. * @requires $parse
  7703. * @requires $sce
  7704. *
  7705. * @description
  7706. *
  7707. * Compiles a string with markup into an interpolation function. This service is used by the
  7708. * HTML {@link ng.$compile $compile} service for data binding. See
  7709. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7710. * interpolation markup.
  7711. *
  7712. *
  7713. * ```js
  7714. * var $interpolate = ...; // injected
  7715. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7716. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7717. * ```
  7718. *
  7719. *
  7720. * @param {string} text The text with markup to interpolate.
  7721. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7722. * embedded expression in order to return an interpolation function. Strings with no
  7723. * embedded expression will return null for the interpolation function.
  7724. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7725. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7726. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7727. * provides Strict Contextual Escaping for details.
  7728. * @returns {function(context)} an interpolation function which is used to compute the
  7729. * interpolated string. The function has these parameters:
  7730. *
  7731. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7732. * against.
  7733. *
  7734. */
  7735. function $interpolate(text, mustHaveExpression, trustedContext) {
  7736. var startIndex,
  7737. endIndex,
  7738. index = 0,
  7739. parts = [],
  7740. length = text.length,
  7741. hasInterpolation = false,
  7742. fn,
  7743. exp,
  7744. concat = [];
  7745. while(index < length) {
  7746. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7747. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7748. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7749. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7750. fn.exp = exp;
  7751. index = endIndex + endSymbolLength;
  7752. hasInterpolation = true;
  7753. } else {
  7754. // we did not find anything, so we have to add the remainder to the parts array
  7755. (index != length) && parts.push(text.substring(index));
  7756. index = length;
  7757. }
  7758. }
  7759. if (!(length = parts.length)) {
  7760. // we added, nothing, must have been an empty string.
  7761. parts.push('');
  7762. length = 1;
  7763. }
  7764. // Concatenating expressions makes it hard to reason about whether some combination of
  7765. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7766. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7767. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7768. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7769. // the load when auditing for XSS issues.
  7770. if (trustedContext && parts.length > 1) {
  7771. throw $interpolateMinErr('noconcat',
  7772. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7773. "interpolations that concatenate multiple expressions when a trusted value is " +
  7774. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7775. }
  7776. if (!mustHaveExpression || hasInterpolation) {
  7777. concat.length = length;
  7778. fn = function(context) {
  7779. try {
  7780. for(var i = 0, ii = length, part; i<ii; i++) {
  7781. if (typeof (part = parts[i]) == 'function') {
  7782. part = part(context);
  7783. if (trustedContext) {
  7784. part = $sce.getTrusted(trustedContext, part);
  7785. } else {
  7786. part = $sce.valueOf(part);
  7787. }
  7788. if (part === null || isUndefined(part)) {
  7789. part = '';
  7790. } else if (typeof part != 'string') {
  7791. part = toJson(part);
  7792. }
  7793. }
  7794. concat[i] = part;
  7795. }
  7796. return concat.join('');
  7797. }
  7798. catch(err) {
  7799. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  7800. err.toString());
  7801. $exceptionHandler(newErr);
  7802. }
  7803. };
  7804. fn.exp = text;
  7805. fn.parts = parts;
  7806. return fn;
  7807. }
  7808. }
  7809. /**
  7810. * @ngdoc method
  7811. * @name $interpolate#startSymbol
  7812. * @description
  7813. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  7814. *
  7815. * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
  7816. * the symbol.
  7817. *
  7818. * @returns {string} start symbol.
  7819. */
  7820. $interpolate.startSymbol = function() {
  7821. return startSymbol;
  7822. };
  7823. /**
  7824. * @ngdoc method
  7825. * @name $interpolate#endSymbol
  7826. * @description
  7827. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7828. *
  7829. * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
  7830. * the symbol.
  7831. *
  7832. * @returns {string} end symbol.
  7833. */
  7834. $interpolate.endSymbol = function() {
  7835. return endSymbol;
  7836. };
  7837. return $interpolate;
  7838. }];
  7839. }
  7840. function $IntervalProvider() {
  7841. this.$get = ['$rootScope', '$window', '$q',
  7842. function($rootScope, $window, $q) {
  7843. var intervals = {};
  7844. /**
  7845. * @ngdoc service
  7846. * @name $interval
  7847. *
  7848. * @description
  7849. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  7850. * milliseconds.
  7851. *
  7852. * The return value of registering an interval function is a promise. This promise will be
  7853. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  7854. * run indefinitely if `count` is not defined. The value of the notification will be the
  7855. * number of iterations that have run.
  7856. * To cancel an interval, call `$interval.cancel(promise)`.
  7857. *
  7858. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  7859. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  7860. * time.
  7861. *
  7862. * <div class="alert alert-warning">
  7863. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  7864. * with them. In particular they are not automatically destroyed when a controller's scope or a
  7865. * directive's element are destroyed.
  7866. * You should take this into consideration and make sure to always cancel the interval at the
  7867. * appropriate moment. See the example below for more details on how and when to do this.
  7868. * </div>
  7869. *
  7870. * @param {function()} fn A function that should be called repeatedly.
  7871. * @param {number} delay Number of milliseconds between each function call.
  7872. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  7873. * indefinitely.
  7874. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  7875. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  7876. * @returns {promise} A promise which will be notified on each iteration.
  7877. *
  7878. * @example
  7879. * <example module="time">
  7880. * <file name="index.html">
  7881. * <script>
  7882. * function Ctrl2($scope,$interval) {
  7883. * $scope.format = 'M/d/yy h:mm:ss a';
  7884. * $scope.blood_1 = 100;
  7885. * $scope.blood_2 = 120;
  7886. *
  7887. * var stop;
  7888. * $scope.fight = function() {
  7889. * // Don't start a new fight if we are already fighting
  7890. * if ( angular.isDefined(stop) ) return;
  7891. *
  7892. * stop = $interval(function() {
  7893. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  7894. * $scope.blood_1 = $scope.blood_1 - 3;
  7895. * $scope.blood_2 = $scope.blood_2 - 4;
  7896. * } else {
  7897. * $scope.stopFight();
  7898. * }
  7899. * }, 100);
  7900. * };
  7901. *
  7902. * $scope.stopFight = function() {
  7903. * if (angular.isDefined(stop)) {
  7904. * $interval.cancel(stop);
  7905. * stop = undefined;
  7906. * }
  7907. * };
  7908. *
  7909. * $scope.resetFight = function() {
  7910. * $scope.blood_1 = 100;
  7911. * $scope.blood_2 = 120;
  7912. * }
  7913. *
  7914. * $scope.$on('$destroy', function() {
  7915. * // Make sure that the interval is destroyed too
  7916. * $scope.stopFight();
  7917. * });
  7918. * }
  7919. *
  7920. * angular.module('time', [])
  7921. * // Register the 'myCurrentTime' directive factory method.
  7922. * // We inject $interval and dateFilter service since the factory method is DI.
  7923. * .directive('myCurrentTime', function($interval, dateFilter) {
  7924. * // return the directive link function. (compile function not needed)
  7925. * return function(scope, element, attrs) {
  7926. * var format, // date format
  7927. * stopTime; // so that we can cancel the time updates
  7928. *
  7929. * // used to update the UI
  7930. * function updateTime() {
  7931. * element.text(dateFilter(new Date(), format));
  7932. * }
  7933. *
  7934. * // watch the expression, and update the UI on change.
  7935. * scope.$watch(attrs.myCurrentTime, function(value) {
  7936. * format = value;
  7937. * updateTime();
  7938. * });
  7939. *
  7940. * stopTime = $interval(updateTime, 1000);
  7941. *
  7942. * // listen on DOM destroy (removal) event, and cancel the next UI update
  7943. * // to prevent updating time ofter the DOM element was removed.
  7944. * element.bind('$destroy', function() {
  7945. * $interval.cancel(stopTime);
  7946. * });
  7947. * }
  7948. * });
  7949. * </script>
  7950. *
  7951. * <div>
  7952. * <div ng-controller="Ctrl2">
  7953. * Date format: <input ng-model="format"> <hr/>
  7954. * Current time is: <span my-current-time="format"></span>
  7955. * <hr/>
  7956. * Blood 1 : <font color='red'>{{blood_1}}</font>
  7957. * Blood 2 : <font color='red'>{{blood_2}}</font>
  7958. * <button type="button" data-ng-click="fight()">Fight</button>
  7959. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  7960. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  7961. * </div>
  7962. * </div>
  7963. *
  7964. * </file>
  7965. * </example>
  7966. */
  7967. function interval(fn, delay, count, invokeApply) {
  7968. var setInterval = $window.setInterval,
  7969. clearInterval = $window.clearInterval,
  7970. deferred = $q.defer(),
  7971. promise = deferred.promise,
  7972. iteration = 0,
  7973. skipApply = (isDefined(invokeApply) && !invokeApply);
  7974. count = isDefined(count) ? count : 0;
  7975. promise.then(null, null, fn);
  7976. promise.$$intervalId = setInterval(function tick() {
  7977. deferred.notify(iteration++);
  7978. if (count > 0 && iteration >= count) {
  7979. deferred.resolve(iteration);
  7980. clearInterval(promise.$$intervalId);
  7981. delete intervals[promise.$$intervalId];
  7982. }
  7983. if (!skipApply) $rootScope.$apply();
  7984. }, delay);
  7985. intervals[promise.$$intervalId] = deferred;
  7986. return promise;
  7987. }
  7988. /**
  7989. * @ngdoc method
  7990. * @name $interval#cancel
  7991. *
  7992. * @description
  7993. * Cancels a task associated with the `promise`.
  7994. *
  7995. * @param {promise} promise returned by the `$interval` function.
  7996. * @returns {boolean} Returns `true` if the task was successfully canceled.
  7997. */
  7998. interval.cancel = function(promise) {
  7999. if (promise && promise.$$intervalId in intervals) {
  8000. intervals[promise.$$intervalId].reject('canceled');
  8001. clearInterval(promise.$$intervalId);
  8002. delete intervals[promise.$$intervalId];
  8003. return true;
  8004. }
  8005. return false;
  8006. };
  8007. return interval;
  8008. }];
  8009. }
  8010. /**
  8011. * @ngdoc service
  8012. * @name $locale
  8013. *
  8014. * @description
  8015. * $locale service provides localization rules for various Angular components. As of right now the
  8016. * only public api is:
  8017. *
  8018. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8019. */
  8020. function $LocaleProvider(){
  8021. this.$get = function() {
  8022. return {
  8023. id: 'en-us',
  8024. NUMBER_FORMATS: {
  8025. DECIMAL_SEP: '.',
  8026. GROUP_SEP: ',',
  8027. PATTERNS: [
  8028. { // Decimal Pattern
  8029. minInt: 1,
  8030. minFrac: 0,
  8031. maxFrac: 3,
  8032. posPre: '',
  8033. posSuf: '',
  8034. negPre: '-',
  8035. negSuf: '',
  8036. gSize: 3,
  8037. lgSize: 3
  8038. },{ //Currency Pattern
  8039. minInt: 1,
  8040. minFrac: 2,
  8041. maxFrac: 2,
  8042. posPre: '\u00A4',
  8043. posSuf: '',
  8044. negPre: '(\u00A4',
  8045. negSuf: ')',
  8046. gSize: 3,
  8047. lgSize: 3
  8048. }
  8049. ],
  8050. CURRENCY_SYM: '$'
  8051. },
  8052. DATETIME_FORMATS: {
  8053. MONTH:
  8054. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8055. .split(','),
  8056. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8057. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8058. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8059. AMPMS: ['AM','PM'],
  8060. medium: 'MMM d, y h:mm:ss a',
  8061. short: 'M/d/yy h:mm a',
  8062. fullDate: 'EEEE, MMMM d, y',
  8063. longDate: 'MMMM d, y',
  8064. mediumDate: 'MMM d, y',
  8065. shortDate: 'M/d/yy',
  8066. mediumTime: 'h:mm:ss a',
  8067. shortTime: 'h:mm a'
  8068. },
  8069. pluralCat: function(num) {
  8070. if (num === 1) {
  8071. return 'one';
  8072. }
  8073. return 'other';
  8074. }
  8075. };
  8076. };
  8077. }
  8078. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8079. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8080. var $locationMinErr = minErr('$location');
  8081. /**
  8082. * Encode path using encodeUriSegment, ignoring forward slashes
  8083. *
  8084. * @param {string} path Path to encode
  8085. * @returns {string}
  8086. */
  8087. function encodePath(path) {
  8088. var segments = path.split('/'),
  8089. i = segments.length;
  8090. while (i--) {
  8091. segments[i] = encodeUriSegment(segments[i]);
  8092. }
  8093. return segments.join('/');
  8094. }
  8095. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8096. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8097. locationObj.$$protocol = parsedUrl.protocol;
  8098. locationObj.$$host = parsedUrl.hostname;
  8099. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8100. }
  8101. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8102. var prefixed = (relativeUrl.charAt(0) !== '/');
  8103. if (prefixed) {
  8104. relativeUrl = '/' + relativeUrl;
  8105. }
  8106. var match = urlResolve(relativeUrl, appBase);
  8107. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8108. match.pathname.substring(1) : match.pathname);
  8109. locationObj.$$search = parseKeyValue(match.search);
  8110. locationObj.$$hash = decodeURIComponent(match.hash);
  8111. // make sure path starts with '/';
  8112. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8113. locationObj.$$path = '/' + locationObj.$$path;
  8114. }
  8115. }
  8116. /**
  8117. *
  8118. * @param {string} begin
  8119. * @param {string} whole
  8120. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8121. * expected string.
  8122. */
  8123. function beginsWith(begin, whole) {
  8124. if (whole.indexOf(begin) === 0) {
  8125. return whole.substr(begin.length);
  8126. }
  8127. }
  8128. function stripHash(url) {
  8129. var index = url.indexOf('#');
  8130. return index == -1 ? url : url.substr(0, index);
  8131. }
  8132. function stripFile(url) {
  8133. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8134. }
  8135. /* return the server only (scheme://host:port) */
  8136. function serverBase(url) {
  8137. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8138. }
  8139. /**
  8140. * LocationHtml5Url represents an url
  8141. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8142. *
  8143. * @constructor
  8144. * @param {string} appBase application base URL
  8145. * @param {string} basePrefix url path prefix
  8146. */
  8147. function LocationHtml5Url(appBase, basePrefix) {
  8148. this.$$html5 = true;
  8149. basePrefix = basePrefix || '';
  8150. var appBaseNoFile = stripFile(appBase);
  8151. parseAbsoluteUrl(appBase, this, appBase);
  8152. /**
  8153. * Parse given html5 (regular) url string into properties
  8154. * @param {string} newAbsoluteUrl HTML5 url
  8155. * @private
  8156. */
  8157. this.$$parse = function(url) {
  8158. var pathUrl = beginsWith(appBaseNoFile, url);
  8159. if (!isString(pathUrl)) {
  8160. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8161. appBaseNoFile);
  8162. }
  8163. parseAppUrl(pathUrl, this, appBase);
  8164. if (!this.$$path) {
  8165. this.$$path = '/';
  8166. }
  8167. this.$$compose();
  8168. };
  8169. /**
  8170. * Compose url and update `absUrl` property
  8171. * @private
  8172. */
  8173. this.$$compose = function() {
  8174. var search = toKeyValue(this.$$search),
  8175. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8176. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8177. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8178. };
  8179. this.$$rewrite = function(url) {
  8180. var appUrl, prevAppUrl;
  8181. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8182. prevAppUrl = appUrl;
  8183. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8184. return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8185. } else {
  8186. return appBase + prevAppUrl;
  8187. }
  8188. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8189. return appBaseNoFile + appUrl;
  8190. } else if (appBaseNoFile == url + '/') {
  8191. return appBaseNoFile;
  8192. }
  8193. };
  8194. }
  8195. /**
  8196. * LocationHashbangUrl represents url
  8197. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8198. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8199. *
  8200. * @constructor
  8201. * @param {string} appBase application base URL
  8202. * @param {string} hashPrefix hashbang prefix
  8203. */
  8204. function LocationHashbangUrl(appBase, hashPrefix) {
  8205. var appBaseNoFile = stripFile(appBase);
  8206. parseAbsoluteUrl(appBase, this, appBase);
  8207. /**
  8208. * Parse given hashbang url into properties
  8209. * @param {string} url Hashbang url
  8210. * @private
  8211. */
  8212. this.$$parse = function(url) {
  8213. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8214. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8215. ? beginsWith(hashPrefix, withoutBaseUrl)
  8216. : (this.$$html5)
  8217. ? withoutBaseUrl
  8218. : '';
  8219. if (!isString(withoutHashUrl)) {
  8220. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8221. hashPrefix);
  8222. }
  8223. parseAppUrl(withoutHashUrl, this, appBase);
  8224. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8225. this.$$compose();
  8226. /*
  8227. * In Windows, on an anchor node on documents loaded from
  8228. * the filesystem, the browser will return a pathname
  8229. * prefixed with the drive name ('/C:/path') when a
  8230. * pathname without a drive is set:
  8231. * * a.setAttribute('href', '/foo')
  8232. * * a.pathname === '/C:/foo' //true
  8233. *
  8234. * Inside of Angular, we're always using pathnames that
  8235. * do not include drive names for routing.
  8236. */
  8237. function removeWindowsDriveName (path, url, base) {
  8238. /*
  8239. Matches paths for file protocol on windows,
  8240. such as /C:/foo/bar, and captures only /foo/bar.
  8241. */
  8242. var windowsFilePathExp = /^\/?.*?:(\/.*)/;
  8243. var firstPathSegmentMatch;
  8244. //Get the relative path from the input URL.
  8245. if (url.indexOf(base) === 0) {
  8246. url = url.replace(base, '');
  8247. }
  8248. /*
  8249. * The input URL intentionally contains a
  8250. * first path segment that ends with a colon.
  8251. */
  8252. if (windowsFilePathExp.exec(url)) {
  8253. return path;
  8254. }
  8255. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8256. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8257. }
  8258. };
  8259. /**
  8260. * Compose hashbang url and update `absUrl` property
  8261. * @private
  8262. */
  8263. this.$$compose = function() {
  8264. var search = toKeyValue(this.$$search),
  8265. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8266. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8267. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8268. };
  8269. this.$$rewrite = function(url) {
  8270. if(stripHash(appBase) == stripHash(url)) {
  8271. return url;
  8272. }
  8273. };
  8274. }
  8275. /**
  8276. * LocationHashbangUrl represents url
  8277. * This object is exposed as $location service when html5 history api is enabled but the browser
  8278. * does not support it.
  8279. *
  8280. * @constructor
  8281. * @param {string} appBase application base URL
  8282. * @param {string} hashPrefix hashbang prefix
  8283. */
  8284. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8285. this.$$html5 = true;
  8286. LocationHashbangUrl.apply(this, arguments);
  8287. var appBaseNoFile = stripFile(appBase);
  8288. this.$$rewrite = function(url) {
  8289. var appUrl;
  8290. if ( appBase == stripHash(url) ) {
  8291. return url;
  8292. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8293. return appBase + hashPrefix + appUrl;
  8294. } else if ( appBaseNoFile === url + '/') {
  8295. return appBaseNoFile;
  8296. }
  8297. };
  8298. }
  8299. LocationHashbangInHtml5Url.prototype =
  8300. LocationHashbangUrl.prototype =
  8301. LocationHtml5Url.prototype = {
  8302. /**
  8303. * Are we in html5 mode?
  8304. * @private
  8305. */
  8306. $$html5: false,
  8307. /**
  8308. * Has any change been replacing ?
  8309. * @private
  8310. */
  8311. $$replace: false,
  8312. /**
  8313. * @ngdoc method
  8314. * @name $location#absUrl
  8315. *
  8316. * @description
  8317. * This method is getter only.
  8318. *
  8319. * Return full url representation with all segments encoded according to rules specified in
  8320. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8321. *
  8322. * @return {string} full url
  8323. */
  8324. absUrl: locationGetter('$$absUrl'),
  8325. /**
  8326. * @ngdoc method
  8327. * @name $location#url
  8328. *
  8329. * @description
  8330. * This method is getter / setter.
  8331. *
  8332. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8333. *
  8334. * Change path, search and hash, when called with parameter and return `$location`.
  8335. *
  8336. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8337. * @param {string=} replace The path that will be changed
  8338. * @return {string} url
  8339. */
  8340. url: function(url, replace) {
  8341. if (isUndefined(url))
  8342. return this.$$url;
  8343. var match = PATH_MATCH.exec(url);
  8344. if (match[1]) this.path(decodeURIComponent(match[1]));
  8345. if (match[2] || match[1]) this.search(match[3] || '');
  8346. this.hash(match[5] || '', replace);
  8347. return this;
  8348. },
  8349. /**
  8350. * @ngdoc method
  8351. * @name $location#protocol
  8352. *
  8353. * @description
  8354. * This method is getter only.
  8355. *
  8356. * Return protocol of current url.
  8357. *
  8358. * @return {string} protocol of current url
  8359. */
  8360. protocol: locationGetter('$$protocol'),
  8361. /**
  8362. * @ngdoc method
  8363. * @name $location#host
  8364. *
  8365. * @description
  8366. * This method is getter only.
  8367. *
  8368. * Return host of current url.
  8369. *
  8370. * @return {string} host of current url.
  8371. */
  8372. host: locationGetter('$$host'),
  8373. /**
  8374. * @ngdoc method
  8375. * @name $location#port
  8376. *
  8377. * @description
  8378. * This method is getter only.
  8379. *
  8380. * Return port of current url.
  8381. *
  8382. * @return {Number} port
  8383. */
  8384. port: locationGetter('$$port'),
  8385. /**
  8386. * @ngdoc method
  8387. * @name $location#path
  8388. *
  8389. * @description
  8390. * This method is getter / setter.
  8391. *
  8392. * Return path of current url when called without any parameter.
  8393. *
  8394. * Change path when called with parameter and return `$location`.
  8395. *
  8396. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8397. * if it is missing.
  8398. *
  8399. * @param {string=} path New path
  8400. * @return {string} path
  8401. */
  8402. path: locationGetterSetter('$$path', function(path) {
  8403. return path.charAt(0) == '/' ? path : '/' + path;
  8404. }),
  8405. /**
  8406. * @ngdoc method
  8407. * @name $location#search
  8408. *
  8409. * @description
  8410. * This method is getter / setter.
  8411. *
  8412. * Return search part (as object) of current url when called without any parameter.
  8413. *
  8414. * Change search part when called with parameter and return `$location`.
  8415. *
  8416. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8417. * hash object. Hash object may contain an array of values, which will be decoded as duplicates in
  8418. * the url.
  8419. *
  8420. * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will override only a
  8421. * single search parameter. If `paramValue` is an array, it will set the parameter as a
  8422. * comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
  8423. *
  8424. * @return {string} search
  8425. */
  8426. search: function(search, paramValue) {
  8427. switch (arguments.length) {
  8428. case 0:
  8429. return this.$$search;
  8430. case 1:
  8431. if (isString(search)) {
  8432. this.$$search = parseKeyValue(search);
  8433. } else if (isObject(search)) {
  8434. this.$$search = search;
  8435. } else {
  8436. throw $locationMinErr('isrcharg',
  8437. 'The first argument of the `$location#search()` call must be a string or an object.');
  8438. }
  8439. break;
  8440. default:
  8441. if (isUndefined(paramValue) || paramValue === null) {
  8442. delete this.$$search[search];
  8443. } else {
  8444. this.$$search[search] = paramValue;
  8445. }
  8446. }
  8447. this.$$compose();
  8448. return this;
  8449. },
  8450. /**
  8451. * @ngdoc method
  8452. * @name $location#hash
  8453. *
  8454. * @description
  8455. * This method is getter / setter.
  8456. *
  8457. * Return hash fragment when called without any parameter.
  8458. *
  8459. * Change hash fragment when called with parameter and return `$location`.
  8460. *
  8461. * @param {string=} hash New hash fragment
  8462. * @return {string} hash
  8463. */
  8464. hash: locationGetterSetter('$$hash', identity),
  8465. /**
  8466. * @ngdoc method
  8467. * @name $location#replace
  8468. *
  8469. * @description
  8470. * If called, all changes to $location during current `$digest` will be replacing current history
  8471. * record, instead of adding new one.
  8472. */
  8473. replace: function() {
  8474. this.$$replace = true;
  8475. return this;
  8476. }
  8477. };
  8478. function locationGetter(property) {
  8479. return function() {
  8480. return this[property];
  8481. };
  8482. }
  8483. function locationGetterSetter(property, preprocess) {
  8484. return function(value) {
  8485. if (isUndefined(value))
  8486. return this[property];
  8487. this[property] = preprocess(value);
  8488. this.$$compose();
  8489. return this;
  8490. };
  8491. }
  8492. /**
  8493. * @ngdoc service
  8494. * @name $location
  8495. *
  8496. * @requires $rootElement
  8497. *
  8498. * @description
  8499. * The $location service parses the URL in the browser address bar (based on the
  8500. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8501. * available to your application. Changes to the URL in the address bar are reflected into
  8502. * $location service and changes to $location are reflected into the browser address bar.
  8503. *
  8504. * **The $location service:**
  8505. *
  8506. * - Exposes the current URL in the browser address bar, so you can
  8507. * - Watch and observe the URL.
  8508. * - Change the URL.
  8509. * - Synchronizes the URL with the browser when the user
  8510. * - Changes the address bar.
  8511. * - Clicks the back or forward button (or clicks a History link).
  8512. * - Clicks on a link.
  8513. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8514. *
  8515. * For more information see {@link guide/$location Developer Guide: Using $location}
  8516. */
  8517. /**
  8518. * @ngdoc provider
  8519. * @name $locationProvider
  8520. * @description
  8521. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8522. */
  8523. function $LocationProvider(){
  8524. var hashPrefix = '',
  8525. html5Mode = false;
  8526. /**
  8527. * @ngdoc property
  8528. * @name $locationProvider#hashPrefix
  8529. * @description
  8530. * @param {string=} prefix Prefix for hash part (containing path and search)
  8531. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8532. */
  8533. this.hashPrefix = function(prefix) {
  8534. if (isDefined(prefix)) {
  8535. hashPrefix = prefix;
  8536. return this;
  8537. } else {
  8538. return hashPrefix;
  8539. }
  8540. };
  8541. /**
  8542. * @ngdoc property
  8543. * @name $locationProvider#html5Mode
  8544. * @description
  8545. * @param {boolean=} mode Use HTML5 strategy if available.
  8546. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8547. */
  8548. this.html5Mode = function(mode) {
  8549. if (isDefined(mode)) {
  8550. html5Mode = mode;
  8551. return this;
  8552. } else {
  8553. return html5Mode;
  8554. }
  8555. };
  8556. /**
  8557. * @ngdoc event
  8558. * @name $location#$locationChangeStart
  8559. * @eventType broadcast on root scope
  8560. * @description
  8561. * Broadcasted before a URL will change. This change can be prevented by calling
  8562. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8563. * details about event object. Upon successful change
  8564. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8565. *
  8566. * @param {Object} angularEvent Synthetic event object.
  8567. * @param {string} newUrl New URL
  8568. * @param {string=} oldUrl URL that was before it was changed.
  8569. */
  8570. /**
  8571. * @ngdoc event
  8572. * @name $location#$locationChangeSuccess
  8573. * @eventType broadcast on root scope
  8574. * @description
  8575. * Broadcasted after a URL was changed.
  8576. *
  8577. * @param {Object} angularEvent Synthetic event object.
  8578. * @param {string} newUrl New URL
  8579. * @param {string=} oldUrl URL that was before it was changed.
  8580. */
  8581. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8582. function( $rootScope, $browser, $sniffer, $rootElement) {
  8583. var $location,
  8584. LocationMode,
  8585. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8586. initialUrl = $browser.url(),
  8587. appBase;
  8588. if (html5Mode) {
  8589. appBase = serverBase(initialUrl) + (baseHref || '/');
  8590. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8591. } else {
  8592. appBase = stripHash(initialUrl);
  8593. LocationMode = LocationHashbangUrl;
  8594. }
  8595. $location = new LocationMode(appBase, '#' + hashPrefix);
  8596. $location.$$parse($location.$$rewrite(initialUrl));
  8597. $rootElement.on('click', function(event) {
  8598. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8599. // currently we open nice url link and redirect then
  8600. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8601. var elm = jqLite(event.target);
  8602. // traverse the DOM up to find first A tag
  8603. while (lowercase(elm[0].nodeName) !== 'a') {
  8604. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8605. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8606. }
  8607. var absHref = elm.prop('href');
  8608. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8609. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8610. // an animation.
  8611. absHref = urlResolve(absHref.animVal).href;
  8612. }
  8613. var rewrittenUrl = $location.$$rewrite(absHref);
  8614. if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
  8615. event.preventDefault();
  8616. if (rewrittenUrl != $browser.url()) {
  8617. // update location manually
  8618. $location.$$parse(rewrittenUrl);
  8619. $rootScope.$apply();
  8620. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8621. window.angular['ff-684208-preventDefault'] = true;
  8622. }
  8623. }
  8624. });
  8625. // rewrite hashbang url <> html5 url
  8626. if ($location.absUrl() != initialUrl) {
  8627. $browser.url($location.absUrl(), true);
  8628. }
  8629. // update $location when $browser url changes
  8630. $browser.onUrlChange(function(newUrl) {
  8631. if ($location.absUrl() != newUrl) {
  8632. $rootScope.$evalAsync(function() {
  8633. var oldUrl = $location.absUrl();
  8634. $location.$$parse(newUrl);
  8635. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8636. oldUrl).defaultPrevented) {
  8637. $location.$$parse(oldUrl);
  8638. $browser.url(oldUrl);
  8639. } else {
  8640. afterLocationChange(oldUrl);
  8641. }
  8642. });
  8643. if (!$rootScope.$$phase) $rootScope.$digest();
  8644. }
  8645. });
  8646. // update browser
  8647. var changeCounter = 0;
  8648. $rootScope.$watch(function $locationWatch() {
  8649. var oldUrl = $browser.url();
  8650. var currentReplace = $location.$$replace;
  8651. if (!changeCounter || oldUrl != $location.absUrl()) {
  8652. changeCounter++;
  8653. $rootScope.$evalAsync(function() {
  8654. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8655. defaultPrevented) {
  8656. $location.$$parse(oldUrl);
  8657. } else {
  8658. $browser.url($location.absUrl(), currentReplace);
  8659. afterLocationChange(oldUrl);
  8660. }
  8661. });
  8662. }
  8663. $location.$$replace = false;
  8664. return changeCounter;
  8665. });
  8666. return $location;
  8667. function afterLocationChange(oldUrl) {
  8668. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8669. }
  8670. }];
  8671. }
  8672. /**
  8673. * @ngdoc service
  8674. * @name $log
  8675. * @requires $window
  8676. *
  8677. * @description
  8678. * Simple service for logging. Default implementation safely writes the message
  8679. * into the browser's console (if present).
  8680. *
  8681. * The main purpose of this service is to simplify debugging and troubleshooting.
  8682. *
  8683. * The default is to log `debug` messages. You can use
  8684. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8685. *
  8686. * @example
  8687. <example>
  8688. <file name="script.js">
  8689. function LogCtrl($scope, $log) {
  8690. $scope.$log = $log;
  8691. $scope.message = 'Hello World!';
  8692. }
  8693. </file>
  8694. <file name="index.html">
  8695. <div ng-controller="LogCtrl">
  8696. <p>Reload this page with open console, enter text and hit the log button...</p>
  8697. Message:
  8698. <input type="text" ng-model="message"/>
  8699. <button ng-click="$log.log(message)">log</button>
  8700. <button ng-click="$log.warn(message)">warn</button>
  8701. <button ng-click="$log.info(message)">info</button>
  8702. <button ng-click="$log.error(message)">error</button>
  8703. </div>
  8704. </file>
  8705. </example>
  8706. */
  8707. /**
  8708. * @ngdoc provider
  8709. * @name $logProvider
  8710. * @description
  8711. * Use the `$logProvider` to configure how the application logs messages
  8712. */
  8713. function $LogProvider(){
  8714. var debug = true,
  8715. self = this;
  8716. /**
  8717. * @ngdoc property
  8718. * @name $logProvider#debugEnabled
  8719. * @description
  8720. * @param {boolean=} flag enable or disable debug level messages
  8721. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8722. */
  8723. this.debugEnabled = function(flag) {
  8724. if (isDefined(flag)) {
  8725. debug = flag;
  8726. return this;
  8727. } else {
  8728. return debug;
  8729. }
  8730. };
  8731. this.$get = ['$window', function($window){
  8732. return {
  8733. /**
  8734. * @ngdoc method
  8735. * @name $log#log
  8736. *
  8737. * @description
  8738. * Write a log message
  8739. */
  8740. log: consoleLog('log'),
  8741. /**
  8742. * @ngdoc method
  8743. * @name $log#info
  8744. *
  8745. * @description
  8746. * Write an information message
  8747. */
  8748. info: consoleLog('info'),
  8749. /**
  8750. * @ngdoc method
  8751. * @name $log#warn
  8752. *
  8753. * @description
  8754. * Write a warning message
  8755. */
  8756. warn: consoleLog('warn'),
  8757. /**
  8758. * @ngdoc method
  8759. * @name $log#error
  8760. *
  8761. * @description
  8762. * Write an error message
  8763. */
  8764. error: consoleLog('error'),
  8765. /**
  8766. * @ngdoc method
  8767. * @name $log#debug
  8768. *
  8769. * @description
  8770. * Write a debug message
  8771. */
  8772. debug: (function () {
  8773. var fn = consoleLog('debug');
  8774. return function() {
  8775. if (debug) {
  8776. fn.apply(self, arguments);
  8777. }
  8778. };
  8779. }())
  8780. };
  8781. function formatError(arg) {
  8782. if (arg instanceof Error) {
  8783. if (arg.stack) {
  8784. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  8785. ? 'Error: ' + arg.message + '\n' + arg.stack
  8786. : arg.stack;
  8787. } else if (arg.sourceURL) {
  8788. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  8789. }
  8790. }
  8791. return arg;
  8792. }
  8793. function consoleLog(type) {
  8794. var console = $window.console || {},
  8795. logFn = console[type] || console.log || noop,
  8796. hasApply = false;
  8797. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  8798. // The reason behind this is that console.log has type "object" in IE8...
  8799. try {
  8800. hasApply = !!logFn.apply;
  8801. } catch (e) {}
  8802. if (hasApply) {
  8803. return function() {
  8804. var args = [];
  8805. forEach(arguments, function(arg) {
  8806. args.push(formatError(arg));
  8807. });
  8808. return logFn.apply(console, args);
  8809. };
  8810. }
  8811. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  8812. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  8813. return function(arg1, arg2) {
  8814. logFn(arg1, arg2 == null ? '' : arg2);
  8815. };
  8816. }
  8817. }];
  8818. }
  8819. var $parseMinErr = minErr('$parse');
  8820. var promiseWarningCache = {};
  8821. var promiseWarning;
  8822. // Sandboxing Angular Expressions
  8823. // ------------------------------
  8824. // Angular expressions are generally considered safe because these expressions only have direct
  8825. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  8826. // obtaining a reference to native JS functions such as the Function constructor.
  8827. //
  8828. // As an example, consider the following Angular expression:
  8829. //
  8830. // {}.toString.constructor(alert("evil JS code"))
  8831. //
  8832. // We want to prevent this type of access. For the sake of performance, during the lexing phase we
  8833. // disallow any "dotted" access to any member named "constructor".
  8834. //
  8835. // For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
  8836. // while evaluating the expression, which is a stronger but more expensive test. Since reflective
  8837. // calls are expensive anyway, this is not such a big deal compared to static dereferencing.
  8838. //
  8839. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  8840. // against the expression language, but not to prevent exploits that were enabled by exposing
  8841. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  8842. // practice and therefore we are not even trying to protect against interaction with an object
  8843. // explicitly exposed in this way.
  8844. //
  8845. // A developer could foil the name check by aliasing the Function constructor under a different
  8846. // name on the scope.
  8847. //
  8848. // In general, it is not possible to access a Window object from an angular expression unless a
  8849. // window or some DOM object that has a reference to window is published onto a Scope.
  8850. function ensureSafeMemberName(name, fullExpression) {
  8851. if (name === "constructor") {
  8852. throw $parseMinErr('isecfld',
  8853. 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
  8854. fullExpression);
  8855. }
  8856. return name;
  8857. }
  8858. function ensureSafeObject(obj, fullExpression) {
  8859. // nifty check if obj is Function that is fast and works across iframes and other contexts
  8860. if (obj) {
  8861. if (obj.constructor === obj) {
  8862. throw $parseMinErr('isecfn',
  8863. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  8864. fullExpression);
  8865. } else if (// isWindow(obj)
  8866. obj.document && obj.location && obj.alert && obj.setInterval) {
  8867. throw $parseMinErr('isecwindow',
  8868. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  8869. fullExpression);
  8870. } else if (// isElement(obj)
  8871. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  8872. throw $parseMinErr('isecdom',
  8873. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  8874. fullExpression);
  8875. }
  8876. }
  8877. return obj;
  8878. }
  8879. var OPERATORS = {
  8880. /* jshint bitwise : false */
  8881. 'null':function(){return null;},
  8882. 'true':function(){return true;},
  8883. 'false':function(){return false;},
  8884. undefined:noop,
  8885. '+':function(self, locals, a,b){
  8886. a=a(self, locals); b=b(self, locals);
  8887. if (isDefined(a)) {
  8888. if (isDefined(b)) {
  8889. return a + b;
  8890. }
  8891. return a;
  8892. }
  8893. return isDefined(b)?b:undefined;},
  8894. '-':function(self, locals, a,b){
  8895. a=a(self, locals); b=b(self, locals);
  8896. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  8897. },
  8898. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  8899. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  8900. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  8901. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  8902. '=':noop,
  8903. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  8904. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  8905. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  8906. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  8907. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  8908. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  8909. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  8910. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  8911. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  8912. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  8913. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  8914. // '|':function(self, locals, a,b){return a|b;},
  8915. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  8916. '!':function(self, locals, a){return !a(self, locals);}
  8917. };
  8918. /* jshint bitwise: true */
  8919. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  8920. /////////////////////////////////////////
  8921. /**
  8922. * @constructor
  8923. */
  8924. var Lexer = function (options) {
  8925. this.options = options;
  8926. };
  8927. Lexer.prototype = {
  8928. constructor: Lexer,
  8929. lex: function (text) {
  8930. this.text = text;
  8931. this.index = 0;
  8932. this.ch = undefined;
  8933. this.lastCh = ':'; // can start regexp
  8934. this.tokens = [];
  8935. var token;
  8936. var json = [];
  8937. while (this.index < this.text.length) {
  8938. this.ch = this.text.charAt(this.index);
  8939. if (this.is('"\'')) {
  8940. this.readString(this.ch);
  8941. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  8942. this.readNumber();
  8943. } else if (this.isIdent(this.ch)) {
  8944. this.readIdent();
  8945. // identifiers can only be if the preceding char was a { or ,
  8946. if (this.was('{,') && json[0] === '{' &&
  8947. (token = this.tokens[this.tokens.length - 1])) {
  8948. token.json = token.text.indexOf('.') === -1;
  8949. }
  8950. } else if (this.is('(){}[].,;:?')) {
  8951. this.tokens.push({
  8952. index: this.index,
  8953. text: this.ch,
  8954. json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
  8955. });
  8956. if (this.is('{[')) json.unshift(this.ch);
  8957. if (this.is('}]')) json.shift();
  8958. this.index++;
  8959. } else if (this.isWhitespace(this.ch)) {
  8960. this.index++;
  8961. continue;
  8962. } else {
  8963. var ch2 = this.ch + this.peek();
  8964. var ch3 = ch2 + this.peek(2);
  8965. var fn = OPERATORS[this.ch];
  8966. var fn2 = OPERATORS[ch2];
  8967. var fn3 = OPERATORS[ch3];
  8968. if (fn3) {
  8969. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  8970. this.index += 3;
  8971. } else if (fn2) {
  8972. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  8973. this.index += 2;
  8974. } else if (fn) {
  8975. this.tokens.push({
  8976. index: this.index,
  8977. text: this.ch,
  8978. fn: fn,
  8979. json: (this.was('[,:') && this.is('+-'))
  8980. });
  8981. this.index += 1;
  8982. } else {
  8983. this.throwError('Unexpected next character ', this.index, this.index + 1);
  8984. }
  8985. }
  8986. this.lastCh = this.ch;
  8987. }
  8988. return this.tokens;
  8989. },
  8990. is: function(chars) {
  8991. return chars.indexOf(this.ch) !== -1;
  8992. },
  8993. was: function(chars) {
  8994. return chars.indexOf(this.lastCh) !== -1;
  8995. },
  8996. peek: function(i) {
  8997. var num = i || 1;
  8998. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  8999. },
  9000. isNumber: function(ch) {
  9001. return ('0' <= ch && ch <= '9');
  9002. },
  9003. isWhitespace: function(ch) {
  9004. // IE treats non-breaking space as \u00A0
  9005. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9006. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9007. },
  9008. isIdent: function(ch) {
  9009. return ('a' <= ch && ch <= 'z' ||
  9010. 'A' <= ch && ch <= 'Z' ||
  9011. '_' === ch || ch === '$');
  9012. },
  9013. isExpOperator: function(ch) {
  9014. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9015. },
  9016. throwError: function(error, start, end) {
  9017. end = end || this.index;
  9018. var colStr = (isDefined(start)
  9019. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9020. : ' ' + end);
  9021. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9022. error, colStr, this.text);
  9023. },
  9024. readNumber: function() {
  9025. var number = '';
  9026. var start = this.index;
  9027. while (this.index < this.text.length) {
  9028. var ch = lowercase(this.text.charAt(this.index));
  9029. if (ch == '.' || this.isNumber(ch)) {
  9030. number += ch;
  9031. } else {
  9032. var peekCh = this.peek();
  9033. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9034. number += ch;
  9035. } else if (this.isExpOperator(ch) &&
  9036. peekCh && this.isNumber(peekCh) &&
  9037. number.charAt(number.length - 1) == 'e') {
  9038. number += ch;
  9039. } else if (this.isExpOperator(ch) &&
  9040. (!peekCh || !this.isNumber(peekCh)) &&
  9041. number.charAt(number.length - 1) == 'e') {
  9042. this.throwError('Invalid exponent');
  9043. } else {
  9044. break;
  9045. }
  9046. }
  9047. this.index++;
  9048. }
  9049. number = 1 * number;
  9050. this.tokens.push({
  9051. index: start,
  9052. text: number,
  9053. json: true,
  9054. fn: function() { return number; }
  9055. });
  9056. },
  9057. readIdent: function() {
  9058. var parser = this;
  9059. var ident = '';
  9060. var start = this.index;
  9061. var lastDot, peekIndex, methodName, ch;
  9062. while (this.index < this.text.length) {
  9063. ch = this.text.charAt(this.index);
  9064. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9065. if (ch === '.') lastDot = this.index;
  9066. ident += ch;
  9067. } else {
  9068. break;
  9069. }
  9070. this.index++;
  9071. }
  9072. //check if this is not a method invocation and if it is back out to last dot
  9073. if (lastDot) {
  9074. peekIndex = this.index;
  9075. while (peekIndex < this.text.length) {
  9076. ch = this.text.charAt(peekIndex);
  9077. if (ch === '(') {
  9078. methodName = ident.substr(lastDot - start + 1);
  9079. ident = ident.substr(0, lastDot - start);
  9080. this.index = peekIndex;
  9081. break;
  9082. }
  9083. if (this.isWhitespace(ch)) {
  9084. peekIndex++;
  9085. } else {
  9086. break;
  9087. }
  9088. }
  9089. }
  9090. var token = {
  9091. index: start,
  9092. text: ident
  9093. };
  9094. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9095. if (OPERATORS.hasOwnProperty(ident)) {
  9096. token.fn = OPERATORS[ident];
  9097. token.json = OPERATORS[ident];
  9098. } else {
  9099. var getter = getterFn(ident, this.options, this.text);
  9100. token.fn = extend(function(self, locals) {
  9101. return (getter(self, locals));
  9102. }, {
  9103. assign: function(self, value) {
  9104. return setter(self, ident, value, parser.text, parser.options);
  9105. }
  9106. });
  9107. }
  9108. this.tokens.push(token);
  9109. if (methodName) {
  9110. this.tokens.push({
  9111. index:lastDot,
  9112. text: '.',
  9113. json: false
  9114. });
  9115. this.tokens.push({
  9116. index: lastDot + 1,
  9117. text: methodName,
  9118. json: false
  9119. });
  9120. }
  9121. },
  9122. readString: function(quote) {
  9123. var start = this.index;
  9124. this.index++;
  9125. var string = '';
  9126. var rawString = quote;
  9127. var escape = false;
  9128. while (this.index < this.text.length) {
  9129. var ch = this.text.charAt(this.index);
  9130. rawString += ch;
  9131. if (escape) {
  9132. if (ch === 'u') {
  9133. var hex = this.text.substring(this.index + 1, this.index + 5);
  9134. if (!hex.match(/[\da-f]{4}/i))
  9135. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9136. this.index += 4;
  9137. string += String.fromCharCode(parseInt(hex, 16));
  9138. } else {
  9139. var rep = ESCAPE[ch];
  9140. if (rep) {
  9141. string += rep;
  9142. } else {
  9143. string += ch;
  9144. }
  9145. }
  9146. escape = false;
  9147. } else if (ch === '\\') {
  9148. escape = true;
  9149. } else if (ch === quote) {
  9150. this.index++;
  9151. this.tokens.push({
  9152. index: start,
  9153. text: rawString,
  9154. string: string,
  9155. json: true,
  9156. fn: function() { return string; }
  9157. });
  9158. return;
  9159. } else {
  9160. string += ch;
  9161. }
  9162. this.index++;
  9163. }
  9164. this.throwError('Unterminated quote', start);
  9165. }
  9166. };
  9167. /**
  9168. * @constructor
  9169. */
  9170. var Parser = function (lexer, $filter, options) {
  9171. this.lexer = lexer;
  9172. this.$filter = $filter;
  9173. this.options = options;
  9174. };
  9175. Parser.ZERO = extend(function () {
  9176. return 0;
  9177. }, {
  9178. constant: true
  9179. });
  9180. Parser.prototype = {
  9181. constructor: Parser,
  9182. parse: function (text, json) {
  9183. this.text = text;
  9184. //TODO(i): strip all the obsolte json stuff from this file
  9185. this.json = json;
  9186. this.tokens = this.lexer.lex(text);
  9187. if (json) {
  9188. // The extra level of aliasing is here, just in case the lexer misses something, so that
  9189. // we prevent any accidental execution in JSON.
  9190. this.assignment = this.logicalOR;
  9191. this.functionCall =
  9192. this.fieldAccess =
  9193. this.objectIndex =
  9194. this.filterChain = function() {
  9195. this.throwError('is not valid json', {text: text, index: 0});
  9196. };
  9197. }
  9198. var value = json ? this.primary() : this.statements();
  9199. if (this.tokens.length !== 0) {
  9200. this.throwError('is an unexpected token', this.tokens[0]);
  9201. }
  9202. value.literal = !!value.literal;
  9203. value.constant = !!value.constant;
  9204. return value;
  9205. },
  9206. primary: function () {
  9207. var primary;
  9208. if (this.expect('(')) {
  9209. primary = this.filterChain();
  9210. this.consume(')');
  9211. } else if (this.expect('[')) {
  9212. primary = this.arrayDeclaration();
  9213. } else if (this.expect('{')) {
  9214. primary = this.object();
  9215. } else {
  9216. var token = this.expect();
  9217. primary = token.fn;
  9218. if (!primary) {
  9219. this.throwError('not a primary expression', token);
  9220. }
  9221. if (token.json) {
  9222. primary.constant = true;
  9223. primary.literal = true;
  9224. }
  9225. }
  9226. var next, context;
  9227. while ((next = this.expect('(', '[', '.'))) {
  9228. if (next.text === '(') {
  9229. primary = this.functionCall(primary, context);
  9230. context = null;
  9231. } else if (next.text === '[') {
  9232. context = primary;
  9233. primary = this.objectIndex(primary);
  9234. } else if (next.text === '.') {
  9235. context = primary;
  9236. primary = this.fieldAccess(primary);
  9237. } else {
  9238. this.throwError('IMPOSSIBLE');
  9239. }
  9240. }
  9241. return primary;
  9242. },
  9243. throwError: function(msg, token) {
  9244. throw $parseMinErr('syntax',
  9245. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9246. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9247. },
  9248. peekToken: function() {
  9249. if (this.tokens.length === 0)
  9250. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9251. return this.tokens[0];
  9252. },
  9253. peek: function(e1, e2, e3, e4) {
  9254. if (this.tokens.length > 0) {
  9255. var token = this.tokens[0];
  9256. var t = token.text;
  9257. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9258. (!e1 && !e2 && !e3 && !e4)) {
  9259. return token;
  9260. }
  9261. }
  9262. return false;
  9263. },
  9264. expect: function(e1, e2, e3, e4){
  9265. var token = this.peek(e1, e2, e3, e4);
  9266. if (token) {
  9267. if (this.json && !token.json) {
  9268. this.throwError('is not valid json', token);
  9269. }
  9270. this.tokens.shift();
  9271. return token;
  9272. }
  9273. return false;
  9274. },
  9275. consume: function(e1){
  9276. if (!this.expect(e1)) {
  9277. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9278. }
  9279. },
  9280. unaryFn: function(fn, right) {
  9281. return extend(function(self, locals) {
  9282. return fn(self, locals, right);
  9283. }, {
  9284. constant:right.constant
  9285. });
  9286. },
  9287. ternaryFn: function(left, middle, right){
  9288. return extend(function(self, locals){
  9289. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9290. }, {
  9291. constant: left.constant && middle.constant && right.constant
  9292. });
  9293. },
  9294. binaryFn: function(left, fn, right) {
  9295. return extend(function(self, locals) {
  9296. return fn(self, locals, left, right);
  9297. }, {
  9298. constant:left.constant && right.constant
  9299. });
  9300. },
  9301. statements: function() {
  9302. var statements = [];
  9303. while (true) {
  9304. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9305. statements.push(this.filterChain());
  9306. if (!this.expect(';')) {
  9307. // optimize for the common case where there is only one statement.
  9308. // TODO(size): maybe we should not support multiple statements?
  9309. return (statements.length === 1)
  9310. ? statements[0]
  9311. : function(self, locals) {
  9312. var value;
  9313. for (var i = 0; i < statements.length; i++) {
  9314. var statement = statements[i];
  9315. if (statement) {
  9316. value = statement(self, locals);
  9317. }
  9318. }
  9319. return value;
  9320. };
  9321. }
  9322. }
  9323. },
  9324. filterChain: function() {
  9325. var left = this.expression();
  9326. var token;
  9327. while (true) {
  9328. if ((token = this.expect('|'))) {
  9329. left = this.binaryFn(left, token.fn, this.filter());
  9330. } else {
  9331. return left;
  9332. }
  9333. }
  9334. },
  9335. filter: function() {
  9336. var token = this.expect();
  9337. var fn = this.$filter(token.text);
  9338. var argsFn = [];
  9339. while (true) {
  9340. if ((token = this.expect(':'))) {
  9341. argsFn.push(this.expression());
  9342. } else {
  9343. var fnInvoke = function(self, locals, input) {
  9344. var args = [input];
  9345. for (var i = 0; i < argsFn.length; i++) {
  9346. args.push(argsFn[i](self, locals));
  9347. }
  9348. return fn.apply(self, args);
  9349. };
  9350. return function() {
  9351. return fnInvoke;
  9352. };
  9353. }
  9354. }
  9355. },
  9356. expression: function() {
  9357. return this.assignment();
  9358. },
  9359. assignment: function() {
  9360. var left = this.ternary();
  9361. var right;
  9362. var token;
  9363. if ((token = this.expect('='))) {
  9364. if (!left.assign) {
  9365. this.throwError('implies assignment but [' +
  9366. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9367. }
  9368. right = this.ternary();
  9369. return function(scope, locals) {
  9370. return left.assign(scope, right(scope, locals), locals);
  9371. };
  9372. }
  9373. return left;
  9374. },
  9375. ternary: function() {
  9376. var left = this.logicalOR();
  9377. var middle;
  9378. var token;
  9379. if ((token = this.expect('?'))) {
  9380. middle = this.ternary();
  9381. if ((token = this.expect(':'))) {
  9382. return this.ternaryFn(left, middle, this.ternary());
  9383. } else {
  9384. this.throwError('expected :', token);
  9385. }
  9386. } else {
  9387. return left;
  9388. }
  9389. },
  9390. logicalOR: function() {
  9391. var left = this.logicalAND();
  9392. var token;
  9393. while (true) {
  9394. if ((token = this.expect('||'))) {
  9395. left = this.binaryFn(left, token.fn, this.logicalAND());
  9396. } else {
  9397. return left;
  9398. }
  9399. }
  9400. },
  9401. logicalAND: function() {
  9402. var left = this.equality();
  9403. var token;
  9404. if ((token = this.expect('&&'))) {
  9405. left = this.binaryFn(left, token.fn, this.logicalAND());
  9406. }
  9407. return left;
  9408. },
  9409. equality: function() {
  9410. var left = this.relational();
  9411. var token;
  9412. if ((token = this.expect('==','!=','===','!=='))) {
  9413. left = this.binaryFn(left, token.fn, this.equality());
  9414. }
  9415. return left;
  9416. },
  9417. relational: function() {
  9418. var left = this.additive();
  9419. var token;
  9420. if ((token = this.expect('<', '>', '<=', '>='))) {
  9421. left = this.binaryFn(left, token.fn, this.relational());
  9422. }
  9423. return left;
  9424. },
  9425. additive: function() {
  9426. var left = this.multiplicative();
  9427. var token;
  9428. while ((token = this.expect('+','-'))) {
  9429. left = this.binaryFn(left, token.fn, this.multiplicative());
  9430. }
  9431. return left;
  9432. },
  9433. multiplicative: function() {
  9434. var left = this.unary();
  9435. var token;
  9436. while ((token = this.expect('*','/','%'))) {
  9437. left = this.binaryFn(left, token.fn, this.unary());
  9438. }
  9439. return left;
  9440. },
  9441. unary: function() {
  9442. var token;
  9443. if (this.expect('+')) {
  9444. return this.primary();
  9445. } else if ((token = this.expect('-'))) {
  9446. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9447. } else if ((token = this.expect('!'))) {
  9448. return this.unaryFn(token.fn, this.unary());
  9449. } else {
  9450. return this.primary();
  9451. }
  9452. },
  9453. fieldAccess: function(object) {
  9454. var parser = this;
  9455. var field = this.expect().text;
  9456. var getter = getterFn(field, this.options, this.text);
  9457. return extend(function(scope, locals, self) {
  9458. return getter(self || object(scope, locals));
  9459. }, {
  9460. assign: function(scope, value, locals) {
  9461. return setter(object(scope, locals), field, value, parser.text, parser.options);
  9462. }
  9463. });
  9464. },
  9465. objectIndex: function(obj) {
  9466. var parser = this;
  9467. var indexFn = this.expression();
  9468. this.consume(']');
  9469. return extend(function(self, locals) {
  9470. var o = obj(self, locals),
  9471. i = indexFn(self, locals),
  9472. v, p;
  9473. if (!o) return undefined;
  9474. v = ensureSafeObject(o[i], parser.text);
  9475. if (v && v.then && parser.options.unwrapPromises) {
  9476. p = v;
  9477. if (!('$$v' in v)) {
  9478. p.$$v = undefined;
  9479. p.then(function(val) { p.$$v = val; });
  9480. }
  9481. v = v.$$v;
  9482. }
  9483. return v;
  9484. }, {
  9485. assign: function(self, value, locals) {
  9486. var key = indexFn(self, locals);
  9487. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9488. var safe = ensureSafeObject(obj(self, locals), parser.text);
  9489. return safe[key] = value;
  9490. }
  9491. });
  9492. },
  9493. functionCall: function(fn, contextGetter) {
  9494. var argsFn = [];
  9495. if (this.peekToken().text !== ')') {
  9496. do {
  9497. argsFn.push(this.expression());
  9498. } while (this.expect(','));
  9499. }
  9500. this.consume(')');
  9501. var parser = this;
  9502. return function(scope, locals) {
  9503. var args = [];
  9504. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9505. for (var i = 0; i < argsFn.length; i++) {
  9506. args.push(argsFn[i](scope, locals));
  9507. }
  9508. var fnPtr = fn(scope, locals, context) || noop;
  9509. ensureSafeObject(context, parser.text);
  9510. ensureSafeObject(fnPtr, parser.text);
  9511. // IE stupidity! (IE doesn't have apply for some native functions)
  9512. var v = fnPtr.apply
  9513. ? fnPtr.apply(context, args)
  9514. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9515. return ensureSafeObject(v, parser.text);
  9516. };
  9517. },
  9518. // This is used with json array declaration
  9519. arrayDeclaration: function () {
  9520. var elementFns = [];
  9521. var allConstant = true;
  9522. if (this.peekToken().text !== ']') {
  9523. do {
  9524. if (this.peek(']')) {
  9525. // Support trailing commas per ES5.1.
  9526. break;
  9527. }
  9528. var elementFn = this.expression();
  9529. elementFns.push(elementFn);
  9530. if (!elementFn.constant) {
  9531. allConstant = false;
  9532. }
  9533. } while (this.expect(','));
  9534. }
  9535. this.consume(']');
  9536. return extend(function(self, locals) {
  9537. var array = [];
  9538. for (var i = 0; i < elementFns.length; i++) {
  9539. array.push(elementFns[i](self, locals));
  9540. }
  9541. return array;
  9542. }, {
  9543. literal: true,
  9544. constant: allConstant
  9545. });
  9546. },
  9547. object: function () {
  9548. var keyValues = [];
  9549. var allConstant = true;
  9550. if (this.peekToken().text !== '}') {
  9551. do {
  9552. if (this.peek('}')) {
  9553. // Support trailing commas per ES5.1.
  9554. break;
  9555. }
  9556. var token = this.expect(),
  9557. key = token.string || token.text;
  9558. this.consume(':');
  9559. var value = this.expression();
  9560. keyValues.push({key: key, value: value});
  9561. if (!value.constant) {
  9562. allConstant = false;
  9563. }
  9564. } while (this.expect(','));
  9565. }
  9566. this.consume('}');
  9567. return extend(function(self, locals) {
  9568. var object = {};
  9569. for (var i = 0; i < keyValues.length; i++) {
  9570. var keyValue = keyValues[i];
  9571. object[keyValue.key] = keyValue.value(self, locals);
  9572. }
  9573. return object;
  9574. }, {
  9575. literal: true,
  9576. constant: allConstant
  9577. });
  9578. }
  9579. };
  9580. //////////////////////////////////////////////////
  9581. // Parser helper functions
  9582. //////////////////////////////////////////////////
  9583. function setter(obj, path, setValue, fullExp, options) {
  9584. //needed?
  9585. options = options || {};
  9586. var element = path.split('.'), key;
  9587. for (var i = 0; element.length > 1; i++) {
  9588. key = ensureSafeMemberName(element.shift(), fullExp);
  9589. var propertyObj = obj[key];
  9590. if (!propertyObj) {
  9591. propertyObj = {};
  9592. obj[key] = propertyObj;
  9593. }
  9594. obj = propertyObj;
  9595. if (obj.then && options.unwrapPromises) {
  9596. promiseWarning(fullExp);
  9597. if (!("$$v" in obj)) {
  9598. (function(promise) {
  9599. promise.then(function(val) { promise.$$v = val; }); }
  9600. )(obj);
  9601. }
  9602. if (obj.$$v === undefined) {
  9603. obj.$$v = {};
  9604. }
  9605. obj = obj.$$v;
  9606. }
  9607. }
  9608. key = ensureSafeMemberName(element.shift(), fullExp);
  9609. obj[key] = setValue;
  9610. return setValue;
  9611. }
  9612. var getterFnCache = {};
  9613. /**
  9614. * Implementation of the "Black Hole" variant from:
  9615. * - http://jsperf.com/angularjs-parse-getter/4
  9616. * - http://jsperf.com/path-evaluation-simplified/7
  9617. */
  9618. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9619. ensureSafeMemberName(key0, fullExp);
  9620. ensureSafeMemberName(key1, fullExp);
  9621. ensureSafeMemberName(key2, fullExp);
  9622. ensureSafeMemberName(key3, fullExp);
  9623. ensureSafeMemberName(key4, fullExp);
  9624. return !options.unwrapPromises
  9625. ? function cspSafeGetter(scope, locals) {
  9626. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9627. if (pathVal == null) return pathVal;
  9628. pathVal = pathVal[key0];
  9629. if (!key1) return pathVal;
  9630. if (pathVal == null) return undefined;
  9631. pathVal = pathVal[key1];
  9632. if (!key2) return pathVal;
  9633. if (pathVal == null) return undefined;
  9634. pathVal = pathVal[key2];
  9635. if (!key3) return pathVal;
  9636. if (pathVal == null) return undefined;
  9637. pathVal = pathVal[key3];
  9638. if (!key4) return pathVal;
  9639. if (pathVal == null) return undefined;
  9640. pathVal = pathVal[key4];
  9641. return pathVal;
  9642. }
  9643. : function cspSafePromiseEnabledGetter(scope, locals) {
  9644. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9645. promise;
  9646. if (pathVal == null) return pathVal;
  9647. pathVal = pathVal[key0];
  9648. if (pathVal && pathVal.then) {
  9649. promiseWarning(fullExp);
  9650. if (!("$$v" in pathVal)) {
  9651. promise = pathVal;
  9652. promise.$$v = undefined;
  9653. promise.then(function(val) { promise.$$v = val; });
  9654. }
  9655. pathVal = pathVal.$$v;
  9656. }
  9657. if (!key1) return pathVal;
  9658. if (pathVal == null) return undefined;
  9659. pathVal = pathVal[key1];
  9660. if (pathVal && pathVal.then) {
  9661. promiseWarning(fullExp);
  9662. if (!("$$v" in pathVal)) {
  9663. promise = pathVal;
  9664. promise.$$v = undefined;
  9665. promise.then(function(val) { promise.$$v = val; });
  9666. }
  9667. pathVal = pathVal.$$v;
  9668. }
  9669. if (!key2) return pathVal;
  9670. if (pathVal == null) return undefined;
  9671. pathVal = pathVal[key2];
  9672. if (pathVal && pathVal.then) {
  9673. promiseWarning(fullExp);
  9674. if (!("$$v" in pathVal)) {
  9675. promise = pathVal;
  9676. promise.$$v = undefined;
  9677. promise.then(function(val) { promise.$$v = val; });
  9678. }
  9679. pathVal = pathVal.$$v;
  9680. }
  9681. if (!key3) return pathVal;
  9682. if (pathVal == null) return undefined;
  9683. pathVal = pathVal[key3];
  9684. if (pathVal && pathVal.then) {
  9685. promiseWarning(fullExp);
  9686. if (!("$$v" in pathVal)) {
  9687. promise = pathVal;
  9688. promise.$$v = undefined;
  9689. promise.then(function(val) { promise.$$v = val; });
  9690. }
  9691. pathVal = pathVal.$$v;
  9692. }
  9693. if (!key4) return pathVal;
  9694. if (pathVal == null) return undefined;
  9695. pathVal = pathVal[key4];
  9696. if (pathVal && pathVal.then) {
  9697. promiseWarning(fullExp);
  9698. if (!("$$v" in pathVal)) {
  9699. promise = pathVal;
  9700. promise.$$v = undefined;
  9701. promise.then(function(val) { promise.$$v = val; });
  9702. }
  9703. pathVal = pathVal.$$v;
  9704. }
  9705. return pathVal;
  9706. };
  9707. }
  9708. function simpleGetterFn1(key0, fullExp) {
  9709. ensureSafeMemberName(key0, fullExp);
  9710. return function simpleGetterFn1(scope, locals) {
  9711. if (scope == null) return undefined;
  9712. return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9713. };
  9714. }
  9715. function simpleGetterFn2(key0, key1, fullExp) {
  9716. ensureSafeMemberName(key0, fullExp);
  9717. ensureSafeMemberName(key1, fullExp);
  9718. return function simpleGetterFn2(scope, locals) {
  9719. if (scope == null) return undefined;
  9720. scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9721. return scope == null ? undefined : scope[key1];
  9722. };
  9723. }
  9724. function getterFn(path, options, fullExp) {
  9725. // Check whether the cache has this getter already.
  9726. // We can use hasOwnProperty directly on the cache because we ensure,
  9727. // see below, that the cache never stores a path called 'hasOwnProperty'
  9728. if (getterFnCache.hasOwnProperty(path)) {
  9729. return getterFnCache[path];
  9730. }
  9731. var pathKeys = path.split('.'),
  9732. pathKeysLength = pathKeys.length,
  9733. fn;
  9734. // When we have only 1 or 2 tokens, use optimized special case closures.
  9735. // http://jsperf.com/angularjs-parse-getter/6
  9736. if (!options.unwrapPromises && pathKeysLength === 1) {
  9737. fn = simpleGetterFn1(pathKeys[0], fullExp);
  9738. } else if (!options.unwrapPromises && pathKeysLength === 2) {
  9739. fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
  9740. } else if (options.csp) {
  9741. if (pathKeysLength < 6) {
  9742. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  9743. options);
  9744. } else {
  9745. fn = function(scope, locals) {
  9746. var i = 0, val;
  9747. do {
  9748. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  9749. pathKeys[i++], fullExp, options)(scope, locals);
  9750. locals = undefined; // clear after first iteration
  9751. scope = val;
  9752. } while (i < pathKeysLength);
  9753. return val;
  9754. };
  9755. }
  9756. } else {
  9757. var code = 'var p;\n';
  9758. forEach(pathKeys, function(key, index) {
  9759. ensureSafeMemberName(key, fullExp);
  9760. code += 'if(s == null) return undefined;\n' +
  9761. 's='+ (index
  9762. // we simply dereference 's' on any .dot notation
  9763. ? 's'
  9764. // but if we are first then we check locals first, and if so read it first
  9765. : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
  9766. (options.unwrapPromises
  9767. ? 'if (s && s.then) {\n' +
  9768. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  9769. ' if (!("$$v" in s)) {\n' +
  9770. ' p=s;\n' +
  9771. ' p.$$v = undefined;\n' +
  9772. ' p.then(function(v) {p.$$v=v;});\n' +
  9773. '}\n' +
  9774. ' s=s.$$v\n' +
  9775. '}\n'
  9776. : '');
  9777. });
  9778. code += 'return s;';
  9779. /* jshint -W054 */
  9780. var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
  9781. /* jshint +W054 */
  9782. evaledFnGetter.toString = valueFn(code);
  9783. fn = options.unwrapPromises ? function(scope, locals) {
  9784. return evaledFnGetter(scope, locals, promiseWarning);
  9785. } : evaledFnGetter;
  9786. }
  9787. // Only cache the value if it's not going to mess up the cache object
  9788. // This is more performant that using Object.prototype.hasOwnProperty.call
  9789. if (path !== 'hasOwnProperty') {
  9790. getterFnCache[path] = fn;
  9791. }
  9792. return fn;
  9793. }
  9794. ///////////////////////////////////
  9795. /**
  9796. * @ngdoc service
  9797. * @name $parse
  9798. * @kind function
  9799. *
  9800. * @description
  9801. *
  9802. * Converts Angular {@link guide/expression expression} into a function.
  9803. *
  9804. * ```js
  9805. * var getter = $parse('user.name');
  9806. * var setter = getter.assign;
  9807. * var context = {user:{name:'angular'}};
  9808. * var locals = {user:{name:'local'}};
  9809. *
  9810. * expect(getter(context)).toEqual('angular');
  9811. * setter(context, 'newValue');
  9812. * expect(context.user.name).toEqual('newValue');
  9813. * expect(getter(context, locals)).toEqual('local');
  9814. * ```
  9815. *
  9816. *
  9817. * @param {string} expression String expression to compile.
  9818. * @returns {function(context, locals)} a function which represents the compiled expression:
  9819. *
  9820. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  9821. * are evaluated against (typically a scope object).
  9822. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  9823. * `context`.
  9824. *
  9825. * The returned function also has the following properties:
  9826. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  9827. * literal.
  9828. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  9829. * constant literals.
  9830. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  9831. * set to a function to change its value on the given context.
  9832. *
  9833. */
  9834. /**
  9835. * @ngdoc provider
  9836. * @name $parseProvider
  9837. * @function
  9838. *
  9839. * @description
  9840. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  9841. * service.
  9842. */
  9843. function $ParseProvider() {
  9844. var cache = {};
  9845. var $parseOptions = {
  9846. csp: false,
  9847. unwrapPromises: false,
  9848. logPromiseWarnings: true
  9849. };
  9850. /**
  9851. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9852. *
  9853. * @ngdoc method
  9854. * @name $parseProvider#unwrapPromises
  9855. * @description
  9856. *
  9857. * **This feature is deprecated, see deprecation notes below for more info**
  9858. *
  9859. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  9860. * found at any part of the expression. In other words, if set to true, the expression will always
  9861. * result in a non-promise value.
  9862. *
  9863. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  9864. * the fulfillment value is used in place of the promise while evaluating the expression.
  9865. *
  9866. * **Deprecation notice**
  9867. *
  9868. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  9869. * dichotomy between data access in templates (accessed as raw values) and controller code
  9870. * (accessed as promises).
  9871. *
  9872. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  9873. * the model access there.
  9874. *
  9875. * Other downsides of automatic promise unwrapping:
  9876. *
  9877. * - when building components it's often desirable to receive the raw promises
  9878. * - adds complexity and slows down expression evaluation
  9879. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  9880. * generated
  9881. * - makes IDE auto-completion and tool support hard
  9882. *
  9883. * **Warning Logs**
  9884. *
  9885. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  9886. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  9887. * `$parseProvider.logPromiseWarnings(false)` api.
  9888. *
  9889. *
  9890. * @param {boolean=} value New value.
  9891. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9892. * setter.
  9893. */
  9894. this.unwrapPromises = function(value) {
  9895. if (isDefined(value)) {
  9896. $parseOptions.unwrapPromises = !!value;
  9897. return this;
  9898. } else {
  9899. return $parseOptions.unwrapPromises;
  9900. }
  9901. };
  9902. /**
  9903. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9904. *
  9905. * @ngdoc method
  9906. * @name $parseProvider#logPromiseWarnings
  9907. * @description
  9908. *
  9909. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  9910. *
  9911. * The default is set to `true`.
  9912. *
  9913. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  9914. *
  9915. * @param {boolean=} value New value.
  9916. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9917. * setter.
  9918. */
  9919. this.logPromiseWarnings = function(value) {
  9920. if (isDefined(value)) {
  9921. $parseOptions.logPromiseWarnings = value;
  9922. return this;
  9923. } else {
  9924. return $parseOptions.logPromiseWarnings;
  9925. }
  9926. };
  9927. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  9928. $parseOptions.csp = $sniffer.csp;
  9929. promiseWarning = function promiseWarningFn(fullExp) {
  9930. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  9931. promiseWarningCache[fullExp] = true;
  9932. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  9933. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  9934. };
  9935. return function(exp) {
  9936. var parsedExpression;
  9937. switch (typeof exp) {
  9938. case 'string':
  9939. if (cache.hasOwnProperty(exp)) {
  9940. return cache[exp];
  9941. }
  9942. var lexer = new Lexer($parseOptions);
  9943. var parser = new Parser(lexer, $filter, $parseOptions);
  9944. parsedExpression = parser.parse(exp, false);
  9945. if (exp !== 'hasOwnProperty') {
  9946. // Only cache the value if it's not going to mess up the cache object
  9947. // This is more performant that using Object.prototype.hasOwnProperty.call
  9948. cache[exp] = parsedExpression;
  9949. }
  9950. return parsedExpression;
  9951. case 'function':
  9952. return exp;
  9953. default:
  9954. return noop;
  9955. }
  9956. };
  9957. }];
  9958. }
  9959. /**
  9960. * @ngdoc service
  9961. * @name $q
  9962. * @requires $rootScope
  9963. *
  9964. * @description
  9965. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  9966. *
  9967. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  9968. * interface for interacting with an object that represents the result of an action that is
  9969. * performed asynchronously, and may or may not be finished at any given point in time.
  9970. *
  9971. * From the perspective of dealing with error handling, deferred and promise APIs are to
  9972. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  9973. *
  9974. * ```js
  9975. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  9976. * // are available in the current lexical scope (they could have been injected or passed in).
  9977. *
  9978. * function asyncGreet(name) {
  9979. * var deferred = $q.defer();
  9980. *
  9981. * setTimeout(function() {
  9982. * // since this fn executes async in a future turn of the event loop, we need to wrap
  9983. * // our code into an $apply call so that the model changes are properly observed.
  9984. * scope.$apply(function() {
  9985. * deferred.notify('About to greet ' + name + '.');
  9986. *
  9987. * if (okToGreet(name)) {
  9988. * deferred.resolve('Hello, ' + name + '!');
  9989. * } else {
  9990. * deferred.reject('Greeting ' + name + ' is not allowed.');
  9991. * }
  9992. * });
  9993. * }, 1000);
  9994. *
  9995. * return deferred.promise;
  9996. * }
  9997. *
  9998. * var promise = asyncGreet('Robin Hood');
  9999. * promise.then(function(greeting) {
  10000. * alert('Success: ' + greeting);
  10001. * }, function(reason) {
  10002. * alert('Failed: ' + reason);
  10003. * }, function(update) {
  10004. * alert('Got notification: ' + update);
  10005. * });
  10006. * ```
  10007. *
  10008. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10009. * comes in the way of guarantees that promise and deferred APIs make, see
  10010. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10011. *
  10012. * Additionally the promise api allows for composition that is very hard to do with the
  10013. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10014. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10015. * section on serial or parallel joining of promises.
  10016. *
  10017. *
  10018. * # The Deferred API
  10019. *
  10020. * A new instance of deferred is constructed by calling `$q.defer()`.
  10021. *
  10022. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10023. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10024. * of the task.
  10025. *
  10026. * **Methods**
  10027. *
  10028. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10029. * constructed via `$q.reject`, the promise will be rejected instead.
  10030. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10031. * resolving it with a rejection constructed via `$q.reject`.
  10032. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10033. * multiple times before the promise is either resolved or rejected.
  10034. *
  10035. * **Properties**
  10036. *
  10037. * - promise – `{Promise}` – promise object associated with this deferred.
  10038. *
  10039. *
  10040. * # The Promise API
  10041. *
  10042. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10043. * calling `deferred.promise`.
  10044. *
  10045. * The purpose of the promise object is to allow for interested parties to get access to the result
  10046. * of the deferred task when it completes.
  10047. *
  10048. * **Methods**
  10049. *
  10050. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10051. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10052. * as soon as the result is available. The callbacks are called with a single argument: the result
  10053. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10054. * provide a progress indication, before the promise is resolved or rejected.
  10055. *
  10056. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10057. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10058. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10059. * method.
  10060. *
  10061. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10062. *
  10063. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10064. * but to do so without modifying the final value. This is useful to release resources or do some
  10065. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10066. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10067. * more information.
  10068. *
  10069. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10070. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10071. * make your code IE8 and Android 2.x compatible.
  10072. *
  10073. * # Chaining promises
  10074. *
  10075. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10076. * possible to create a chain of promises:
  10077. *
  10078. * ```js
  10079. * promiseB = promiseA.then(function(result) {
  10080. * return result + 1;
  10081. * });
  10082. *
  10083. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10084. * // will be the result of promiseA incremented by 1
  10085. * ```
  10086. *
  10087. * It is possible to create chains of any length and since a promise can be resolved with another
  10088. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10089. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10090. * $http's response interceptors.
  10091. *
  10092. *
  10093. * # Differences between Kris Kowal's Q and $q
  10094. *
  10095. * There are two main differences:
  10096. *
  10097. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10098. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10099. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10100. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10101. * all the important functionality needed for common async tasks.
  10102. *
  10103. * # Testing
  10104. *
  10105. * ```js
  10106. * it('should simulate promise', inject(function($q, $rootScope) {
  10107. * var deferred = $q.defer();
  10108. * var promise = deferred.promise;
  10109. * var resolvedValue;
  10110. *
  10111. * promise.then(function(value) { resolvedValue = value; });
  10112. * expect(resolvedValue).toBeUndefined();
  10113. *
  10114. * // Simulate resolving of promise
  10115. * deferred.resolve(123);
  10116. * // Note that the 'then' function does not get called synchronously.
  10117. * // This is because we want the promise API to always be async, whether or not
  10118. * // it got called synchronously or asynchronously.
  10119. * expect(resolvedValue).toBeUndefined();
  10120. *
  10121. * // Propagate promise resolution to 'then' functions using $apply().
  10122. * $rootScope.$apply();
  10123. * expect(resolvedValue).toEqual(123);
  10124. * }));
  10125. * ```
  10126. */
  10127. function $QProvider() {
  10128. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10129. return qFactory(function(callback) {
  10130. $rootScope.$evalAsync(callback);
  10131. }, $exceptionHandler);
  10132. }];
  10133. }
  10134. /**
  10135. * Constructs a promise manager.
  10136. *
  10137. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10138. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10139. * debugging purposes.
  10140. * @returns {object} Promise manager.
  10141. */
  10142. function qFactory(nextTick, exceptionHandler) {
  10143. /**
  10144. * @ngdoc method
  10145. * @name $q#defer
  10146. * @function
  10147. *
  10148. * @description
  10149. * Creates a `Deferred` object which represents a task which will finish in the future.
  10150. *
  10151. * @returns {Deferred} Returns a new instance of deferred.
  10152. */
  10153. var defer = function() {
  10154. var pending = [],
  10155. value, deferred;
  10156. deferred = {
  10157. resolve: function(val) {
  10158. if (pending) {
  10159. var callbacks = pending;
  10160. pending = undefined;
  10161. value = ref(val);
  10162. if (callbacks.length) {
  10163. nextTick(function() {
  10164. var callback;
  10165. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10166. callback = callbacks[i];
  10167. value.then(callback[0], callback[1], callback[2]);
  10168. }
  10169. });
  10170. }
  10171. }
  10172. },
  10173. reject: function(reason) {
  10174. deferred.resolve(createInternalRejectedPromise(reason));
  10175. },
  10176. notify: function(progress) {
  10177. if (pending) {
  10178. var callbacks = pending;
  10179. if (pending.length) {
  10180. nextTick(function() {
  10181. var callback;
  10182. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10183. callback = callbacks[i];
  10184. callback[2](progress);
  10185. }
  10186. });
  10187. }
  10188. }
  10189. },
  10190. promise: {
  10191. then: function(callback, errback, progressback) {
  10192. var result = defer();
  10193. var wrappedCallback = function(value) {
  10194. try {
  10195. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10196. } catch(e) {
  10197. result.reject(e);
  10198. exceptionHandler(e);
  10199. }
  10200. };
  10201. var wrappedErrback = function(reason) {
  10202. try {
  10203. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10204. } catch(e) {
  10205. result.reject(e);
  10206. exceptionHandler(e);
  10207. }
  10208. };
  10209. var wrappedProgressback = function(progress) {
  10210. try {
  10211. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10212. } catch(e) {
  10213. exceptionHandler(e);
  10214. }
  10215. };
  10216. if (pending) {
  10217. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10218. } else {
  10219. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10220. }
  10221. return result.promise;
  10222. },
  10223. "catch": function(callback) {
  10224. return this.then(null, callback);
  10225. },
  10226. "finally": function(callback) {
  10227. function makePromise(value, resolved) {
  10228. var result = defer();
  10229. if (resolved) {
  10230. result.resolve(value);
  10231. } else {
  10232. result.reject(value);
  10233. }
  10234. return result.promise;
  10235. }
  10236. function handleCallback(value, isResolved) {
  10237. var callbackOutput = null;
  10238. try {
  10239. callbackOutput = (callback ||defaultCallback)();
  10240. } catch(e) {
  10241. return makePromise(e, false);
  10242. }
  10243. if (callbackOutput && isFunction(callbackOutput.then)) {
  10244. return callbackOutput.then(function() {
  10245. return makePromise(value, isResolved);
  10246. }, function(error) {
  10247. return makePromise(error, false);
  10248. });
  10249. } else {
  10250. return makePromise(value, isResolved);
  10251. }
  10252. }
  10253. return this.then(function(value) {
  10254. return handleCallback(value, true);
  10255. }, function(error) {
  10256. return handleCallback(error, false);
  10257. });
  10258. }
  10259. }
  10260. };
  10261. return deferred;
  10262. };
  10263. var ref = function(value) {
  10264. if (value && isFunction(value.then)) return value;
  10265. return {
  10266. then: function(callback) {
  10267. var result = defer();
  10268. nextTick(function() {
  10269. result.resolve(callback(value));
  10270. });
  10271. return result.promise;
  10272. }
  10273. };
  10274. };
  10275. /**
  10276. * @ngdoc method
  10277. * @name $q#reject
  10278. * @function
  10279. *
  10280. * @description
  10281. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10282. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10283. * a promise chain, you don't need to worry about it.
  10284. *
  10285. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10286. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10287. * a promise error callback and you want to forward the error to the promise derived from the
  10288. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10289. * `reject`.
  10290. *
  10291. * ```js
  10292. * promiseB = promiseA.then(function(result) {
  10293. * // success: do something and resolve promiseB
  10294. * // with the old or a new result
  10295. * return result;
  10296. * }, function(reason) {
  10297. * // error: handle the error if possible and
  10298. * // resolve promiseB with newPromiseOrValue,
  10299. * // otherwise forward the rejection to promiseB
  10300. * if (canHandle(reason)) {
  10301. * // handle the error and recover
  10302. * return newPromiseOrValue;
  10303. * }
  10304. * return $q.reject(reason);
  10305. * });
  10306. * ```
  10307. *
  10308. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10309. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10310. */
  10311. var reject = function(reason) {
  10312. var result = defer();
  10313. result.reject(reason);
  10314. return result.promise;
  10315. };
  10316. var createInternalRejectedPromise = function(reason) {
  10317. return {
  10318. then: function(callback, errback) {
  10319. var result = defer();
  10320. nextTick(function() {
  10321. try {
  10322. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10323. } catch(e) {
  10324. result.reject(e);
  10325. exceptionHandler(e);
  10326. }
  10327. });
  10328. return result.promise;
  10329. }
  10330. };
  10331. };
  10332. /**
  10333. * @ngdoc method
  10334. * @name $q#when
  10335. * @function
  10336. *
  10337. * @description
  10338. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10339. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10340. * the promise comes from a source that can't be trusted.
  10341. *
  10342. * @param {*} value Value or a promise
  10343. * @returns {Promise} Returns a promise of the passed value or promise
  10344. */
  10345. var when = function(value, callback, errback, progressback) {
  10346. var result = defer(),
  10347. done;
  10348. var wrappedCallback = function(value) {
  10349. try {
  10350. return (isFunction(callback) ? callback : defaultCallback)(value);
  10351. } catch (e) {
  10352. exceptionHandler(e);
  10353. return reject(e);
  10354. }
  10355. };
  10356. var wrappedErrback = function(reason) {
  10357. try {
  10358. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10359. } catch (e) {
  10360. exceptionHandler(e);
  10361. return reject(e);
  10362. }
  10363. };
  10364. var wrappedProgressback = function(progress) {
  10365. try {
  10366. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10367. } catch (e) {
  10368. exceptionHandler(e);
  10369. }
  10370. };
  10371. nextTick(function() {
  10372. ref(value).then(function(value) {
  10373. if (done) return;
  10374. done = true;
  10375. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10376. }, function(reason) {
  10377. if (done) return;
  10378. done = true;
  10379. result.resolve(wrappedErrback(reason));
  10380. }, function(progress) {
  10381. if (done) return;
  10382. result.notify(wrappedProgressback(progress));
  10383. });
  10384. });
  10385. return result.promise;
  10386. };
  10387. function defaultCallback(value) {
  10388. return value;
  10389. }
  10390. function defaultErrback(reason) {
  10391. return reject(reason);
  10392. }
  10393. /**
  10394. * @ngdoc method
  10395. * @name $q#all
  10396. * @function
  10397. *
  10398. * @description
  10399. * Combines multiple promises into a single promise that is resolved when all of the input
  10400. * promises are resolved.
  10401. *
  10402. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10403. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10404. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10405. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10406. * with the same rejection value.
  10407. */
  10408. function all(promises) {
  10409. var deferred = defer(),
  10410. counter = 0,
  10411. results = isArray(promises) ? [] : {};
  10412. forEach(promises, function(promise, key) {
  10413. counter++;
  10414. ref(promise).then(function(value) {
  10415. if (results.hasOwnProperty(key)) return;
  10416. results[key] = value;
  10417. if (!(--counter)) deferred.resolve(results);
  10418. }, function(reason) {
  10419. if (results.hasOwnProperty(key)) return;
  10420. deferred.reject(reason);
  10421. });
  10422. });
  10423. if (counter === 0) {
  10424. deferred.resolve(results);
  10425. }
  10426. return deferred.promise;
  10427. }
  10428. return {
  10429. defer: defer,
  10430. reject: reject,
  10431. when: when,
  10432. all: all
  10433. };
  10434. }
  10435. function $$RAFProvider(){ //rAF
  10436. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10437. var requestAnimationFrame = $window.requestAnimationFrame ||
  10438. $window.webkitRequestAnimationFrame ||
  10439. $window.mozRequestAnimationFrame;
  10440. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10441. $window.webkitCancelAnimationFrame ||
  10442. $window.mozCancelAnimationFrame ||
  10443. $window.webkitCancelRequestAnimationFrame;
  10444. var rafSupported = !!requestAnimationFrame;
  10445. var raf = rafSupported
  10446. ? function(fn) {
  10447. var id = requestAnimationFrame(fn);
  10448. return function() {
  10449. cancelAnimationFrame(id);
  10450. };
  10451. }
  10452. : function(fn) {
  10453. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10454. return function() {
  10455. $timeout.cancel(timer);
  10456. };
  10457. };
  10458. raf.supported = rafSupported;
  10459. return raf;
  10460. }];
  10461. }
  10462. /**
  10463. * DESIGN NOTES
  10464. *
  10465. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10466. *
  10467. * The typical use of scope is to watch the expressions, which most of the time return the same
  10468. * value as last time so we optimize the operation.
  10469. *
  10470. * Closures construction is expensive in terms of speed as well as memory:
  10471. * - No closures, instead use prototypical inheritance for API
  10472. * - Internal state needs to be stored on scope directly, which means that private state is
  10473. * exposed as $$____ properties
  10474. *
  10475. * Loop operations are optimized by using while(count--) { ... }
  10476. * - this means that in order to keep the same order of execution as addition we have to add
  10477. * items to the array at the beginning (shift) instead of at the end (push)
  10478. *
  10479. * Child scopes are created and removed often
  10480. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10481. *
  10482. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10483. * implemented in the same way as watch. Watch requires return of initialization function which
  10484. * are expensive to construct.
  10485. */
  10486. /**
  10487. * @ngdoc provider
  10488. * @name $rootScopeProvider
  10489. * @description
  10490. *
  10491. * Provider for the $rootScope service.
  10492. */
  10493. /**
  10494. * @ngdoc method
  10495. * @name $rootScopeProvider#digestTtl
  10496. * @description
  10497. *
  10498. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10499. * assuming that the model is unstable.
  10500. *
  10501. * The current default is 10 iterations.
  10502. *
  10503. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10504. * several digest iterations. However if an application needs more than the default 10 digest
  10505. * iterations for its model to stabilize then you should investigate what is causing the model to
  10506. * continuously change during the digest.
  10507. *
  10508. * Increasing the TTL could have performance implications, so you should not change it without
  10509. * proper justification.
  10510. *
  10511. * @param {number} limit The number of digest iterations.
  10512. */
  10513. /**
  10514. * @ngdoc service
  10515. * @name $rootScope
  10516. * @description
  10517. *
  10518. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10519. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10520. * between the model and the view, via a mechanism for watching the model for changes.
  10521. * They also provide an event emission/broadcast and subscription facility. See the
  10522. * {@link guide/scope developer guide on scopes}.
  10523. */
  10524. function $RootScopeProvider(){
  10525. var TTL = 10;
  10526. var $rootScopeMinErr = minErr('$rootScope');
  10527. var lastDirtyWatch = null;
  10528. this.digestTtl = function(value) {
  10529. if (arguments.length) {
  10530. TTL = value;
  10531. }
  10532. return TTL;
  10533. };
  10534. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10535. function( $injector, $exceptionHandler, $parse, $browser) {
  10536. /**
  10537. * @ngdoc type
  10538. * @name $rootScope.Scope
  10539. *
  10540. * @description
  10541. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10542. * {@link auto.$injector $injector}. Child scopes are created using the
  10543. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10544. * compiled HTML template is executed.)
  10545. *
  10546. * Here is a simple scope snippet to show how you can interact with the scope.
  10547. * ```html
  10548. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10549. * ```
  10550. *
  10551. * # Inheritance
  10552. * A scope can inherit from a parent scope, as in this example:
  10553. * ```js
  10554. var parent = $rootScope;
  10555. var child = parent.$new();
  10556. parent.salutation = "Hello";
  10557. child.name = "World";
  10558. expect(child.salutation).toEqual('Hello');
  10559. child.salutation = "Welcome";
  10560. expect(child.salutation).toEqual('Welcome');
  10561. expect(parent.salutation).toEqual('Hello');
  10562. * ```
  10563. *
  10564. *
  10565. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10566. * provided for the current scope. Defaults to {@link ng}.
  10567. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10568. * append/override services provided by `providers`. This is handy
  10569. * when unit-testing and having the need to override a default
  10570. * service.
  10571. * @returns {Object} Newly created scope.
  10572. *
  10573. */
  10574. function Scope() {
  10575. this.$id = nextUid();
  10576. this.$$phase = this.$parent = this.$$watchers =
  10577. this.$$nextSibling = this.$$prevSibling =
  10578. this.$$childHead = this.$$childTail = null;
  10579. this['this'] = this.$root = this;
  10580. this.$$destroyed = false;
  10581. this.$$asyncQueue = [];
  10582. this.$$postDigestQueue = [];
  10583. this.$$listeners = {};
  10584. this.$$listenerCount = {};
  10585. this.$$isolateBindings = {};
  10586. }
  10587. /**
  10588. * @ngdoc property
  10589. * @name $rootScope.Scope#$id
  10590. * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
  10591. * debugging.
  10592. */
  10593. Scope.prototype = {
  10594. constructor: Scope,
  10595. /**
  10596. * @ngdoc method
  10597. * @name $rootScope.Scope#$new
  10598. * @function
  10599. *
  10600. * @description
  10601. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10602. *
  10603. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
  10604. * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
  10605. * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10606. *
  10607. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10608. * desired for the scope and its child scopes to be permanently detached from the parent and
  10609. * thus stop participating in model change detection and listener notification by invoking.
  10610. *
  10611. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10612. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10613. * When creating widgets, it is useful for the widget to not accidentally read parent
  10614. * state.
  10615. *
  10616. * @returns {Object} The newly created child scope.
  10617. *
  10618. */
  10619. $new: function(isolate) {
  10620. var ChildScope,
  10621. child;
  10622. if (isolate) {
  10623. child = new Scope();
  10624. child.$root = this.$root;
  10625. // ensure that there is just one async queue per $rootScope and its children
  10626. child.$$asyncQueue = this.$$asyncQueue;
  10627. child.$$postDigestQueue = this.$$postDigestQueue;
  10628. } else {
  10629. ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges
  10630. // the name it does not become random set of chars. This will then show up as class
  10631. // name in the web inspector.
  10632. ChildScope.prototype = this;
  10633. child = new ChildScope();
  10634. child.$id = nextUid();
  10635. }
  10636. child['this'] = child;
  10637. child.$$listeners = {};
  10638. child.$$listenerCount = {};
  10639. child.$parent = this;
  10640. child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
  10641. child.$$prevSibling = this.$$childTail;
  10642. if (this.$$childHead) {
  10643. this.$$childTail.$$nextSibling = child;
  10644. this.$$childTail = child;
  10645. } else {
  10646. this.$$childHead = this.$$childTail = child;
  10647. }
  10648. return child;
  10649. },
  10650. /**
  10651. * @ngdoc method
  10652. * @name $rootScope.Scope#$watch
  10653. * @function
  10654. *
  10655. * @description
  10656. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10657. *
  10658. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  10659. * $digest()} and should return the value that will be watched. (Since
  10660. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  10661. * `watchExpression` can execute multiple times per
  10662. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  10663. * - The `listener` is called only when the value from the current `watchExpression` and the
  10664. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10665. * see below). The inequality is determined according to
  10666. * {@link angular.equals} function. To save the value of the object for later comparison,
  10667. * the {@link angular.copy} function is used. It also means that watching complex options
  10668. * will have adverse memory and performance implications.
  10669. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  10670. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  10671. * iteration limit is 10 to prevent an infinite loop deadlock.
  10672. *
  10673. *
  10674. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  10675. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  10676. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  10677. * change is detected, be prepared for multiple calls to your listener.)
  10678. *
  10679. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  10680. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  10681. * watcher. In rare cases, this is undesirable because the listener is called when the result
  10682. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  10683. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  10684. * listener was called due to initialization.
  10685. *
  10686. * The example below contains an illustration of using a function as your $watch listener
  10687. *
  10688. *
  10689. * # Example
  10690. * ```js
  10691. // let's assume that scope was dependency injected as the $rootScope
  10692. var scope = $rootScope;
  10693. scope.name = 'misko';
  10694. scope.counter = 0;
  10695. expect(scope.counter).toEqual(0);
  10696. scope.$watch('name', function(newValue, oldValue) {
  10697. scope.counter = scope.counter + 1;
  10698. });
  10699. expect(scope.counter).toEqual(0);
  10700. scope.$digest();
  10701. // no variable change
  10702. expect(scope.counter).toEqual(0);
  10703. scope.name = 'adam';
  10704. scope.$digest();
  10705. expect(scope.counter).toEqual(1);
  10706. // Using a listener function
  10707. var food;
  10708. scope.foodCounter = 0;
  10709. expect(scope.foodCounter).toEqual(0);
  10710. scope.$watch(
  10711. // This is the listener function
  10712. function() { return food; },
  10713. // This is the change handler
  10714. function(newValue, oldValue) {
  10715. if ( newValue !== oldValue ) {
  10716. // Only increment the counter if the value changed
  10717. scope.foodCounter = scope.foodCounter + 1;
  10718. }
  10719. }
  10720. );
  10721. // No digest has been run so the counter will be zero
  10722. expect(scope.foodCounter).toEqual(0);
  10723. // Run the digest but since food has not changed count will still be zero
  10724. scope.$digest();
  10725. expect(scope.foodCounter).toEqual(0);
  10726. // Update food and run digest. Now the counter will increment
  10727. food = 'cheeseburger';
  10728. scope.$digest();
  10729. expect(scope.foodCounter).toEqual(1);
  10730. * ```
  10731. *
  10732. *
  10733. *
  10734. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  10735. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  10736. * a call to the `listener`.
  10737. *
  10738. * - `string`: Evaluated as {@link guide/expression expression}
  10739. * - `function(scope)`: called with current `scope` as a parameter.
  10740. * @param {(function()|string)=} listener Callback called whenever the return value of
  10741. * the `watchExpression` changes.
  10742. *
  10743. * - `string`: Evaluated as {@link guide/expression expression}
  10744. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  10745. * parameters.
  10746. *
  10747. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  10748. * comparing for reference equality.
  10749. * @returns {function()} Returns a deregistration function for this listener.
  10750. */
  10751. $watch: function(watchExp, listener, objectEquality) {
  10752. var scope = this,
  10753. get = compileToFn(watchExp, 'watch'),
  10754. array = scope.$$watchers,
  10755. watcher = {
  10756. fn: listener,
  10757. last: initWatchVal,
  10758. get: get,
  10759. exp: watchExp,
  10760. eq: !!objectEquality
  10761. };
  10762. lastDirtyWatch = null;
  10763. // in the case user pass string, we need to compile it, do we really need this ?
  10764. if (!isFunction(listener)) {
  10765. var listenFn = compileToFn(listener || noop, 'listener');
  10766. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  10767. }
  10768. if (typeof watchExp == 'string' && get.constant) {
  10769. var originalFn = watcher.fn;
  10770. watcher.fn = function(newVal, oldVal, scope) {
  10771. originalFn.call(this, newVal, oldVal, scope);
  10772. arrayRemove(array, watcher);
  10773. };
  10774. }
  10775. if (!array) {
  10776. array = scope.$$watchers = [];
  10777. }
  10778. // we use unshift since we use a while loop in $digest for speed.
  10779. // the while loop reads in reverse order.
  10780. array.unshift(watcher);
  10781. return function() {
  10782. arrayRemove(array, watcher);
  10783. lastDirtyWatch = null;
  10784. };
  10785. },
  10786. /**
  10787. * @ngdoc method
  10788. * @name $rootScope.Scope#$watchCollection
  10789. * @function
  10790. *
  10791. * @description
  10792. * Shallow watches the properties of an object and fires whenever any of the properties change
  10793. * (for arrays, this implies watching the array items; for object maps, this implies watching
  10794. * the properties). If a change is detected, the `listener` callback is fired.
  10795. *
  10796. * - The `obj` collection is observed via standard $watch operation and is examined on every
  10797. * call to $digest() to see if any items have been added, removed, or moved.
  10798. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  10799. * adding, removing, and moving items belonging to an object or array.
  10800. *
  10801. *
  10802. * # Example
  10803. * ```js
  10804. $scope.names = ['igor', 'matias', 'misko', 'james'];
  10805. $scope.dataCount = 4;
  10806. $scope.$watchCollection('names', function(newNames, oldNames) {
  10807. $scope.dataCount = newNames.length;
  10808. });
  10809. expect($scope.dataCount).toEqual(4);
  10810. $scope.$digest();
  10811. //still at 4 ... no changes
  10812. expect($scope.dataCount).toEqual(4);
  10813. $scope.names.pop();
  10814. $scope.$digest();
  10815. //now there's been a change
  10816. expect($scope.dataCount).toEqual(3);
  10817. * ```
  10818. *
  10819. *
  10820. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  10821. * expression value should evaluate to an object or an array which is observed on each
  10822. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  10823. * collection will trigger a call to the `listener`.
  10824. *
  10825. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  10826. * when a change is detected.
  10827. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  10828. * - The `oldCollection` object is a copy of the former collection data.
  10829. * Due to performance considerations, the`oldCollection` value is computed only if the
  10830. * `listener` function declares two or more arguments.
  10831. * - The `scope` argument refers to the current scope.
  10832. *
  10833. * @returns {function()} Returns a de-registration function for this listener. When the
  10834. * de-registration function is executed, the internal watch operation is terminated.
  10835. */
  10836. $watchCollection: function(obj, listener) {
  10837. var self = this;
  10838. // the current value, updated on each dirty-check run
  10839. var newValue;
  10840. // a shallow copy of the newValue from the last dirty-check run,
  10841. // updated to match newValue during dirty-check run
  10842. var oldValue;
  10843. // a shallow copy of the newValue from when the last change happened
  10844. var veryOldValue;
  10845. // only track veryOldValue if the listener is asking for it
  10846. var trackVeryOldValue = (listener.length > 1);
  10847. var changeDetected = 0;
  10848. var objGetter = $parse(obj);
  10849. var internalArray = [];
  10850. var internalObject = {};
  10851. var initRun = true;
  10852. var oldLength = 0;
  10853. function $watchCollectionWatch() {
  10854. newValue = objGetter(self);
  10855. var newLength, key;
  10856. if (!isObject(newValue)) { // if primitive
  10857. if (oldValue !== newValue) {
  10858. oldValue = newValue;
  10859. changeDetected++;
  10860. }
  10861. } else if (isArrayLike(newValue)) {
  10862. if (oldValue !== internalArray) {
  10863. // we are transitioning from something which was not an array into array.
  10864. oldValue = internalArray;
  10865. oldLength = oldValue.length = 0;
  10866. changeDetected++;
  10867. }
  10868. newLength = newValue.length;
  10869. if (oldLength !== newLength) {
  10870. // if lengths do not match we need to trigger change notification
  10871. changeDetected++;
  10872. oldValue.length = oldLength = newLength;
  10873. }
  10874. // copy the items to oldValue and look for changes.
  10875. for (var i = 0; i < newLength; i++) {
  10876. var bothNaN = (oldValue[i] !== oldValue[i]) &&
  10877. (newValue[i] !== newValue[i]);
  10878. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  10879. changeDetected++;
  10880. oldValue[i] = newValue[i];
  10881. }
  10882. }
  10883. } else {
  10884. if (oldValue !== internalObject) {
  10885. // we are transitioning from something which was not an object into object.
  10886. oldValue = internalObject = {};
  10887. oldLength = 0;
  10888. changeDetected++;
  10889. }
  10890. // copy the items to oldValue and look for changes.
  10891. newLength = 0;
  10892. for (key in newValue) {
  10893. if (newValue.hasOwnProperty(key)) {
  10894. newLength++;
  10895. if (oldValue.hasOwnProperty(key)) {
  10896. if (oldValue[key] !== newValue[key]) {
  10897. changeDetected++;
  10898. oldValue[key] = newValue[key];
  10899. }
  10900. } else {
  10901. oldLength++;
  10902. oldValue[key] = newValue[key];
  10903. changeDetected++;
  10904. }
  10905. }
  10906. }
  10907. if (oldLength > newLength) {
  10908. // we used to have more keys, need to find them and destroy them.
  10909. changeDetected++;
  10910. for(key in oldValue) {
  10911. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  10912. oldLength--;
  10913. delete oldValue[key];
  10914. }
  10915. }
  10916. }
  10917. }
  10918. return changeDetected;
  10919. }
  10920. function $watchCollectionAction() {
  10921. if (initRun) {
  10922. initRun = false;
  10923. listener(newValue, newValue, self);
  10924. } else {
  10925. listener(newValue, veryOldValue, self);
  10926. }
  10927. // make a copy for the next time a collection is changed
  10928. if (trackVeryOldValue) {
  10929. if (!isObject(newValue)) {
  10930. //primitive
  10931. veryOldValue = newValue;
  10932. } else if (isArrayLike(newValue)) {
  10933. veryOldValue = new Array(newValue.length);
  10934. for (var i = 0; i < newValue.length; i++) {
  10935. veryOldValue[i] = newValue[i];
  10936. }
  10937. } else { // if object
  10938. veryOldValue = {};
  10939. for (var key in newValue) {
  10940. if (hasOwnProperty.call(newValue, key)) {
  10941. veryOldValue[key] = newValue[key];
  10942. }
  10943. }
  10944. }
  10945. }
  10946. }
  10947. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  10948. },
  10949. /**
  10950. * @ngdoc method
  10951. * @name $rootScope.Scope#$digest
  10952. * @function
  10953. *
  10954. * @description
  10955. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  10956. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  10957. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  10958. * until no more listeners are firing. This means that it is possible to get into an infinite
  10959. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  10960. * iterations exceeds 10.
  10961. *
  10962. * Usually, you don't call `$digest()` directly in
  10963. * {@link ng.directive:ngController controllers} or in
  10964. * {@link ng.$compileProvider#directive directives}.
  10965. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  10966. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  10967. *
  10968. * If you want to be notified whenever `$digest()` is called,
  10969. * you can register a `watchExpression` function with
  10970. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  10971. *
  10972. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  10973. *
  10974. * # Example
  10975. * ```js
  10976. var scope = ...;
  10977. scope.name = 'misko';
  10978. scope.counter = 0;
  10979. expect(scope.counter).toEqual(0);
  10980. scope.$watch('name', function(newValue, oldValue) {
  10981. scope.counter = scope.counter + 1;
  10982. });
  10983. expect(scope.counter).toEqual(0);
  10984. scope.$digest();
  10985. // no variable change
  10986. expect(scope.counter).toEqual(0);
  10987. scope.name = 'adam';
  10988. scope.$digest();
  10989. expect(scope.counter).toEqual(1);
  10990. * ```
  10991. *
  10992. */
  10993. $digest: function() {
  10994. var watch, value, last,
  10995. watchers,
  10996. asyncQueue = this.$$asyncQueue,
  10997. postDigestQueue = this.$$postDigestQueue,
  10998. length,
  10999. dirty, ttl = TTL,
  11000. next, current, target = this,
  11001. watchLog = [],
  11002. logIdx, logMsg, asyncTask;
  11003. beginPhase('$digest');
  11004. lastDirtyWatch = null;
  11005. do { // "while dirty" loop
  11006. dirty = false;
  11007. current = target;
  11008. while(asyncQueue.length) {
  11009. try {
  11010. asyncTask = asyncQueue.shift();
  11011. asyncTask.scope.$eval(asyncTask.expression);
  11012. } catch (e) {
  11013. clearPhase();
  11014. $exceptionHandler(e);
  11015. }
  11016. lastDirtyWatch = null;
  11017. }
  11018. traverseScopesLoop:
  11019. do { // "traverse the scopes" loop
  11020. if ((watchers = current.$$watchers)) {
  11021. // process our watches
  11022. length = watchers.length;
  11023. while (length--) {
  11024. try {
  11025. watch = watchers[length];
  11026. // Most common watches are on primitives, in which case we can short
  11027. // circuit it with === operator, only when === fails do we use .equals
  11028. if (watch) {
  11029. if ((value = watch.get(current)) !== (last = watch.last) &&
  11030. !(watch.eq
  11031. ? equals(value, last)
  11032. : (typeof value == 'number' && typeof last == 'number'
  11033. && isNaN(value) && isNaN(last)))) {
  11034. dirty = true;
  11035. lastDirtyWatch = watch;
  11036. watch.last = watch.eq ? copy(value) : value;
  11037. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11038. if (ttl < 5) {
  11039. logIdx = 4 - ttl;
  11040. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11041. logMsg = (isFunction(watch.exp))
  11042. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11043. : watch.exp;
  11044. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11045. watchLog[logIdx].push(logMsg);
  11046. }
  11047. } else if (watch === lastDirtyWatch) {
  11048. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11049. // have already been tested.
  11050. dirty = false;
  11051. break traverseScopesLoop;
  11052. }
  11053. }
  11054. } catch (e) {
  11055. clearPhase();
  11056. $exceptionHandler(e);
  11057. }
  11058. }
  11059. }
  11060. // Insanity Warning: scope depth-first traversal
  11061. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11062. // this piece should be kept in sync with the traversal in $broadcast
  11063. if (!(next = (current.$$childHead ||
  11064. (current !== target && current.$$nextSibling)))) {
  11065. while(current !== target && !(next = current.$$nextSibling)) {
  11066. current = current.$parent;
  11067. }
  11068. }
  11069. } while ((current = next));
  11070. // `break traverseScopesLoop;` takes us to here
  11071. if((dirty || asyncQueue.length) && !(ttl--)) {
  11072. clearPhase();
  11073. throw $rootScopeMinErr('infdig',
  11074. '{0} $digest() iterations reached. Aborting!\n' +
  11075. 'Watchers fired in the last 5 iterations: {1}',
  11076. TTL, toJson(watchLog));
  11077. }
  11078. } while (dirty || asyncQueue.length);
  11079. clearPhase();
  11080. while(postDigestQueue.length) {
  11081. try {
  11082. postDigestQueue.shift()();
  11083. } catch (e) {
  11084. $exceptionHandler(e);
  11085. }
  11086. }
  11087. },
  11088. /**
  11089. * @ngdoc event
  11090. * @name $rootScope.Scope#$destroy
  11091. * @eventType broadcast on scope being destroyed
  11092. *
  11093. * @description
  11094. * Broadcasted when a scope and its children are being destroyed.
  11095. *
  11096. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11097. * clean up DOM bindings before an element is removed from the DOM.
  11098. */
  11099. /**
  11100. * @ngdoc method
  11101. * @name $rootScope.Scope#$destroy
  11102. * @function
  11103. *
  11104. * @description
  11105. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11106. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11107. * propagate to the current scope and its children. Removal also implies that the current
  11108. * scope is eligible for garbage collection.
  11109. *
  11110. * The `$destroy()` is usually used by directives such as
  11111. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11112. * unrolling of the loop.
  11113. *
  11114. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11115. * Application code can register a `$destroy` event handler that will give it a chance to
  11116. * perform any necessary cleanup.
  11117. *
  11118. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11119. * clean up DOM bindings before an element is removed from the DOM.
  11120. */
  11121. $destroy: function() {
  11122. // we can't destroy the root scope or a scope that has been already destroyed
  11123. if (this.$$destroyed) return;
  11124. var parent = this.$parent;
  11125. this.$broadcast('$destroy');
  11126. this.$$destroyed = true;
  11127. if (this === $rootScope) return;
  11128. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11129. // sever all the references to parent scopes (after this cleanup, the current scope should
  11130. // not be retained by any of our references and should be eligible for garbage collection)
  11131. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11132. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11133. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11134. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11135. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11136. // and inline caches.
  11137. //
  11138. // see:
  11139. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11140. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11141. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11142. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11143. this.$$childTail = this.$root = null;
  11144. // don't reset these to null in case some async task tries to register a listener/watch/task
  11145. this.$$listeners = {};
  11146. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11147. // prevent NPEs since these methods have references to properties we nulled out
  11148. this.$destroy = this.$digest = this.$apply = noop;
  11149. this.$on = this.$watch = function() { return noop; };
  11150. },
  11151. /**
  11152. * @ngdoc method
  11153. * @name $rootScope.Scope#$eval
  11154. * @function
  11155. *
  11156. * @description
  11157. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11158. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11159. * expressions.
  11160. *
  11161. * # Example
  11162. * ```js
  11163. var scope = ng.$rootScope.Scope();
  11164. scope.a = 1;
  11165. scope.b = 2;
  11166. expect(scope.$eval('a+b')).toEqual(3);
  11167. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11168. * ```
  11169. *
  11170. * @param {(string|function())=} expression An angular expression to be executed.
  11171. *
  11172. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11173. * - `function(scope)`: execute the function with the current `scope` parameter.
  11174. *
  11175. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11176. * @returns {*} The result of evaluating the expression.
  11177. */
  11178. $eval: function(expr, locals) {
  11179. return $parse(expr)(this, locals);
  11180. },
  11181. /**
  11182. * @ngdoc method
  11183. * @name $rootScope.Scope#$evalAsync
  11184. * @function
  11185. *
  11186. * @description
  11187. * Executes the expression on the current scope at a later point in time.
  11188. *
  11189. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11190. * that:
  11191. *
  11192. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11193. * rendering).
  11194. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11195. * `expression` execution.
  11196. *
  11197. * Any exceptions from the execution of the expression are forwarded to the
  11198. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11199. *
  11200. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11201. * will be scheduled. However, it is encouraged to always call code that changes the model
  11202. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11203. *
  11204. * @param {(string|function())=} expression An angular expression to be executed.
  11205. *
  11206. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11207. * - `function(scope)`: execute the function with the current `scope` parameter.
  11208. *
  11209. */
  11210. $evalAsync: function(expr) {
  11211. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11212. // task also schedule async auto-flush
  11213. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11214. $browser.defer(function() {
  11215. if ($rootScope.$$asyncQueue.length) {
  11216. $rootScope.$digest();
  11217. }
  11218. });
  11219. }
  11220. this.$$asyncQueue.push({scope: this, expression: expr});
  11221. },
  11222. $$postDigest : function(fn) {
  11223. this.$$postDigestQueue.push(fn);
  11224. },
  11225. /**
  11226. * @ngdoc method
  11227. * @name $rootScope.Scope#$apply
  11228. * @function
  11229. *
  11230. * @description
  11231. * `$apply()` is used to execute an expression in angular from outside of the angular
  11232. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11233. * Because we are calling into the angular framework we need to perform proper scope life
  11234. * cycle of {@link ng.$exceptionHandler exception handling},
  11235. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11236. *
  11237. * ## Life cycle
  11238. *
  11239. * # Pseudo-Code of `$apply()`
  11240. * ```js
  11241. function $apply(expr) {
  11242. try {
  11243. return $eval(expr);
  11244. } catch (e) {
  11245. $exceptionHandler(e);
  11246. } finally {
  11247. $root.$digest();
  11248. }
  11249. }
  11250. * ```
  11251. *
  11252. *
  11253. * Scope's `$apply()` method transitions through the following stages:
  11254. *
  11255. * 1. The {@link guide/expression expression} is executed using the
  11256. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11257. * 2. Any exceptions from the execution of the expression are forwarded to the
  11258. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11259. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11260. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11261. *
  11262. *
  11263. * @param {(string|function())=} exp An angular expression to be executed.
  11264. *
  11265. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11266. * - `function(scope)`: execute the function with current `scope` parameter.
  11267. *
  11268. * @returns {*} The result of evaluating the expression.
  11269. */
  11270. $apply: function(expr) {
  11271. try {
  11272. beginPhase('$apply');
  11273. return this.$eval(expr);
  11274. } catch (e) {
  11275. $exceptionHandler(e);
  11276. } finally {
  11277. clearPhase();
  11278. try {
  11279. $rootScope.$digest();
  11280. } catch (e) {
  11281. $exceptionHandler(e);
  11282. throw e;
  11283. }
  11284. }
  11285. },
  11286. /**
  11287. * @ngdoc method
  11288. * @name $rootScope.Scope#$on
  11289. * @function
  11290. *
  11291. * @description
  11292. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11293. * discussion of event life cycle.
  11294. *
  11295. * The event listener function format is: `function(event, args...)`. The `event` object
  11296. * passed into the listener has the following attributes:
  11297. *
  11298. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11299. * `$broadcast`-ed.
  11300. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11301. * - `name` - `{string}`: name of the event.
  11302. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11303. * further event propagation (available only for events that were `$emit`-ed).
  11304. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11305. * to true.
  11306. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11307. *
  11308. * @param {string} name Event name to listen on.
  11309. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11310. * @returns {function()} Returns a deregistration function for this listener.
  11311. */
  11312. $on: function(name, listener) {
  11313. var namedListeners = this.$$listeners[name];
  11314. if (!namedListeners) {
  11315. this.$$listeners[name] = namedListeners = [];
  11316. }
  11317. namedListeners.push(listener);
  11318. var current = this;
  11319. do {
  11320. if (!current.$$listenerCount[name]) {
  11321. current.$$listenerCount[name] = 0;
  11322. }
  11323. current.$$listenerCount[name]++;
  11324. } while ((current = current.$parent));
  11325. var self = this;
  11326. return function() {
  11327. namedListeners[indexOf(namedListeners, listener)] = null;
  11328. decrementListenerCount(self, 1, name);
  11329. };
  11330. },
  11331. /**
  11332. * @ngdoc method
  11333. * @name $rootScope.Scope#$emit
  11334. * @function
  11335. *
  11336. * @description
  11337. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11338. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11339. *
  11340. * The event life cycle starts at the scope on which `$emit` was called. All
  11341. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11342. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11343. * registered listeners along the way. The event will stop propagating if one of the listeners
  11344. * cancels it.
  11345. *
  11346. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11347. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11348. *
  11349. * @param {string} name Event name to emit.
  11350. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11351. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11352. */
  11353. $emit: function(name, args) {
  11354. var empty = [],
  11355. namedListeners,
  11356. scope = this,
  11357. stopPropagation = false,
  11358. event = {
  11359. name: name,
  11360. targetScope: scope,
  11361. stopPropagation: function() {stopPropagation = true;},
  11362. preventDefault: function() {
  11363. event.defaultPrevented = true;
  11364. },
  11365. defaultPrevented: false
  11366. },
  11367. listenerArgs = concat([event], arguments, 1),
  11368. i, length;
  11369. do {
  11370. namedListeners = scope.$$listeners[name] || empty;
  11371. event.currentScope = scope;
  11372. for (i=0, length=namedListeners.length; i<length; i++) {
  11373. // if listeners were deregistered, defragment the array
  11374. if (!namedListeners[i]) {
  11375. namedListeners.splice(i, 1);
  11376. i--;
  11377. length--;
  11378. continue;
  11379. }
  11380. try {
  11381. //allow all listeners attached to the current scope to run
  11382. namedListeners[i].apply(null, listenerArgs);
  11383. } catch (e) {
  11384. $exceptionHandler(e);
  11385. }
  11386. }
  11387. //if any listener on the current scope stops propagation, prevent bubbling
  11388. if (stopPropagation) return event;
  11389. //traverse upwards
  11390. scope = scope.$parent;
  11391. } while (scope);
  11392. return event;
  11393. },
  11394. /**
  11395. * @ngdoc method
  11396. * @name $rootScope.Scope#$broadcast
  11397. * @function
  11398. *
  11399. * @description
  11400. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11401. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11402. *
  11403. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11404. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11405. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11406. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11407. *
  11408. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11409. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11410. *
  11411. * @param {string} name Event name to broadcast.
  11412. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11413. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11414. */
  11415. $broadcast: function(name, args) {
  11416. console.debug(name);
  11417. var target = this,
  11418. current = target,
  11419. next = target,
  11420. event = {
  11421. name: name,
  11422. targetScope: target,
  11423. preventDefault: function() {
  11424. event.defaultPrevented = true;
  11425. },
  11426. defaultPrevented: false
  11427. },
  11428. listenerArgs = concat([event], arguments, 1),
  11429. listeners, i, length;
  11430. //down while you can, then up and next sibling or up and next sibling until back at root
  11431. while ((current = next)) {
  11432. event.currentScope = current;
  11433. listeners = current.$$listeners[name] || [];
  11434. for (i=0, length = listeners.length; i<length; i++) {
  11435. // if listeners were deregistered, defragment the array
  11436. if (!listeners[i]) {
  11437. listeners.splice(i, 1);
  11438. i--;
  11439. length--;
  11440. continue;
  11441. }
  11442. try {
  11443. listeners[i].apply(null, listenerArgs);
  11444. } catch(e) {
  11445. $exceptionHandler(e);
  11446. }
  11447. }
  11448. // Insanity Warning: scope depth-first traversal
  11449. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11450. // this piece should be kept in sync with the traversal in $digest
  11451. // (though it differs due to having the extra check for $$listenerCount)
  11452. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11453. (current !== target && current.$$nextSibling)))) {
  11454. while(current !== target && !(next = current.$$nextSibling)) {
  11455. current = current.$parent;
  11456. }
  11457. }
  11458. }
  11459. return event;
  11460. }
  11461. };
  11462. var $rootScope = new Scope();
  11463. return $rootScope;
  11464. function beginPhase(phase) {
  11465. if ($rootScope.$$phase) {
  11466. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11467. }
  11468. $rootScope.$$phase = phase;
  11469. }
  11470. function clearPhase() {
  11471. $rootScope.$$phase = null;
  11472. }
  11473. function compileToFn(exp, name) {
  11474. var fn = $parse(exp);
  11475. assertArgFn(fn, name);
  11476. return fn;
  11477. }
  11478. function decrementListenerCount(current, count, name) {
  11479. do {
  11480. current.$$listenerCount[name] -= count;
  11481. if (current.$$listenerCount[name] === 0) {
  11482. delete current.$$listenerCount[name];
  11483. }
  11484. } while ((current = current.$parent));
  11485. }
  11486. /**
  11487. * function used as an initial value for watchers.
  11488. * because it's unique we can easily tell it apart from other values
  11489. */
  11490. function initWatchVal() {}
  11491. }];
  11492. }
  11493. /**
  11494. * @description
  11495. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11496. */
  11497. function $$SanitizeUriProvider() {
  11498. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11499. imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
  11500. /**
  11501. * @description
  11502. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11503. * urls during a[href] sanitization.
  11504. *
  11505. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11506. *
  11507. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11508. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11509. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11510. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11511. *
  11512. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11513. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11514. * chaining otherwise.
  11515. */
  11516. this.aHrefSanitizationWhitelist = function(regexp) {
  11517. if (isDefined(regexp)) {
  11518. aHrefSanitizationWhitelist = regexp;
  11519. return this;
  11520. }
  11521. return aHrefSanitizationWhitelist;
  11522. };
  11523. /**
  11524. * @description
  11525. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11526. * urls during img[src] sanitization.
  11527. *
  11528. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11529. *
  11530. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11531. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11532. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11533. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11534. *
  11535. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11536. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11537. * chaining otherwise.
  11538. */
  11539. this.imgSrcSanitizationWhitelist = function(regexp) {
  11540. if (isDefined(regexp)) {
  11541. imgSrcSanitizationWhitelist = regexp;
  11542. return this;
  11543. }
  11544. return imgSrcSanitizationWhitelist;
  11545. };
  11546. this.$get = function() {
  11547. return function sanitizeUri(uri, isImage) {
  11548. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11549. var normalizedVal;
  11550. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11551. if (!msie || msie >= 8 ) {
  11552. normalizedVal = urlResolve(uri).href;
  11553. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11554. return 'unsafe:'+normalizedVal;
  11555. }
  11556. }
  11557. return uri;
  11558. };
  11559. };
  11560. }
  11561. var $sceMinErr = minErr('$sce');
  11562. var SCE_CONTEXTS = {
  11563. HTML: 'html',
  11564. CSS: 'css',
  11565. URL: 'url',
  11566. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11567. // url. (e.g. ng-include, script src, templateUrl)
  11568. RESOURCE_URL: 'resourceUrl',
  11569. JS: 'js'
  11570. };
  11571. // Helper functions follow.
  11572. // Copied from:
  11573. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11574. // Prereq: s is a string.
  11575. function escapeForRegexp(s) {
  11576. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11577. replace(/\x08/g, '\\x08');
  11578. }
  11579. function adjustMatcher(matcher) {
  11580. if (matcher === 'self') {
  11581. return matcher;
  11582. } else if (isString(matcher)) {
  11583. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11584. // '*' matches any character except those from the set ':/.?&'.
  11585. // '**' matches any character (like .* in a RegExp).
  11586. // More than 2 *'s raises an error as it's ill defined.
  11587. if (matcher.indexOf('***') > -1) {
  11588. throw $sceMinErr('iwcard',
  11589. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11590. }
  11591. matcher = escapeForRegexp(matcher).
  11592. replace('\\*\\*', '.*').
  11593. replace('\\*', '[^:/.?&;]*');
  11594. return new RegExp('^' + matcher + '$');
  11595. } else if (isRegExp(matcher)) {
  11596. // The only other type of matcher allowed is a Regexp.
  11597. // Match entire URL / disallow partial matches.
  11598. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11599. return new RegExp('^' + matcher.source + '$');
  11600. } else {
  11601. throw $sceMinErr('imatcher',
  11602. 'Matchers may only be "self", string patterns or RegExp objects');
  11603. }
  11604. }
  11605. function adjustMatchers(matchers) {
  11606. var adjustedMatchers = [];
  11607. if (isDefined(matchers)) {
  11608. forEach(matchers, function(matcher) {
  11609. adjustedMatchers.push(adjustMatcher(matcher));
  11610. });
  11611. }
  11612. return adjustedMatchers;
  11613. }
  11614. /**
  11615. * @ngdoc service
  11616. * @name $sceDelegate
  11617. * @function
  11618. *
  11619. * @description
  11620. *
  11621. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11622. * Contextual Escaping (SCE)} services to AngularJS.
  11623. *
  11624. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11625. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11626. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11627. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11628. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11629. *
  11630. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11631. *
  11632. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  11633. * can override it completely to change the behavior of `$sce`, the common case would
  11634. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  11635. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  11636. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  11637. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  11638. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11639. */
  11640. /**
  11641. * @ngdoc provider
  11642. * @name $sceDelegateProvider
  11643. * @description
  11644. *
  11645. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11646. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11647. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11648. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11649. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11650. *
  11651. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11652. * Strict Contextual Escaping (SCE)}.
  11653. *
  11654. * **Example**: Consider the following case. <a name="example"></a>
  11655. *
  11656. * - your app is hosted at url `http://myapp.example.com/`
  11657. * - but some of your templates are hosted on other domains you control such as
  11658. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  11659. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  11660. *
  11661. * Here is what a secure configuration for this scenario might look like:
  11662. *
  11663. * <pre class="prettyprint">
  11664. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  11665. * $sceDelegateProvider.resourceUrlWhitelist([
  11666. * // Allow same origin resource loads.
  11667. * 'self',
  11668. * // Allow loading from our assets domain. Notice the difference between * and **.
  11669. * 'http://srv*.assets.example.com/**']);
  11670. *
  11671. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  11672. * $sceDelegateProvider.resourceUrlBlacklist([
  11673. * 'http://myapp.example.com/clickThru**']);
  11674. * });
  11675. * </pre>
  11676. */
  11677. function $SceDelegateProvider() {
  11678. this.SCE_CONTEXTS = SCE_CONTEXTS;
  11679. // Resource URLs can also be trusted by policy.
  11680. var resourceUrlWhitelist = ['self'],
  11681. resourceUrlBlacklist = [];
  11682. /**
  11683. * @ngdoc method
  11684. * @name $sceDelegateProvider#resourceUrlWhitelist
  11685. * @function
  11686. *
  11687. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  11688. * provided. This must be an array or null. A snapshot of this array is used so further
  11689. * changes to the array are ignored.
  11690. *
  11691. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11692. * allowed in this array.
  11693. *
  11694. * Note: **an empty whitelist array will block all URLs**!
  11695. *
  11696. * @return {Array} the currently set whitelist array.
  11697. *
  11698. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  11699. * same origin resource requests.
  11700. *
  11701. * @description
  11702. * Sets/Gets the whitelist of trusted resource URLs.
  11703. */
  11704. this.resourceUrlWhitelist = function (value) {
  11705. if (arguments.length) {
  11706. resourceUrlWhitelist = adjustMatchers(value);
  11707. }
  11708. return resourceUrlWhitelist;
  11709. };
  11710. /**
  11711. * @ngdoc method
  11712. * @name $sceDelegateProvider#resourceUrlBlacklist
  11713. * @function
  11714. *
  11715. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  11716. * provided. This must be an array or null. A snapshot of this array is used so further
  11717. * changes to the array are ignored.
  11718. *
  11719. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11720. * allowed in this array.
  11721. *
  11722. * The typical usage for the blacklist is to **block
  11723. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  11724. * these would otherwise be trusted but actually return content from the redirected domain.
  11725. *
  11726. * Finally, **the blacklist overrides the whitelist** and has the final say.
  11727. *
  11728. * @return {Array} the currently set blacklist array.
  11729. *
  11730. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  11731. * is no blacklist.)
  11732. *
  11733. * @description
  11734. * Sets/Gets the blacklist of trusted resource URLs.
  11735. */
  11736. this.resourceUrlBlacklist = function (value) {
  11737. if (arguments.length) {
  11738. resourceUrlBlacklist = adjustMatchers(value);
  11739. }
  11740. return resourceUrlBlacklist;
  11741. };
  11742. this.$get = ['$injector', function($injector) {
  11743. var htmlSanitizer = function htmlSanitizer(html) {
  11744. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11745. };
  11746. if ($injector.has('$sanitize')) {
  11747. htmlSanitizer = $injector.get('$sanitize');
  11748. }
  11749. function matchUrl(matcher, parsedUrl) {
  11750. if (matcher === 'self') {
  11751. return urlIsSameOrigin(parsedUrl);
  11752. } else {
  11753. // definitely a regex. See adjustMatchers()
  11754. return !!matcher.exec(parsedUrl.href);
  11755. }
  11756. }
  11757. function isResourceUrlAllowedByPolicy(url) {
  11758. var parsedUrl = urlResolve(url.toString());
  11759. var i, n, allowed = false;
  11760. // Ensure that at least one item from the whitelist allows this url.
  11761. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  11762. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  11763. allowed = true;
  11764. break;
  11765. }
  11766. }
  11767. if (allowed) {
  11768. // Ensure that no item from the blacklist blocked this url.
  11769. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  11770. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  11771. allowed = false;
  11772. break;
  11773. }
  11774. }
  11775. }
  11776. return allowed;
  11777. }
  11778. function generateHolderType(Base) {
  11779. var holderType = function TrustedValueHolderType(trustedValue) {
  11780. this.$$unwrapTrustedValue = function() {
  11781. return trustedValue;
  11782. };
  11783. };
  11784. if (Base) {
  11785. holderType.prototype = new Base();
  11786. }
  11787. holderType.prototype.valueOf = function sceValueOf() {
  11788. return this.$$unwrapTrustedValue();
  11789. };
  11790. holderType.prototype.toString = function sceToString() {
  11791. return this.$$unwrapTrustedValue().toString();
  11792. };
  11793. return holderType;
  11794. }
  11795. var trustedValueHolderBase = generateHolderType(),
  11796. byType = {};
  11797. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  11798. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  11799. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  11800. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  11801. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  11802. /**
  11803. * @ngdoc method
  11804. * @name $sceDelegate#trustAs
  11805. *
  11806. * @description
  11807. * Returns an object that is trusted by angular for use in specified strict
  11808. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  11809. * attribute interpolation, any dom event binding attribute interpolation
  11810. * such as for onclick, etc.) that uses the provided value.
  11811. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  11812. *
  11813. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11814. * resourceUrl, html, js and css.
  11815. * @param {*} value The value that that should be considered trusted/safe.
  11816. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11817. * where Angular expects a $sce.trustAs() return value.
  11818. */
  11819. function trustAs(type, trustedValue) {
  11820. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11821. if (!Constructor) {
  11822. throw $sceMinErr('icontext',
  11823. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  11824. type, trustedValue);
  11825. }
  11826. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  11827. return trustedValue;
  11828. }
  11829. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  11830. // mutable objects, we ensure here that the value passed in is actually a string.
  11831. if (typeof trustedValue !== 'string') {
  11832. throw $sceMinErr('itype',
  11833. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  11834. type);
  11835. }
  11836. return new Constructor(trustedValue);
  11837. }
  11838. /**
  11839. * @ngdoc method
  11840. * @name $sceDelegate#valueOf
  11841. *
  11842. * @description
  11843. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  11844. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  11845. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  11846. *
  11847. * If the passed parameter is not a value that had been returned by {@link
  11848. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  11849. *
  11850. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  11851. * call or anything else.
  11852. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  11853. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  11854. * `value` unchanged.
  11855. */
  11856. function valueOf(maybeTrusted) {
  11857. if (maybeTrusted instanceof trustedValueHolderBase) {
  11858. return maybeTrusted.$$unwrapTrustedValue();
  11859. } else {
  11860. return maybeTrusted;
  11861. }
  11862. }
  11863. /**
  11864. * @ngdoc method
  11865. * @name $sceDelegate#getTrusted
  11866. *
  11867. * @description
  11868. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  11869. * returns the originally supplied value if the queried context type is a supertype of the
  11870. * created type. If this condition isn't satisfied, throws an exception.
  11871. *
  11872. * @param {string} type The kind of context in which this value is to be used.
  11873. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  11874. * `$sceDelegate.trustAs`} call.
  11875. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  11876. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  11877. */
  11878. function getTrusted(type, maybeTrusted) {
  11879. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  11880. return maybeTrusted;
  11881. }
  11882. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11883. if (constructor && maybeTrusted instanceof constructor) {
  11884. return maybeTrusted.$$unwrapTrustedValue();
  11885. }
  11886. // If we get here, then we may only take one of two actions.
  11887. // 1. sanitize the value for the requested type, or
  11888. // 2. throw an exception.
  11889. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  11890. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  11891. return maybeTrusted;
  11892. } else {
  11893. throw $sceMinErr('insecurl',
  11894. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  11895. maybeTrusted.toString());
  11896. }
  11897. } else if (type === SCE_CONTEXTS.HTML) {
  11898. return htmlSanitizer(maybeTrusted);
  11899. }
  11900. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11901. }
  11902. return { trustAs: trustAs,
  11903. getTrusted: getTrusted,
  11904. valueOf: valueOf };
  11905. }];
  11906. }
  11907. /**
  11908. * @ngdoc provider
  11909. * @name $sceProvider
  11910. * @description
  11911. *
  11912. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  11913. * - enable/disable Strict Contextual Escaping (SCE) in a module
  11914. * - override the default implementation with a custom delegate
  11915. *
  11916. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  11917. */
  11918. /* jshint maxlen: false*/
  11919. /**
  11920. * @ngdoc service
  11921. * @name $sce
  11922. * @function
  11923. *
  11924. * @description
  11925. *
  11926. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  11927. *
  11928. * # Strict Contextual Escaping
  11929. *
  11930. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  11931. * contexts to result in a value that is marked as safe to use for that context. One example of
  11932. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  11933. * to these contexts as privileged or SCE contexts.
  11934. *
  11935. * As of version 1.2, Angular ships with SCE enabled by default.
  11936. *
  11937. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  11938. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  11939. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  11940. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  11941. * to the top of your HTML document.
  11942. *
  11943. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  11944. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  11945. *
  11946. * Here's an example of a binding in a privileged context:
  11947. *
  11948. * <pre class="prettyprint">
  11949. * <input ng-model="userHtml">
  11950. * <div ng-bind-html="userHtml">
  11951. * </pre>
  11952. *
  11953. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  11954. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  11955. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  11956. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  11957. * security vulnerabilities.)
  11958. *
  11959. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  11960. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  11961. *
  11962. * How would you ensure that every place that used these types of bindings was bound to a value that
  11963. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  11964. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  11965. * properties/fields and forgot to update the binding to the sanitized value?
  11966. *
  11967. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  11968. * determine that something explicitly says it's safe to use a value for binding in that
  11969. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  11970. * for those values that you can easily tell are safe - because they were received from your server,
  11971. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  11972. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  11973. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  11974. *
  11975. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  11976. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  11977. * obtain values that will be accepted by SCE / privileged contexts.
  11978. *
  11979. *
  11980. * ## How does it work?
  11981. *
  11982. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  11983. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  11984. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  11985. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  11986. *
  11987. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  11988. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  11989. * simplified):
  11990. *
  11991. * <pre class="prettyprint">
  11992. * var ngBindHtmlDirective = ['$sce', function($sce) {
  11993. * return function(scope, element, attr) {
  11994. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  11995. * element.html(value || '');
  11996. * });
  11997. * };
  11998. * }];
  11999. * </pre>
  12000. *
  12001. * ## Impact on loading templates
  12002. *
  12003. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12004. * `templateUrl`'s specified by {@link guide/directive directives}.
  12005. *
  12006. * By default, Angular only loads templates from the same domain and protocol as the application
  12007. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12008. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12009. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12010. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12011. *
  12012. * *Please note*:
  12013. * The browser's
  12014. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12015. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12016. * policy apply in addition to this and may further restrict whether the template is successfully
  12017. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12018. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12019. * browsers.
  12020. *
  12021. * ## This feels like too much overhead for the developer?
  12022. *
  12023. * It's important to remember that SCE only applies to interpolation expressions.
  12024. *
  12025. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12026. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12027. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12028. *
  12029. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12030. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12031. *
  12032. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12033. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12034. * It blocks loading templates from other domains or loading templates over http from an https
  12035. * served document. You can change these by setting your own custom {@link
  12036. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12037. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12038. *
  12039. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12040. * application that's secure and can be audited to verify that with much more ease than bolting
  12041. * security onto an application later.
  12042. *
  12043. * <a name="contexts"></a>
  12044. * ## What trusted context types are supported?
  12045. *
  12046. * | Context | Notes |
  12047. * |---------------------|----------------|
  12048. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
  12049. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12050. * | `$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. |
  12051. * | `$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. |
  12052. * | `$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. |
  12053. *
  12054. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12055. *
  12056. * Each element in these arrays must be one of the following:
  12057. *
  12058. * - **'self'**
  12059. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12060. * domain** as the application document using the **same protocol**.
  12061. * - **String** (except the special value `'self'`)
  12062. * - The string is matched against the full *normalized / absolute URL* of the resource
  12063. * being tested (substring matches are not good enough.)
  12064. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12065. * match themselves.
  12066. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12067. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12068. * in a whitelist.
  12069. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12070. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12071. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12072. * not have been the intention.) It's usage at the very end of the path is ok. (e.g.
  12073. * http://foo.example.com/templates/**).
  12074. * - **RegExp** (*see caveat below*)
  12075. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12076. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12077. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12078. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12079. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12080. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12081. * is highly recommended to use the string patterns and only fall back to regular expressions
  12082. * if they as a last resort.
  12083. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12084. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12085. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12086. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12087. * - If you are generating your JavaScript from some other templating engine (not
  12088. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12089. * remember to escape your regular expression (and be aware that you might need more than
  12090. * one level of escaping depending on your templating engine and the way you interpolated
  12091. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12092. * enough before coding your own. e.g. Ruby has
  12093. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12094. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12095. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12096. * Closure library's [goog.string.regExpEscape(s)](
  12097. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12098. *
  12099. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12100. *
  12101. * ## Show me an example using SCE.
  12102. *
  12103. * @example
  12104. <example module="mySceApp" deps="angular-sanitize.js">
  12105. <file name="index.html">
  12106. <div ng-controller="myAppController as myCtrl">
  12107. <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12108. <b>User comments</b><br>
  12109. By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12110. $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12111. exploit.
  12112. <div class="well">
  12113. <div ng-repeat="userComment in myCtrl.userComments">
  12114. <b>{{userComment.name}}</b>:
  12115. <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12116. <br>
  12117. </div>
  12118. </div>
  12119. </div>
  12120. </file>
  12121. <file name="script.js">
  12122. var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12123. mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12124. var self = this;
  12125. $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12126. self.userComments = userComments;
  12127. });
  12128. self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12129. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12130. 'sanitization.&quot;">Hover over this text.</span>');
  12131. });
  12132. </file>
  12133. <file name="test_data.json">
  12134. [
  12135. { "name": "Alice",
  12136. "htmlComment":
  12137. "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12138. },
  12139. { "name": "Bob",
  12140. "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12141. }
  12142. ]
  12143. </file>
  12144. <file name="protractor.js" type="protractor">
  12145. describe('SCE doc demo', function() {
  12146. it('should sanitize untrusted values', function() {
  12147. expect(element(by.css('.htmlComment')).getInnerHtml())
  12148. .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12149. });
  12150. it('should NOT sanitize explicitly trusted values', function() {
  12151. expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12152. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12153. 'sanitization.&quot;">Hover over this text.</span>');
  12154. });
  12155. });
  12156. </file>
  12157. </example>
  12158. *
  12159. *
  12160. *
  12161. * ## Can I disable SCE completely?
  12162. *
  12163. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12164. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12165. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12166. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12167. * you're migrating them a module at a time.
  12168. *
  12169. * That said, here's how you can completely disable SCE:
  12170. *
  12171. * <pre class="prettyprint">
  12172. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12173. * // Completely disable SCE. For demonstration purposes only!
  12174. * // Do not use in new projects.
  12175. * $sceProvider.enabled(false);
  12176. * });
  12177. * </pre>
  12178. *
  12179. */
  12180. /* jshint maxlen: 100 */
  12181. function $SceProvider() {
  12182. var enabled = true;
  12183. /**
  12184. * @ngdoc method
  12185. * @name $sceProvider#enabled
  12186. * @function
  12187. *
  12188. * @param {boolean=} value If provided, then enables/disables SCE.
  12189. * @return {boolean} true if SCE is enabled, false otherwise.
  12190. *
  12191. * @description
  12192. * Enables/disables SCE and returns the current value.
  12193. */
  12194. this.enabled = function (value) {
  12195. if (arguments.length) {
  12196. enabled = !!value;
  12197. }
  12198. return enabled;
  12199. };
  12200. /* Design notes on the default implementation for SCE.
  12201. *
  12202. * The API contract for the SCE delegate
  12203. * -------------------------------------
  12204. * The SCE delegate object must provide the following 3 methods:
  12205. *
  12206. * - trustAs(contextEnum, value)
  12207. * This method is used to tell the SCE service that the provided value is OK to use in the
  12208. * contexts specified by contextEnum. It must return an object that will be accepted by
  12209. * getTrusted() for a compatible contextEnum and return this value.
  12210. *
  12211. * - valueOf(value)
  12212. * For values that were not produced by trustAs(), return them as is. For values that were
  12213. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12214. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12215. * such a value.
  12216. *
  12217. * - getTrusted(contextEnum, value)
  12218. * This function should return the a value that is safe to use in the context specified by
  12219. * contextEnum or throw and exception otherwise.
  12220. *
  12221. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12222. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12223. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12224. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12225. * return the same object passed in if it was found in the registry under a compatible context or
  12226. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12227. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12228. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12229. *
  12230. *
  12231. * A note on the inheritance model for SCE contexts
  12232. * ------------------------------------------------
  12233. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12234. * is purely an implementation details.
  12235. *
  12236. * The contract is simply this:
  12237. *
  12238. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12239. * will also succeed.
  12240. *
  12241. * Inheritance happens to capture this in a natural way. In some future, we
  12242. * may not use inheritance anymore. That is OK because no code outside of
  12243. * sce.js and sceSpecs.js would need to be aware of this detail.
  12244. */
  12245. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12246. $parse, $sniffer, $sceDelegate) {
  12247. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12248. // the "expression(javascript expression)" syntax which is insecure.
  12249. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12250. throw $sceMinErr('iequirks',
  12251. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12252. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12253. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12254. }
  12255. var sce = copy(SCE_CONTEXTS);
  12256. /**
  12257. * @ngdoc method
  12258. * @name $sce#isEnabled
  12259. * @function
  12260. *
  12261. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12262. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12263. *
  12264. * @description
  12265. * Returns a boolean indicating if SCE is enabled.
  12266. */
  12267. sce.isEnabled = function () {
  12268. return enabled;
  12269. };
  12270. sce.trustAs = $sceDelegate.trustAs;
  12271. sce.getTrusted = $sceDelegate.getTrusted;
  12272. sce.valueOf = $sceDelegate.valueOf;
  12273. if (!enabled) {
  12274. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12275. sce.valueOf = identity;
  12276. }
  12277. /**
  12278. * @ngdoc method
  12279. * @name $sce#parse
  12280. *
  12281. * @description
  12282. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12283. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12284. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12285. * *result*)}
  12286. *
  12287. * @param {string} type The kind of SCE context in which this result will be used.
  12288. * @param {string} expression String expression to compile.
  12289. * @returns {function(context, locals)} a function which represents the compiled expression:
  12290. *
  12291. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12292. * are evaluated against (typically a scope object).
  12293. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12294. * `context`.
  12295. */
  12296. sce.parseAs = function sceParseAs(type, expr) {
  12297. var parsed = $parse(expr);
  12298. if (parsed.literal && parsed.constant) {
  12299. return parsed;
  12300. } else {
  12301. return function sceParseAsTrusted(self, locals) {
  12302. return sce.getTrusted(type, parsed(self, locals));
  12303. };
  12304. }
  12305. };
  12306. /**
  12307. * @ngdoc method
  12308. * @name $sce#trustAs
  12309. *
  12310. * @description
  12311. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12312. * returns an object that is trusted by angular for use in specified strict contextual
  12313. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12314. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12315. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12316. * escaping.
  12317. *
  12318. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12319. * resource_url, html, js and css.
  12320. * @param {*} value The value that that should be considered trusted/safe.
  12321. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12322. * where Angular expects a $sce.trustAs() return value.
  12323. */
  12324. /**
  12325. * @ngdoc method
  12326. * @name $sce#trustAsHtml
  12327. *
  12328. * @description
  12329. * Shorthand method. `$sce.trustAsHtml(value)` →
  12330. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12331. *
  12332. * @param {*} value The value to trustAs.
  12333. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12334. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12335. * only accept expressions that are either literal constants or are the
  12336. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12337. */
  12338. /**
  12339. * @ngdoc method
  12340. * @name $sce#trustAsUrl
  12341. *
  12342. * @description
  12343. * Shorthand method. `$sce.trustAsUrl(value)` →
  12344. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12345. *
  12346. * @param {*} value The value to trustAs.
  12347. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12348. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12349. * only accept expressions that are either literal constants or are the
  12350. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12351. */
  12352. /**
  12353. * @ngdoc method
  12354. * @name $sce#trustAsResourceUrl
  12355. *
  12356. * @description
  12357. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12358. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12359. *
  12360. * @param {*} value The value to trustAs.
  12361. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12362. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12363. * only accept expressions that are either literal constants or are the return
  12364. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12365. */
  12366. /**
  12367. * @ngdoc method
  12368. * @name $sce#trustAsJs
  12369. *
  12370. * @description
  12371. * Shorthand method. `$sce.trustAsJs(value)` →
  12372. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12373. *
  12374. * @param {*} value The value to trustAs.
  12375. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12376. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12377. * only accept expressions that are either literal constants or are the
  12378. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12379. */
  12380. /**
  12381. * @ngdoc method
  12382. * @name $sce#getTrusted
  12383. *
  12384. * @description
  12385. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12386. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12387. * originally supplied value if the queried context type is a supertype of the created type.
  12388. * If this condition isn't satisfied, throws an exception.
  12389. *
  12390. * @param {string} type The kind of context in which this value is to be used.
  12391. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12392. * call.
  12393. * @returns {*} The value the was originally provided to
  12394. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12395. * Otherwise, throws an exception.
  12396. */
  12397. /**
  12398. * @ngdoc method
  12399. * @name $sce#getTrustedHtml
  12400. *
  12401. * @description
  12402. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12403. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12404. *
  12405. * @param {*} value The value to pass to `$sce.getTrusted`.
  12406. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12407. */
  12408. /**
  12409. * @ngdoc method
  12410. * @name $sce#getTrustedCss
  12411. *
  12412. * @description
  12413. * Shorthand method. `$sce.getTrustedCss(value)` →
  12414. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12415. *
  12416. * @param {*} value The value to pass to `$sce.getTrusted`.
  12417. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12418. */
  12419. /**
  12420. * @ngdoc method
  12421. * @name $sce#getTrustedUrl
  12422. *
  12423. * @description
  12424. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12425. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12426. *
  12427. * @param {*} value The value to pass to `$sce.getTrusted`.
  12428. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12429. */
  12430. /**
  12431. * @ngdoc method
  12432. * @name $sce#getTrustedResourceUrl
  12433. *
  12434. * @description
  12435. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12436. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12437. *
  12438. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12439. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12440. */
  12441. /**
  12442. * @ngdoc method
  12443. * @name $sce#getTrustedJs
  12444. *
  12445. * @description
  12446. * Shorthand method. `$sce.getTrustedJs(value)` →
  12447. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12448. *
  12449. * @param {*} value The value to pass to `$sce.getTrusted`.
  12450. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12451. */
  12452. /**
  12453. * @ngdoc method
  12454. * @name $sce#parseAsHtml
  12455. *
  12456. * @description
  12457. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12458. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12459. *
  12460. * @param {string} expression String expression to compile.
  12461. * @returns {function(context, locals)} a function which represents the compiled expression:
  12462. *
  12463. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12464. * are evaluated against (typically a scope object).
  12465. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12466. * `context`.
  12467. */
  12468. /**
  12469. * @ngdoc method
  12470. * @name $sce#parseAsCss
  12471. *
  12472. * @description
  12473. * Shorthand method. `$sce.parseAsCss(value)` →
  12474. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12475. *
  12476. * @param {string} expression String expression to compile.
  12477. * @returns {function(context, locals)} a function which represents the compiled expression:
  12478. *
  12479. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12480. * are evaluated against (typically a scope object).
  12481. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12482. * `context`.
  12483. */
  12484. /**
  12485. * @ngdoc method
  12486. * @name $sce#parseAsUrl
  12487. *
  12488. * @description
  12489. * Shorthand method. `$sce.parseAsUrl(value)` →
  12490. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12491. *
  12492. * @param {string} expression String expression to compile.
  12493. * @returns {function(context, locals)} a function which represents the compiled expression:
  12494. *
  12495. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12496. * are evaluated against (typically a scope object).
  12497. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12498. * `context`.
  12499. */
  12500. /**
  12501. * @ngdoc method
  12502. * @name $sce#parseAsResourceUrl
  12503. *
  12504. * @description
  12505. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12506. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12507. *
  12508. * @param {string} expression String expression to compile.
  12509. * @returns {function(context, locals)} a function which represents the compiled expression:
  12510. *
  12511. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12512. * are evaluated against (typically a scope object).
  12513. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12514. * `context`.
  12515. */
  12516. /**
  12517. * @ngdoc method
  12518. * @name $sce#parseAsJs
  12519. *
  12520. * @description
  12521. * Shorthand method. `$sce.parseAsJs(value)` →
  12522. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12523. *
  12524. * @param {string} expression String expression to compile.
  12525. * @returns {function(context, locals)} a function which represents the compiled expression:
  12526. *
  12527. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12528. * are evaluated against (typically a scope object).
  12529. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12530. * `context`.
  12531. */
  12532. // Shorthand delegations.
  12533. var parse = sce.parseAs,
  12534. getTrusted = sce.getTrusted,
  12535. trustAs = sce.trustAs;
  12536. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12537. var lName = lowercase(name);
  12538. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12539. return parse(enumValue, expr);
  12540. };
  12541. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12542. return getTrusted(enumValue, value);
  12543. };
  12544. sce[camelCase("trust_as_" + lName)] = function (value) {
  12545. return trustAs(enumValue, value);
  12546. };
  12547. });
  12548. return sce;
  12549. }];
  12550. }
  12551. /**
  12552. * !!! This is an undocumented "private" service !!!
  12553. *
  12554. * @name $sniffer
  12555. * @requires $window
  12556. * @requires $document
  12557. *
  12558. * @property {boolean} history Does the browser support html5 history api ?
  12559. * @property {boolean} hashchange Does the browser support hashchange event ?
  12560. * @property {boolean} transitions Does the browser support CSS transition events ?
  12561. * @property {boolean} animations Does the browser support CSS animation events ?
  12562. *
  12563. * @description
  12564. * This is very simple implementation of testing browser's features.
  12565. */
  12566. function $SnifferProvider() {
  12567. this.$get = ['$window', '$document', function($window, $document) {
  12568. var eventSupport = {},
  12569. android =
  12570. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12571. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12572. document = $document[0] || {},
  12573. documentMode = document.documentMode,
  12574. vendorPrefix,
  12575. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12576. bodyStyle = document.body && document.body.style,
  12577. transitions = false,
  12578. animations = false,
  12579. match;
  12580. if (bodyStyle) {
  12581. for(var prop in bodyStyle) {
  12582. if(match = vendorRegex.exec(prop)) {
  12583. vendorPrefix = match[0];
  12584. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12585. break;
  12586. }
  12587. }
  12588. if(!vendorPrefix) {
  12589. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12590. }
  12591. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12592. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12593. if (android && (!transitions||!animations)) {
  12594. transitions = isString(document.body.style.webkitTransition);
  12595. animations = isString(document.body.style.webkitAnimation);
  12596. }
  12597. }
  12598. return {
  12599. // Android has history.pushState, but it does not update location correctly
  12600. // so let's not use the history API at all.
  12601. // http://code.google.com/p/android/issues/detail?id=17471
  12602. // https://github.com/angular/angular.js/issues/904
  12603. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12604. // so let's not use the history API also
  12605. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12606. // jshint -W018
  12607. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12608. // jshint +W018
  12609. hashchange: 'onhashchange' in $window &&
  12610. // IE8 compatible mode lies
  12611. (!documentMode || documentMode > 7),
  12612. hasEvent: function(event) {
  12613. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12614. // it. In particular the event is not fired when backspace or delete key are pressed or
  12615. // when cut operation is performed.
  12616. if (event == 'input' && msie == 9) return false;
  12617. if (isUndefined(eventSupport[event])) {
  12618. var divElm = document.createElement('div');
  12619. eventSupport[event] = 'on' + event in divElm;
  12620. }
  12621. return eventSupport[event];
  12622. },
  12623. csp: csp(),
  12624. vendorPrefix: vendorPrefix,
  12625. transitions : transitions,
  12626. animations : animations,
  12627. android: android,
  12628. msie : msie,
  12629. msieDocumentMode: documentMode
  12630. };
  12631. }];
  12632. }
  12633. function $TimeoutProvider() {
  12634. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12635. function($rootScope, $browser, $q, $exceptionHandler) {
  12636. var deferreds = {};
  12637. /**
  12638. * @ngdoc service
  12639. * @name $timeout
  12640. *
  12641. * @description
  12642. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12643. * block and delegates any exceptions to
  12644. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12645. *
  12646. * The return value of registering a timeout function is a promise, which will be resolved when
  12647. * the timeout is reached and the timeout function is executed.
  12648. *
  12649. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  12650. *
  12651. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  12652. * synchronously flush the queue of deferred functions.
  12653. *
  12654. * @param {function()} fn A function, whose execution should be delayed.
  12655. * @param {number=} [delay=0] Delay in milliseconds.
  12656. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12657. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12658. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  12659. * promise will be resolved with is the return value of the `fn` function.
  12660. *
  12661. */
  12662. function timeout(fn, delay, invokeApply) {
  12663. var deferred = $q.defer(),
  12664. promise = deferred.promise,
  12665. skipApply = (isDefined(invokeApply) && !invokeApply),
  12666. timeoutId;
  12667. timeoutId = $browser.defer(function() {
  12668. try {
  12669. deferred.resolve(fn());
  12670. } catch(e) {
  12671. deferred.reject(e);
  12672. $exceptionHandler(e);
  12673. }
  12674. finally {
  12675. delete deferreds[promise.$$timeoutId];
  12676. }
  12677. if (!skipApply) $rootScope.$apply();
  12678. }, delay);
  12679. promise.$$timeoutId = timeoutId;
  12680. deferreds[timeoutId] = deferred;
  12681. return promise;
  12682. }
  12683. /**
  12684. * @ngdoc method
  12685. * @name $timeout#cancel
  12686. *
  12687. * @description
  12688. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  12689. * resolved with a rejection.
  12690. *
  12691. * @param {Promise=} promise Promise returned by the `$timeout` function.
  12692. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  12693. * canceled.
  12694. */
  12695. timeout.cancel = function(promise) {
  12696. if (promise && promise.$$timeoutId in deferreds) {
  12697. deferreds[promise.$$timeoutId].reject('canceled');
  12698. delete deferreds[promise.$$timeoutId];
  12699. return $browser.defer.cancel(promise.$$timeoutId);
  12700. }
  12701. return false;
  12702. };
  12703. return timeout;
  12704. }];
  12705. }
  12706. // NOTE: The usage of window and document instead of $window and $document here is
  12707. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  12708. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  12709. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  12710. // doesn't know about mocked locations and resolves URLs to the real document - which is
  12711. // exactly the behavior needed here. There is little value is mocking these out for this
  12712. // service.
  12713. var urlParsingNode = document.createElement("a");
  12714. var originUrl = urlResolve(window.location.href, true);
  12715. /**
  12716. *
  12717. * Implementation Notes for non-IE browsers
  12718. * ----------------------------------------
  12719. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  12720. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  12721. * URL will be resolved into an absolute URL in the context of the application document.
  12722. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  12723. * properties are all populated to reflect the normalized URL. This approach has wide
  12724. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  12725. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12726. *
  12727. * Implementation Notes for IE
  12728. * ---------------------------
  12729. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  12730. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  12731. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  12732. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  12733. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  12734. * properties such as protocol, hostname, port, etc.
  12735. *
  12736. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  12737. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  12738. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  12739. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  12740. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  12741. * method and IE < 8 is unsupported.
  12742. *
  12743. * References:
  12744. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  12745. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12746. * http://url.spec.whatwg.org/#urlutils
  12747. * https://github.com/angular/angular.js/pull/2902
  12748. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  12749. *
  12750. * @function
  12751. * @param {string} url The URL to be parsed.
  12752. * @description Normalizes and parses a URL.
  12753. * @returns {object} Returns the normalized URL as a dictionary.
  12754. *
  12755. * | member name | Description |
  12756. * |---------------|----------------|
  12757. * | href | A normalized version of the provided URL if it was not an absolute URL |
  12758. * | protocol | The protocol including the trailing colon |
  12759. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  12760. * | search | The search params, minus the question mark |
  12761. * | hash | The hash string, minus the hash symbol
  12762. * | hostname | The hostname
  12763. * | port | The port, without ":"
  12764. * | pathname | The pathname, beginning with "/"
  12765. *
  12766. */
  12767. function urlResolve(url, base) {
  12768. var href = url;
  12769. if (msie) {
  12770. // Normalize before parse. Refer Implementation Notes on why this is
  12771. // done in two steps on IE.
  12772. urlParsingNode.setAttribute("href", href);
  12773. href = urlParsingNode.href;
  12774. }
  12775. urlParsingNode.setAttribute('href', href);
  12776. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  12777. return {
  12778. href: urlParsingNode.href,
  12779. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  12780. host: urlParsingNode.host,
  12781. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  12782. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  12783. hostname: urlParsingNode.hostname,
  12784. port: urlParsingNode.port,
  12785. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  12786. ? urlParsingNode.pathname
  12787. : '/' + urlParsingNode.pathname
  12788. };
  12789. }
  12790. /**
  12791. * Parse a request URL and determine whether this is a same-origin request as the application document.
  12792. *
  12793. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  12794. * or a parsed URL object.
  12795. * @returns {boolean} Whether the request is for the same origin as the application document.
  12796. */
  12797. function urlIsSameOrigin(requestUrl) {
  12798. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  12799. return (parsed.protocol === originUrl.protocol &&
  12800. parsed.host === originUrl.host);
  12801. }
  12802. /**
  12803. * @ngdoc service
  12804. * @name $window
  12805. *
  12806. * @description
  12807. * A reference to the browser's `window` object. While `window`
  12808. * is globally available in JavaScript, it causes testability problems, because
  12809. * it is a global variable. In angular we always refer to it through the
  12810. * `$window` service, so it may be overridden, removed or mocked for testing.
  12811. *
  12812. * Expressions, like the one defined for the `ngClick` directive in the example
  12813. * below, are evaluated with respect to the current scope. Therefore, there is
  12814. * no risk of inadvertently coding in a dependency on a global value in such an
  12815. * expression.
  12816. *
  12817. * @example
  12818. <example>
  12819. <file name="index.html">
  12820. <script>
  12821. function Ctrl($scope, $window) {
  12822. $scope.greeting = 'Hello, World!';
  12823. $scope.doGreeting = function(greeting) {
  12824. $window.alert(greeting);
  12825. };
  12826. }
  12827. </script>
  12828. <div ng-controller="Ctrl">
  12829. <input type="text" ng-model="greeting" />
  12830. <button ng-click="doGreeting(greeting)">ALERT</button>
  12831. </div>
  12832. </file>
  12833. <file name="protractor.js" type="protractor">
  12834. it('should display the greeting in the input box', function() {
  12835. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  12836. // If we click the button it will block the test runner
  12837. // element(':button').click();
  12838. });
  12839. </file>
  12840. </example>
  12841. */
  12842. function $WindowProvider(){
  12843. this.$get = valueFn(window);
  12844. }
  12845. /**
  12846. * @ngdoc provider
  12847. * @name $filterProvider
  12848. * @description
  12849. *
  12850. * Filters are just functions which transform input to an output. However filters need to be
  12851. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  12852. * annotated with dependencies and is responsible for creating a filter function.
  12853. *
  12854. * ```js
  12855. * // Filter registration
  12856. * function MyModule($provide, $filterProvider) {
  12857. * // create a service to demonstrate injection (not always needed)
  12858. * $provide.value('greet', function(name){
  12859. * return 'Hello ' + name + '!';
  12860. * });
  12861. *
  12862. * // register a filter factory which uses the
  12863. * // greet service to demonstrate DI.
  12864. * $filterProvider.register('greet', function(greet){
  12865. * // return the filter function which uses the greet service
  12866. * // to generate salutation
  12867. * return function(text) {
  12868. * // filters need to be forgiving so check input validity
  12869. * return text && greet(text) || text;
  12870. * };
  12871. * });
  12872. * }
  12873. * ```
  12874. *
  12875. * The filter function is registered with the `$injector` under the filter name suffix with
  12876. * `Filter`.
  12877. *
  12878. * ```js
  12879. * it('should be the same instance', inject(
  12880. * function($filterProvider) {
  12881. * $filterProvider.register('reverse', function(){
  12882. * return ...;
  12883. * });
  12884. * },
  12885. * function($filter, reverseFilter) {
  12886. * expect($filter('reverse')).toBe(reverseFilter);
  12887. * });
  12888. * ```
  12889. *
  12890. *
  12891. * For more information about how angular filters work, and how to create your own filters, see
  12892. * {@link guide/filter Filters} in the Angular Developer Guide.
  12893. */
  12894. /**
  12895. * @ngdoc method
  12896. * @name $filterProvider#register
  12897. * @description
  12898. * Register filter factory function.
  12899. *
  12900. * @param {String} name Name of the filter.
  12901. * @param {Function} fn The filter factory function which is injectable.
  12902. */
  12903. /**
  12904. * @ngdoc service
  12905. * @name $filter
  12906. * @function
  12907. * @description
  12908. * Filters are used for formatting data displayed to the user.
  12909. *
  12910. * The general syntax in templates is as follows:
  12911. *
  12912. * {{ expression [| filter_name[:parameter_value] ... ] }}
  12913. *
  12914. * @param {String} name Name of the filter function to retrieve
  12915. * @return {Function} the filter function
  12916. */
  12917. $FilterProvider.$inject = ['$provide'];
  12918. function $FilterProvider($provide) {
  12919. var suffix = 'Filter';
  12920. /**
  12921. * @ngdoc method
  12922. * @name $controllerProvider#register
  12923. * @param {string|Object} name Name of the filter function, or an object map of filters where
  12924. * the keys are the filter names and the values are the filter factories.
  12925. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  12926. * of the registered filter instances.
  12927. */
  12928. function register(name, factory) {
  12929. if(isObject(name)) {
  12930. var filters = {};
  12931. forEach(name, function(filter, key) {
  12932. filters[key] = register(key, filter);
  12933. });
  12934. return filters;
  12935. } else {
  12936. return $provide.factory(name + suffix, factory);
  12937. }
  12938. }
  12939. this.register = register;
  12940. this.$get = ['$injector', function($injector) {
  12941. return function(name) {
  12942. return $injector.get(name + suffix);
  12943. };
  12944. }];
  12945. ////////////////////////////////////////
  12946. /* global
  12947. currencyFilter: false,
  12948. dateFilter: false,
  12949. filterFilter: false,
  12950. jsonFilter: false,
  12951. limitToFilter: false,
  12952. lowercaseFilter: false,
  12953. numberFilter: false,
  12954. orderByFilter: false,
  12955. uppercaseFilter: false,
  12956. */
  12957. register('currency', currencyFilter);
  12958. register('date', dateFilter);
  12959. register('filter', filterFilter);
  12960. register('json', jsonFilter);
  12961. register('limitTo', limitToFilter);
  12962. register('lowercase', lowercaseFilter);
  12963. register('number', numberFilter);
  12964. register('orderBy', orderByFilter);
  12965. register('uppercase', uppercaseFilter);
  12966. }
  12967. /**
  12968. * @ngdoc filter
  12969. * @name filter
  12970. * @function
  12971. *
  12972. * @description
  12973. * Selects a subset of items from `array` and returns it as a new array.
  12974. *
  12975. * @param {Array} array The source array.
  12976. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  12977. * `array`.
  12978. *
  12979. * Can be one of:
  12980. *
  12981. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  12982. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  12983. * will be returned. The predicate can be negated by prefixing the string with `!`.
  12984. *
  12985. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  12986. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  12987. * which have property `name` containing "M" and property `phone` containing "1". A special
  12988. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  12989. * property of the object. That's equivalent to the simple substring match with a `string`
  12990. * as described above.
  12991. *
  12992. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  12993. * called for each element of `array`. The final result is an array of those elements that
  12994. * the predicate returned true for.
  12995. *
  12996. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  12997. * determining if the expected value (from the filter expression) and actual value (from
  12998. * the object in the array) should be considered a match.
  12999. *
  13000. * Can be one of:
  13001. *
  13002. * - `function(actual, expected)`:
  13003. * The function will be given the object value and the predicate value to compare and
  13004. * should return true if the item should be included in filtered result.
  13005. *
  13006. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13007. * this is essentially strict comparison of expected and actual.
  13008. *
  13009. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13010. * insensitive way.
  13011. *
  13012. * @example
  13013. <example>
  13014. <file name="index.html">
  13015. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13016. {name:'Mary', phone:'800-BIG-MARY'},
  13017. {name:'Mike', phone:'555-4321'},
  13018. {name:'Adam', phone:'555-5678'},
  13019. {name:'Julie', phone:'555-8765'},
  13020. {name:'Juliette', phone:'555-5678'}]"></div>
  13021. Search: <input ng-model="searchText">
  13022. <table id="searchTextResults">
  13023. <tr><th>Name</th><th>Phone</th></tr>
  13024. <tr ng-repeat="friend in friends | filter:searchText">
  13025. <td>{{friend.name}}</td>
  13026. <td>{{friend.phone}}</td>
  13027. </tr>
  13028. </table>
  13029. <hr>
  13030. Any: <input ng-model="search.$"> <br>
  13031. Name only <input ng-model="search.name"><br>
  13032. Phone only <input ng-model="search.phone"><br>
  13033. Equality <input type="checkbox" ng-model="strict"><br>
  13034. <table id="searchObjResults">
  13035. <tr><th>Name</th><th>Phone</th></tr>
  13036. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13037. <td>{{friendObj.name}}</td>
  13038. <td>{{friendObj.phone}}</td>
  13039. </tr>
  13040. </table>
  13041. </file>
  13042. <file name="protractor.js" type="protractor">
  13043. var expectFriendNames = function(expectedNames, key) {
  13044. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13045. arr.forEach(function(wd, i) {
  13046. expect(wd.getText()).toMatch(expectedNames[i]);
  13047. });
  13048. });
  13049. };
  13050. it('should search across all fields when filtering with a string', function() {
  13051. var searchText = element(by.model('searchText'));
  13052. searchText.clear();
  13053. searchText.sendKeys('m');
  13054. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13055. searchText.clear();
  13056. searchText.sendKeys('76');
  13057. expectFriendNames(['John', 'Julie'], 'friend');
  13058. });
  13059. it('should search in specific fields when filtering with a predicate object', function() {
  13060. var searchAny = element(by.model('search.$'));
  13061. searchAny.clear();
  13062. searchAny.sendKeys('i');
  13063. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13064. });
  13065. it('should use a equal comparison when comparator is true', function() {
  13066. var searchName = element(by.model('search.name'));
  13067. var strict = element(by.model('strict'));
  13068. searchName.clear();
  13069. searchName.sendKeys('Julie');
  13070. strict.click();
  13071. expectFriendNames(['Julie'], 'friendObj');
  13072. });
  13073. </file>
  13074. </example>
  13075. */
  13076. function filterFilter() {
  13077. return function(array, expression, comparator) {
  13078. if (!isArray(array)) return array;
  13079. var comparatorType = typeof(comparator),
  13080. predicates = [];
  13081. predicates.check = function(value) {
  13082. for (var j = 0; j < predicates.length; j++) {
  13083. if(!predicates[j](value)) {
  13084. return false;
  13085. }
  13086. }
  13087. return true;
  13088. };
  13089. if (comparatorType !== 'function') {
  13090. if (comparatorType === 'boolean' && comparator) {
  13091. comparator = function(obj, text) {
  13092. return angular.equals(obj, text);
  13093. };
  13094. } else {
  13095. comparator = function(obj, text) {
  13096. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13097. for (var objKey in obj) {
  13098. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13099. comparator(obj[objKey], text[objKey])) {
  13100. return true;
  13101. }
  13102. }
  13103. return false;
  13104. }
  13105. text = (''+text).toLowerCase();
  13106. return (''+obj).toLowerCase().indexOf(text) > -1;
  13107. };
  13108. }
  13109. }
  13110. var search = function(obj, text){
  13111. if (typeof text == 'string' && text.charAt(0) === '!') {
  13112. return !search(obj, text.substr(1));
  13113. }
  13114. switch (typeof obj) {
  13115. case "boolean":
  13116. case "number":
  13117. case "string":
  13118. return comparator(obj, text);
  13119. case "object":
  13120. switch (typeof text) {
  13121. case "object":
  13122. return comparator(obj, text);
  13123. default:
  13124. for ( var objKey in obj) {
  13125. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13126. return true;
  13127. }
  13128. }
  13129. break;
  13130. }
  13131. return false;
  13132. case "array":
  13133. for ( var i = 0; i < obj.length; i++) {
  13134. if (search(obj[i], text)) {
  13135. return true;
  13136. }
  13137. }
  13138. return false;
  13139. default:
  13140. return false;
  13141. }
  13142. };
  13143. switch (typeof expression) {
  13144. case "boolean":
  13145. case "number":
  13146. case "string":
  13147. // Set up expression object and fall through
  13148. expression = {$:expression};
  13149. // jshint -W086
  13150. case "object":
  13151. // jshint +W086
  13152. for (var key in expression) {
  13153. (function(path) {
  13154. if (typeof expression[path] == 'undefined') return;
  13155. predicates.push(function(value) {
  13156. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13157. });
  13158. })(key);
  13159. }
  13160. break;
  13161. case 'function':
  13162. predicates.push(expression);
  13163. break;
  13164. default:
  13165. return array;
  13166. }
  13167. var filtered = [];
  13168. for ( var j = 0; j < array.length; j++) {
  13169. var value = array[j];
  13170. if (predicates.check(value)) {
  13171. filtered.push(value);
  13172. }
  13173. }
  13174. return filtered;
  13175. };
  13176. }
  13177. /**
  13178. * @ngdoc filter
  13179. * @name currency
  13180. * @function
  13181. *
  13182. * @description
  13183. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13184. * symbol for current locale is used.
  13185. *
  13186. * @param {number} amount Input to filter.
  13187. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13188. * @returns {string} Formatted number.
  13189. *
  13190. *
  13191. * @example
  13192. <example>
  13193. <file name="index.html">
  13194. <script>
  13195. function Ctrl($scope) {
  13196. $scope.amount = 1234.56;
  13197. }
  13198. </script>
  13199. <div ng-controller="Ctrl">
  13200. <input type="number" ng-model="amount"> <br>
  13201. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13202. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13203. </div>
  13204. </file>
  13205. <file name="protractor.js" type="protractor">
  13206. it('should init with 1234.56', function() {
  13207. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13208. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13209. });
  13210. it('should update', function() {
  13211. if (browser.params.browser == 'safari') {
  13212. // Safari does not understand the minus key. See
  13213. // https://github.com/angular/protractor/issues/481
  13214. return;
  13215. }
  13216. element(by.model('amount')).clear();
  13217. element(by.model('amount')).sendKeys('-1234');
  13218. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13219. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13220. });
  13221. </file>
  13222. </example>
  13223. */
  13224. currencyFilter.$inject = ['$locale'];
  13225. function currencyFilter($locale) {
  13226. var formats = $locale.NUMBER_FORMATS;
  13227. return function(amount, currencySymbol){
  13228. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13229. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13230. replace(/\u00A4/g, currencySymbol);
  13231. };
  13232. }
  13233. /**
  13234. * @ngdoc filter
  13235. * @name number
  13236. * @function
  13237. *
  13238. * @description
  13239. * Formats a number as text.
  13240. *
  13241. * If the input is not a number an empty string is returned.
  13242. *
  13243. * @param {number|string} number Number to format.
  13244. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13245. * If this is not provided then the fraction size is computed from the current locale's number
  13246. * formatting pattern. In the case of the default locale, it will be 3.
  13247. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13248. *
  13249. * @example
  13250. <example>
  13251. <file name="index.html">
  13252. <script>
  13253. function Ctrl($scope) {
  13254. $scope.val = 1234.56789;
  13255. }
  13256. </script>
  13257. <div ng-controller="Ctrl">
  13258. Enter number: <input ng-model='val'><br>
  13259. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13260. No fractions: <span>{{val | number:0}}</span><br>
  13261. Negative number: <span>{{-val | number:4}}</span>
  13262. </div>
  13263. </file>
  13264. <file name="protractor.js" type="protractor">
  13265. it('should format numbers', function() {
  13266. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13267. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13268. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13269. });
  13270. it('should update', function() {
  13271. element(by.model('val')).clear();
  13272. element(by.model('val')).sendKeys('3374.333');
  13273. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13274. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13275. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13276. });
  13277. </file>
  13278. </example>
  13279. */
  13280. numberFilter.$inject = ['$locale'];
  13281. function numberFilter($locale) {
  13282. var formats = $locale.NUMBER_FORMATS;
  13283. return function(number, fractionSize) {
  13284. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13285. fractionSize);
  13286. };
  13287. }
  13288. var DECIMAL_SEP = '.';
  13289. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13290. if (number == null || !isFinite(number) || isObject(number)) return '';
  13291. var isNegative = number < 0;
  13292. number = Math.abs(number);
  13293. var numStr = number + '',
  13294. formatedText = '',
  13295. parts = [];
  13296. var hasExponent = false;
  13297. if (numStr.indexOf('e') !== -1) {
  13298. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13299. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13300. numStr = '0';
  13301. } else {
  13302. formatedText = numStr;
  13303. hasExponent = true;
  13304. }
  13305. }
  13306. if (!hasExponent) {
  13307. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13308. // determine fractionSize if it is not specified
  13309. if (isUndefined(fractionSize)) {
  13310. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13311. }
  13312. var pow = Math.pow(10, fractionSize);
  13313. number = Math.round(number * pow) / pow;
  13314. var fraction = ('' + number).split(DECIMAL_SEP);
  13315. var whole = fraction[0];
  13316. fraction = fraction[1] || '';
  13317. var i, pos = 0,
  13318. lgroup = pattern.lgSize,
  13319. group = pattern.gSize;
  13320. if (whole.length >= (lgroup + group)) {
  13321. pos = whole.length - lgroup;
  13322. for (i = 0; i < pos; i++) {
  13323. if ((pos - i)%group === 0 && i !== 0) {
  13324. formatedText += groupSep;
  13325. }
  13326. formatedText += whole.charAt(i);
  13327. }
  13328. }
  13329. for (i = pos; i < whole.length; i++) {
  13330. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13331. formatedText += groupSep;
  13332. }
  13333. formatedText += whole.charAt(i);
  13334. }
  13335. // format fraction part.
  13336. while(fraction.length < fractionSize) {
  13337. fraction += '0';
  13338. }
  13339. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13340. } else {
  13341. if (fractionSize > 0 && number > -1 && number < 1) {
  13342. formatedText = number.toFixed(fractionSize);
  13343. }
  13344. }
  13345. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13346. parts.push(formatedText);
  13347. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13348. return parts.join('');
  13349. }
  13350. function padNumber(num, digits, trim) {
  13351. var neg = '';
  13352. if (num < 0) {
  13353. neg = '-';
  13354. num = -num;
  13355. }
  13356. num = '' + num;
  13357. while(num.length < digits) num = '0' + num;
  13358. if (trim)
  13359. num = num.substr(num.length - digits);
  13360. return neg + num;
  13361. }
  13362. function dateGetter(name, size, offset, trim) {
  13363. offset = offset || 0;
  13364. return function(date) {
  13365. var value = date['get' + name]();
  13366. if (offset > 0 || value > -offset)
  13367. value += offset;
  13368. if (value === 0 && offset == -12 ) value = 12;
  13369. return padNumber(value, size, trim);
  13370. };
  13371. }
  13372. function dateStrGetter(name, shortForm) {
  13373. return function(date, formats) {
  13374. var value = date['get' + name]();
  13375. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13376. return formats[get][value];
  13377. };
  13378. }
  13379. function timeZoneGetter(date) {
  13380. var zone = -1 * date.getTimezoneOffset();
  13381. var paddedZone = (zone >= 0) ? "+" : "";
  13382. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13383. padNumber(Math.abs(zone % 60), 2);
  13384. return paddedZone;
  13385. }
  13386. function ampmGetter(date, formats) {
  13387. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13388. }
  13389. var DATE_FORMATS = {
  13390. yyyy: dateGetter('FullYear', 4),
  13391. yy: dateGetter('FullYear', 2, 0, true),
  13392. y: dateGetter('FullYear', 1),
  13393. MMMM: dateStrGetter('Month'),
  13394. MMM: dateStrGetter('Month', true),
  13395. MM: dateGetter('Month', 2, 1),
  13396. M: dateGetter('Month', 1, 1),
  13397. dd: dateGetter('Date', 2),
  13398. d: dateGetter('Date', 1),
  13399. HH: dateGetter('Hours', 2),
  13400. H: dateGetter('Hours', 1),
  13401. hh: dateGetter('Hours', 2, -12),
  13402. h: dateGetter('Hours', 1, -12),
  13403. mm: dateGetter('Minutes', 2),
  13404. m: dateGetter('Minutes', 1),
  13405. ss: dateGetter('Seconds', 2),
  13406. s: dateGetter('Seconds', 1),
  13407. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13408. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13409. sss: dateGetter('Milliseconds', 3),
  13410. EEEE: dateStrGetter('Day'),
  13411. EEE: dateStrGetter('Day', true),
  13412. a: ampmGetter,
  13413. Z: timeZoneGetter
  13414. };
  13415. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13416. NUMBER_STRING = /^\-?\d+$/;
  13417. /**
  13418. * @ngdoc filter
  13419. * @name date
  13420. * @function
  13421. *
  13422. * @description
  13423. * Formats `date` to a string based on the requested `format`.
  13424. *
  13425. * `format` string can be composed of the following elements:
  13426. *
  13427. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13428. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13429. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13430. * * `'MMMM'`: Month in year (January-December)
  13431. * * `'MMM'`: Month in year (Jan-Dec)
  13432. * * `'MM'`: Month in year, padded (01-12)
  13433. * * `'M'`: Month in year (1-12)
  13434. * * `'dd'`: Day in month, padded (01-31)
  13435. * * `'d'`: Day in month (1-31)
  13436. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13437. * * `'EEE'`: Day in Week, (Sun-Sat)
  13438. * * `'HH'`: Hour in day, padded (00-23)
  13439. * * `'H'`: Hour in day (0-23)
  13440. * * `'hh'`: Hour in am/pm, padded (01-12)
  13441. * * `'h'`: Hour in am/pm, (1-12)
  13442. * * `'mm'`: Minute in hour, padded (00-59)
  13443. * * `'m'`: Minute in hour (0-59)
  13444. * * `'ss'`: Second in minute, padded (00-59)
  13445. * * `'s'`: Second in minute (0-59)
  13446. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13447. * * `'a'`: am/pm marker
  13448. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13449. *
  13450. * `format` string can also be one of the following predefined
  13451. * {@link guide/i18n localizable formats}:
  13452. *
  13453. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13454. * (e.g. Sep 3, 2010 12:05:08 pm)
  13455. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13456. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13457. * (e.g. Friday, September 3, 2010)
  13458. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13459. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13460. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13461. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13462. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13463. *
  13464. * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
  13465. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
  13466. * (e.g. `"h 'o''clock'"`).
  13467. *
  13468. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13469. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
  13470. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13471. * specified in the string input, the time is considered to be in the local timezone.
  13472. * @param {string=} format Formatting rules (see Description). If not specified,
  13473. * `mediumDate` is used.
  13474. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13475. *
  13476. * @example
  13477. <example>
  13478. <file name="index.html">
  13479. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13480. <span>{{1288323623006 | date:'medium'}}</span><br>
  13481. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13482. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13483. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13484. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13485. </file>
  13486. <file name="protractor.js" type="protractor">
  13487. it('should format date', function() {
  13488. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13489. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13490. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13491. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13492. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13493. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13494. });
  13495. </file>
  13496. </example>
  13497. */
  13498. dateFilter.$inject = ['$locale'];
  13499. function dateFilter($locale) {
  13500. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13501. // 1 2 3 4 5 6 7 8 9 10 11
  13502. function jsonStringToDate(string) {
  13503. var match;
  13504. if (match = string.match(R_ISO8601_STR)) {
  13505. var date = new Date(0),
  13506. tzHour = 0,
  13507. tzMin = 0,
  13508. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13509. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13510. if (match[9]) {
  13511. tzHour = int(match[9] + match[10]);
  13512. tzMin = int(match[9] + match[11]);
  13513. }
  13514. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13515. var h = int(match[4]||0) - tzHour;
  13516. var m = int(match[5]||0) - tzMin;
  13517. var s = int(match[6]||0);
  13518. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13519. timeSetter.call(date, h, m, s, ms);
  13520. return date;
  13521. }
  13522. return string;
  13523. }
  13524. return function(date, format) {
  13525. var text = '',
  13526. parts = [],
  13527. fn, match;
  13528. format = format || 'mediumDate';
  13529. format = $locale.DATETIME_FORMATS[format] || format;
  13530. if (isString(date)) {
  13531. if (NUMBER_STRING.test(date)) {
  13532. date = int(date);
  13533. } else {
  13534. date = jsonStringToDate(date);
  13535. }
  13536. }
  13537. if (isNumber(date)) {
  13538. date = new Date(date);
  13539. }
  13540. if (!isDate(date)) {
  13541. return date;
  13542. }
  13543. while(format) {
  13544. match = DATE_FORMATS_SPLIT.exec(format);
  13545. if (match) {
  13546. parts = concat(parts, match, 1);
  13547. format = parts.pop();
  13548. } else {
  13549. parts.push(format);
  13550. format = null;
  13551. }
  13552. }
  13553. forEach(parts, function(value){
  13554. fn = DATE_FORMATS[value];
  13555. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13556. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13557. });
  13558. return text;
  13559. };
  13560. }
  13561. /**
  13562. * @ngdoc filter
  13563. * @name json
  13564. * @function
  13565. *
  13566. * @description
  13567. * Allows you to convert a JavaScript object into JSON string.
  13568. *
  13569. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13570. * the binding is automatically converted to JSON.
  13571. *
  13572. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13573. * @returns {string} JSON string.
  13574. *
  13575. *
  13576. * @example
  13577. <example>
  13578. <file name="index.html">
  13579. <pre>{{ {'name':'value'} | json }}</pre>
  13580. </file>
  13581. <file name="protractor.js" type="protractor">
  13582. it('should jsonify filtered objects', function() {
  13583. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  13584. });
  13585. </file>
  13586. </example>
  13587. *
  13588. */
  13589. function jsonFilter() {
  13590. return function(object) {
  13591. return toJson(object, true);
  13592. };
  13593. }
  13594. /**
  13595. * @ngdoc filter
  13596. * @name lowercase
  13597. * @function
  13598. * @description
  13599. * Converts string to lowercase.
  13600. * @see angular.lowercase
  13601. */
  13602. var lowercaseFilter = valueFn(lowercase);
  13603. /**
  13604. * @ngdoc filter
  13605. * @name uppercase
  13606. * @function
  13607. * @description
  13608. * Converts string to uppercase.
  13609. * @see angular.uppercase
  13610. */
  13611. var uppercaseFilter = valueFn(uppercase);
  13612. /**
  13613. * @ngdoc filter
  13614. * @name limitTo
  13615. * @function
  13616. *
  13617. * @description
  13618. * Creates a new array or string containing only a specified number of elements. The elements
  13619. * are taken from either the beginning or the end of the source array or string, as specified by
  13620. * the value and sign (positive or negative) of `limit`.
  13621. *
  13622. * @param {Array|string} input Source array or string to be limited.
  13623. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  13624. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  13625. * If the number is negative, `limit` number of items from the end of the source array/string
  13626. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  13627. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  13628. * had less than `limit` elements.
  13629. *
  13630. * @example
  13631. <example>
  13632. <file name="index.html">
  13633. <script>
  13634. function Ctrl($scope) {
  13635. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  13636. $scope.letters = "abcdefghi";
  13637. $scope.numLimit = 3;
  13638. $scope.letterLimit = 3;
  13639. }
  13640. </script>
  13641. <div ng-controller="Ctrl">
  13642. Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
  13643. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  13644. Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
  13645. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  13646. </div>
  13647. </file>
  13648. <file name="protractor.js" type="protractor">
  13649. var numLimitInput = element(by.model('numLimit'));
  13650. var letterLimitInput = element(by.model('letterLimit'));
  13651. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  13652. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  13653. it('should limit the number array to first three items', function() {
  13654. expect(numLimitInput.getAttribute('value')).toBe('3');
  13655. expect(letterLimitInput.getAttribute('value')).toBe('3');
  13656. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  13657. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  13658. });
  13659. it('should update the output when -3 is entered', function() {
  13660. numLimitInput.clear();
  13661. numLimitInput.sendKeys('-3');
  13662. letterLimitInput.clear();
  13663. letterLimitInput.sendKeys('-3');
  13664. expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  13665. expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  13666. });
  13667. it('should not exceed the maximum size of input array', function() {
  13668. numLimitInput.clear();
  13669. numLimitInput.sendKeys('100');
  13670. letterLimitInput.clear();
  13671. letterLimitInput.sendKeys('100');
  13672. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  13673. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  13674. });
  13675. </file>
  13676. </example>
  13677. */
  13678. function limitToFilter(){
  13679. return function(input, limit) {
  13680. if (!isArray(input) && !isString(input)) return input;
  13681. limit = int(limit);
  13682. if (isString(input)) {
  13683. //NaN check on limit
  13684. if (limit) {
  13685. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  13686. } else {
  13687. return "";
  13688. }
  13689. }
  13690. var out = [],
  13691. i, n;
  13692. // if abs(limit) exceeds maximum length, trim it
  13693. if (limit > input.length)
  13694. limit = input.length;
  13695. else if (limit < -input.length)
  13696. limit = -input.length;
  13697. if (limit > 0) {
  13698. i = 0;
  13699. n = limit;
  13700. } else {
  13701. i = input.length + limit;
  13702. n = input.length;
  13703. }
  13704. for (; i<n; i++) {
  13705. out.push(input[i]);
  13706. }
  13707. return out;
  13708. };
  13709. }
  13710. /**
  13711. * @ngdoc filter
  13712. * @name orderBy
  13713. * @function
  13714. *
  13715. * @description
  13716. * Orders a specified `array` by the `expression` predicate.
  13717. *
  13718. * @param {Array} array The array to sort.
  13719. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
  13720. * used by the comparator to determine the order of elements.
  13721. *
  13722. * Can be one of:
  13723. *
  13724. * - `function`: Getter function. The result of this function will be sorted using the
  13725. * `<`, `=`, `>` operator.
  13726. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
  13727. * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
  13728. * ascending or descending sort order (for example, +name or -name).
  13729. * - `Array`: An array of function or string predicates. The first predicate in the array
  13730. * is used for sorting, but when two items are equivalent, the next predicate is used.
  13731. *
  13732. * @param {boolean=} reverse Reverse the order of the array.
  13733. * @returns {Array} Sorted copy of the source array.
  13734. *
  13735. * @example
  13736. <example>
  13737. <file name="index.html">
  13738. <script>
  13739. function Ctrl($scope) {
  13740. $scope.friends =
  13741. [{name:'John', phone:'555-1212', age:10},
  13742. {name:'Mary', phone:'555-9876', age:19},
  13743. {name:'Mike', phone:'555-4321', age:21},
  13744. {name:'Adam', phone:'555-5678', age:35},
  13745. {name:'Julie', phone:'555-8765', age:29}]
  13746. $scope.predicate = '-age';
  13747. }
  13748. </script>
  13749. <div ng-controller="Ctrl">
  13750. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  13751. <hr/>
  13752. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  13753. <table class="friend">
  13754. <tr>
  13755. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  13756. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  13757. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  13758. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  13759. </tr>
  13760. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  13761. <td>{{friend.name}}</td>
  13762. <td>{{friend.phone}}</td>
  13763. <td>{{friend.age}}</td>
  13764. </tr>
  13765. </table>
  13766. </div>
  13767. </file>
  13768. </example>
  13769. */
  13770. orderByFilter.$inject = ['$parse'];
  13771. function orderByFilter($parse){
  13772. return function(array, sortPredicate, reverseOrder) {
  13773. if (!isArray(array)) return array;
  13774. if (!sortPredicate) return array;
  13775. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  13776. sortPredicate = map(sortPredicate, function(predicate){
  13777. var descending = false, get = predicate || identity;
  13778. if (isString(predicate)) {
  13779. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  13780. descending = predicate.charAt(0) == '-';
  13781. predicate = predicate.substring(1);
  13782. }
  13783. get = $parse(predicate);
  13784. if (get.constant) {
  13785. var key = get();
  13786. return reverseComparator(function(a,b) {
  13787. return compare(a[key], b[key]);
  13788. }, descending);
  13789. }
  13790. }
  13791. return reverseComparator(function(a,b){
  13792. return compare(get(a),get(b));
  13793. }, descending);
  13794. });
  13795. var arrayCopy = [];
  13796. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  13797. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  13798. function comparator(o1, o2){
  13799. for ( var i = 0; i < sortPredicate.length; i++) {
  13800. var comp = sortPredicate[i](o1, o2);
  13801. if (comp !== 0) return comp;
  13802. }
  13803. return 0;
  13804. }
  13805. function reverseComparator(comp, descending) {
  13806. return toBoolean(descending)
  13807. ? function(a,b){return comp(b,a);}
  13808. : comp;
  13809. }
  13810. function compare(v1, v2){
  13811. var t1 = typeof v1;
  13812. var t2 = typeof v2;
  13813. if (t1 == t2) {
  13814. if (t1 == "string") {
  13815. v1 = v1.toLowerCase();
  13816. v2 = v2.toLowerCase();
  13817. }
  13818. if (v1 === v2) return 0;
  13819. return v1 < v2 ? -1 : 1;
  13820. } else {
  13821. return t1 < t2 ? -1 : 1;
  13822. }
  13823. }
  13824. };
  13825. }
  13826. function ngDirective(directive) {
  13827. if (isFunction(directive)) {
  13828. directive = {
  13829. link: directive
  13830. };
  13831. }
  13832. directive.restrict = directive.restrict || 'AC';
  13833. return valueFn(directive);
  13834. }
  13835. /**
  13836. * @ngdoc directive
  13837. * @name a
  13838. * @restrict E
  13839. *
  13840. * @description
  13841. * Modifies the default behavior of the html A tag so that the default action is prevented when
  13842. * the href attribute is empty.
  13843. *
  13844. * This change permits the easy creation of action links with the `ngClick` directive
  13845. * without changing the location or causing page reloads, e.g.:
  13846. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  13847. */
  13848. var htmlAnchorDirective = valueFn({
  13849. restrict: 'E',
  13850. compile: function(element, attr) {
  13851. if (msie <= 8) {
  13852. // turn <a href ng-click="..">link</a> into a stylable link in IE
  13853. // but only if it doesn't have name attribute, in which case it's an anchor
  13854. if (!attr.href && !attr.name) {
  13855. attr.$set('href', '');
  13856. }
  13857. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  13858. // to new attribute content if attribute is updated with value containing @ and element also
  13859. // contains value with @
  13860. // see issue #1949
  13861. element.append(document.createComment('IE fix'));
  13862. }
  13863. if (!attr.href && !attr.xlinkHref && !attr.name) {
  13864. return function(scope, element) {
  13865. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  13866. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  13867. 'xlink:href' : 'href';
  13868. element.on('click', function(event){
  13869. // if we have no href url, then don't navigate anywhere.
  13870. if (!element.attr(href)) {
  13871. event.preventDefault();
  13872. }
  13873. });
  13874. };
  13875. }
  13876. }
  13877. });
  13878. /**
  13879. * @ngdoc directive
  13880. * @name ngHref
  13881. * @restrict A
  13882. * @priority 99
  13883. *
  13884. * @description
  13885. * Using Angular markup like `{{hash}}` in an href attribute will
  13886. * make the link go to the wrong URL if the user clicks it before
  13887. * Angular has a chance to replace the `{{hash}}` markup with its
  13888. * value. Until Angular replaces the markup the link will be broken
  13889. * and will most likely return a 404 error.
  13890. *
  13891. * The `ngHref` directive solves this problem.
  13892. *
  13893. * The wrong way to write it:
  13894. * ```html
  13895. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  13896. * ```
  13897. *
  13898. * The correct way to write it:
  13899. * ```html
  13900. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  13901. * ```
  13902. *
  13903. * @element A
  13904. * @param {template} ngHref any string which can contain `{{}}` markup.
  13905. *
  13906. * @example
  13907. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  13908. * in links and their different behaviors:
  13909. <example>
  13910. <file name="index.html">
  13911. <input ng-model="value" /><br />
  13912. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  13913. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  13914. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  13915. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  13916. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  13917. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  13918. </file>
  13919. <file name="protractor.js" type="protractor">
  13920. it('should execute ng-click but not reload when href without value', function() {
  13921. element(by.id('link-1')).click();
  13922. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  13923. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  13924. });
  13925. it('should execute ng-click but not reload when href empty string', function() {
  13926. element(by.id('link-2')).click();
  13927. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  13928. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  13929. });
  13930. it('should execute ng-click and change url when ng-href specified', function() {
  13931. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  13932. element(by.id('link-3')).click();
  13933. // At this point, we navigate away from an Angular page, so we need
  13934. // to use browser.driver to get the base webdriver.
  13935. browser.wait(function() {
  13936. return browser.driver.getCurrentUrl().then(function(url) {
  13937. return url.match(/\/123$/);
  13938. });
  13939. }, 1000, 'page should navigate to /123');
  13940. });
  13941. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  13942. element(by.id('link-4')).click();
  13943. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  13944. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  13945. });
  13946. it('should execute ng-click but not reload when no href but name specified', function() {
  13947. element(by.id('link-5')).click();
  13948. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  13949. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  13950. });
  13951. it('should only change url when only ng-href', function() {
  13952. element(by.model('value')).clear();
  13953. element(by.model('value')).sendKeys('6');
  13954. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  13955. element(by.id('link-6')).click();
  13956. // At this point, we navigate away from an Angular page, so we need
  13957. // to use browser.driver to get the base webdriver.
  13958. browser.wait(function() {
  13959. return browser.driver.getCurrentUrl().then(function(url) {
  13960. return url.match(/\/6$/);
  13961. });
  13962. }, 1000, 'page should navigate to /6');
  13963. });
  13964. </file>
  13965. </example>
  13966. */
  13967. /**
  13968. * @ngdoc directive
  13969. * @name ngSrc
  13970. * @restrict A
  13971. * @priority 99
  13972. *
  13973. * @description
  13974. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  13975. * work right: The browser will fetch from the URL with the literal
  13976. * text `{{hash}}` until Angular replaces the expression inside
  13977. * `{{hash}}`. The `ngSrc` directive solves this problem.
  13978. *
  13979. * The buggy way to write it:
  13980. * ```html
  13981. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  13982. * ```
  13983. *
  13984. * The correct way to write it:
  13985. * ```html
  13986. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  13987. * ```
  13988. *
  13989. * @element IMG
  13990. * @param {template} ngSrc any string which can contain `{{}}` markup.
  13991. */
  13992. /**
  13993. * @ngdoc directive
  13994. * @name ngSrcset
  13995. * @restrict A
  13996. * @priority 99
  13997. *
  13998. * @description
  13999. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14000. * work right: The browser will fetch from the URL with the literal
  14001. * text `{{hash}}` until Angular replaces the expression inside
  14002. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14003. *
  14004. * The buggy way to write it:
  14005. * ```html
  14006. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14007. * ```
  14008. *
  14009. * The correct way to write it:
  14010. * ```html
  14011. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14012. * ```
  14013. *
  14014. * @element IMG
  14015. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14016. */
  14017. /**
  14018. * @ngdoc directive
  14019. * @name ngDisabled
  14020. * @restrict A
  14021. * @priority 100
  14022. *
  14023. * @description
  14024. *
  14025. * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14026. * ```html
  14027. * <div ng-init="scope = { isDisabled: false }">
  14028. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14029. * </div>
  14030. * ```
  14031. *
  14032. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14033. * such as disabled. (Their presence means true and their absence means false.)
  14034. * If we put an Angular interpolation expression into such an attribute then the
  14035. * binding information would be lost when the browser removes the attribute.
  14036. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14037. * This complementary directive is not removed by the browser and so provides
  14038. * a permanent reliable place to store the binding information.
  14039. *
  14040. * @example
  14041. <example>
  14042. <file name="index.html">
  14043. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14044. <button ng-model="button" ng-disabled="checked">Button</button>
  14045. </file>
  14046. <file name="protractor.js" type="protractor">
  14047. it('should toggle button', function() {
  14048. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14049. element(by.model('checked')).click();
  14050. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14051. });
  14052. </file>
  14053. </example>
  14054. *
  14055. * @element INPUT
  14056. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14057. * then special attribute "disabled" will be set on the element
  14058. */
  14059. /**
  14060. * @ngdoc directive
  14061. * @name ngChecked
  14062. * @restrict A
  14063. * @priority 100
  14064. *
  14065. * @description
  14066. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14067. * such as checked. (Their presence means true and their absence means false.)
  14068. * If we put an Angular interpolation expression into such an attribute then the
  14069. * binding information would be lost when the browser removes the attribute.
  14070. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14071. * This complementary directive is not removed by the browser and so provides
  14072. * a permanent reliable place to store the binding information.
  14073. * @example
  14074. <example>
  14075. <file name="index.html">
  14076. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14077. <input id="checkSlave" type="checkbox" ng-checked="master">
  14078. </file>
  14079. <file name="protractor.js" type="protractor">
  14080. it('should check both checkBoxes', function() {
  14081. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14082. element(by.model('master')).click();
  14083. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14084. });
  14085. </file>
  14086. </example>
  14087. *
  14088. * @element INPUT
  14089. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14090. * then special attribute "checked" will be set on the element
  14091. */
  14092. /**
  14093. * @ngdoc directive
  14094. * @name ngReadonly
  14095. * @restrict A
  14096. * @priority 100
  14097. *
  14098. * @description
  14099. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14100. * such as readonly. (Their presence means true and their absence means false.)
  14101. * If we put an Angular interpolation expression into such an attribute then the
  14102. * binding information would be lost when the browser removes the attribute.
  14103. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14104. * This complementary directive is not removed by the browser and so provides
  14105. * a permanent reliable place to store the binding information.
  14106. * @example
  14107. <example>
  14108. <file name="index.html">
  14109. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14110. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14111. </file>
  14112. <file name="protractor.js" type="protractor">
  14113. it('should toggle readonly attr', function() {
  14114. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14115. element(by.model('checked')).click();
  14116. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14117. });
  14118. </file>
  14119. </example>
  14120. *
  14121. * @element INPUT
  14122. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14123. * then special attribute "readonly" will be set on the element
  14124. */
  14125. /**
  14126. * @ngdoc directive
  14127. * @name ngSelected
  14128. * @restrict A
  14129. * @priority 100
  14130. *
  14131. * @description
  14132. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14133. * such as selected. (Their presence means true and their absence means false.)
  14134. * If we put an Angular interpolation expression into such an attribute then the
  14135. * binding information would be lost when the browser removes the attribute.
  14136. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14137. * This complementary directive is not removed by the browser and so provides
  14138. * a permanent reliable place to store the binding information.
  14139. *
  14140. * @example
  14141. <example>
  14142. <file name="index.html">
  14143. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14144. <select>
  14145. <option>Hello!</option>
  14146. <option id="greet" ng-selected="selected">Greetings!</option>
  14147. </select>
  14148. </file>
  14149. <file name="protractor.js" type="protractor">
  14150. it('should select Greetings!', function() {
  14151. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14152. element(by.model('selected')).click();
  14153. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14154. });
  14155. </file>
  14156. </example>
  14157. *
  14158. * @element OPTION
  14159. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14160. * then special attribute "selected" will be set on the element
  14161. */
  14162. /**
  14163. * @ngdoc directive
  14164. * @name ngOpen
  14165. * @restrict A
  14166. * @priority 100
  14167. *
  14168. * @description
  14169. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14170. * such as open. (Their presence means true and their absence means false.)
  14171. * If we put an Angular interpolation expression into such an attribute then the
  14172. * binding information would be lost when the browser removes the attribute.
  14173. * The `ngOpen` directive solves this problem for the `open` attribute.
  14174. * This complementary directive is not removed by the browser and so provides
  14175. * a permanent reliable place to store the binding information.
  14176. * @example
  14177. <example>
  14178. <file name="index.html">
  14179. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14180. <details id="details" ng-open="open">
  14181. <summary>Show/Hide me</summary>
  14182. </details>
  14183. </file>
  14184. <file name="protractor.js" type="protractor">
  14185. it('should toggle open', function() {
  14186. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14187. element(by.model('open')).click();
  14188. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14189. });
  14190. </file>
  14191. </example>
  14192. *
  14193. * @element DETAILS
  14194. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14195. * then special attribute "open" will be set on the element
  14196. */
  14197. var ngAttributeAliasDirectives = {};
  14198. // boolean attrs are evaluated
  14199. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14200. // binding to multiple is not supported
  14201. if (propName == "multiple") return;
  14202. var normalized = directiveNormalize('ng-' + attrName);
  14203. ngAttributeAliasDirectives[normalized] = function() {
  14204. return {
  14205. priority: 100,
  14206. link: function(scope, element, attr) {
  14207. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14208. attr.$set(attrName, !!value);
  14209. });
  14210. }
  14211. };
  14212. };
  14213. });
  14214. // ng-src, ng-srcset, ng-href are interpolated
  14215. forEach(['src', 'srcset', 'href'], function(attrName) {
  14216. var normalized = directiveNormalize('ng-' + attrName);
  14217. ngAttributeAliasDirectives[normalized] = function() {
  14218. return {
  14219. priority: 99, // it needs to run after the attributes are interpolated
  14220. link: function(scope, element, attr) {
  14221. var propName = attrName,
  14222. name = attrName;
  14223. if (attrName === 'href' &&
  14224. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14225. name = 'xlinkHref';
  14226. attr.$attr[name] = 'xlink:href';
  14227. propName = null;
  14228. }
  14229. attr.$observe(normalized, function(value) {
  14230. if (!value)
  14231. return;
  14232. attr.$set(name, value);
  14233. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14234. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14235. // to set the property as well to achieve the desired effect.
  14236. // we use attr[attrName] value since $set can sanitize the url.
  14237. if (msie && propName) element.prop(propName, attr[name]);
  14238. });
  14239. }
  14240. };
  14241. };
  14242. });
  14243. /* global -nullFormCtrl */
  14244. var nullFormCtrl = {
  14245. $addControl: noop,
  14246. $removeControl: noop,
  14247. $setValidity: noop,
  14248. $setDirty: noop,
  14249. $setPristine: noop
  14250. };
  14251. /**
  14252. * @ngdoc type
  14253. * @name form.FormController
  14254. *
  14255. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14256. * @property {boolean} $dirty True if user has already interacted with the form.
  14257. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14258. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14259. *
  14260. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14261. * forms, where:
  14262. *
  14263. * - keys are validation tokens (error names),
  14264. * - values are arrays of controls or forms that are invalid for given error name.
  14265. *
  14266. *
  14267. * Built-in validation tokens:
  14268. *
  14269. * - `email`
  14270. * - `max`
  14271. * - `maxlength`
  14272. * - `min`
  14273. * - `minlength`
  14274. * - `number`
  14275. * - `pattern`
  14276. * - `required`
  14277. * - `url`
  14278. *
  14279. * @description
  14280. * `FormController` keeps track of all its controls and nested forms as well as state of them,
  14281. * such as being valid/invalid or dirty/pristine.
  14282. *
  14283. * Each {@link ng.directive:form form} directive creates an instance
  14284. * of `FormController`.
  14285. *
  14286. */
  14287. //asks for $scope to fool the BC controller module
  14288. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14289. function FormController(element, attrs, $scope, $animate) {
  14290. var form = this,
  14291. parentForm = element.parent().controller('form') || nullFormCtrl,
  14292. invalidCount = 0, // used to easily determine if we are valid
  14293. errors = form.$error = {},
  14294. controls = [];
  14295. // init state
  14296. form.$name = attrs.name || attrs.ngForm;
  14297. form.$dirty = false;
  14298. form.$pristine = true;
  14299. form.$valid = true;
  14300. form.$invalid = false;
  14301. parentForm.$addControl(form);
  14302. // Setup initial state of the control
  14303. element.addClass(PRISTINE_CLASS);
  14304. toggleValidCss(true);
  14305. // convenience method for easy toggling of classes
  14306. function toggleValidCss(isValid, validationErrorKey) {
  14307. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14308. $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14309. $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  14310. }
  14311. /**
  14312. * @ngdoc method
  14313. * @name form.FormController#$addControl
  14314. *
  14315. * @description
  14316. * Register a control with the form.
  14317. *
  14318. * Input elements using ngModelController do this automatically when they are linked.
  14319. */
  14320. form.$addControl = function(control) {
  14321. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14322. // and not added to the scope. Now we throw an error.
  14323. assertNotHasOwnProperty(control.$name, 'input');
  14324. controls.push(control);
  14325. if (control.$name) {
  14326. form[control.$name] = control;
  14327. }
  14328. };
  14329. /**
  14330. * @ngdoc method
  14331. * @name form.FormController#$removeControl
  14332. *
  14333. * @description
  14334. * Deregister a control from the form.
  14335. *
  14336. * Input elements using ngModelController do this automatically when they are destroyed.
  14337. */
  14338. form.$removeControl = function(control) {
  14339. if (control.$name && form[control.$name] === control) {
  14340. delete form[control.$name];
  14341. }
  14342. forEach(errors, function(queue, validationToken) {
  14343. form.$setValidity(validationToken, true, control);
  14344. });
  14345. arrayRemove(controls, control);
  14346. };
  14347. /**
  14348. * @ngdoc method
  14349. * @name form.FormController#$setValidity
  14350. *
  14351. * @description
  14352. * Sets the validity of a form control.
  14353. *
  14354. * This method will also propagate to parent forms.
  14355. */
  14356. form.$setValidity = function(validationToken, isValid, control) {
  14357. var queue = errors[validationToken];
  14358. if (isValid) {
  14359. if (queue) {
  14360. arrayRemove(queue, control);
  14361. if (!queue.length) {
  14362. invalidCount--;
  14363. if (!invalidCount) {
  14364. toggleValidCss(isValid);
  14365. form.$valid = true;
  14366. form.$invalid = false;
  14367. }
  14368. errors[validationToken] = false;
  14369. toggleValidCss(true, validationToken);
  14370. parentForm.$setValidity(validationToken, true, form);
  14371. }
  14372. }
  14373. } else {
  14374. if (!invalidCount) {
  14375. toggleValidCss(isValid);
  14376. }
  14377. if (queue) {
  14378. if (includes(queue, control)) return;
  14379. } else {
  14380. errors[validationToken] = queue = [];
  14381. invalidCount++;
  14382. toggleValidCss(false, validationToken);
  14383. parentForm.$setValidity(validationToken, false, form);
  14384. }
  14385. queue.push(control);
  14386. form.$valid = false;
  14387. form.$invalid = true;
  14388. }
  14389. };
  14390. /**
  14391. * @ngdoc method
  14392. * @name form.FormController#$setDirty
  14393. *
  14394. * @description
  14395. * Sets the form to a dirty state.
  14396. *
  14397. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14398. * state (ng-dirty class). This method will also propagate to parent forms.
  14399. */
  14400. form.$setDirty = function() {
  14401. $animate.removeClass(element, PRISTINE_CLASS);
  14402. $animate.addClass(element, DIRTY_CLASS);
  14403. form.$dirty = true;
  14404. form.$pristine = false;
  14405. parentForm.$setDirty();
  14406. };
  14407. /**
  14408. * @ngdoc method
  14409. * @name form.FormController#$setPristine
  14410. *
  14411. * @description
  14412. * Sets the form to its pristine state.
  14413. *
  14414. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14415. * state (ng-pristine class). This method will also propagate to all the controls contained
  14416. * in this form.
  14417. *
  14418. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14419. * saving or resetting it.
  14420. */
  14421. form.$setPristine = function () {
  14422. $animate.removeClass(element, DIRTY_CLASS);
  14423. $animate.addClass(element, PRISTINE_CLASS);
  14424. form.$dirty = false;
  14425. form.$pristine = true;
  14426. forEach(controls, function(control) {
  14427. control.$setPristine();
  14428. });
  14429. };
  14430. }
  14431. /**
  14432. * @ngdoc directive
  14433. * @name ngForm
  14434. * @restrict EAC
  14435. *
  14436. * @description
  14437. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14438. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14439. * sub-group of controls needs to be determined.
  14440. *
  14441. * Note: the purpose of `ngForm` is to group controls,
  14442. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14443. * (e.g. posting to the server, ...).
  14444. *
  14445. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14446. * related scope, under this name.
  14447. *
  14448. */
  14449. /**
  14450. * @ngdoc directive
  14451. * @name form
  14452. * @restrict E
  14453. *
  14454. * @description
  14455. * Directive that instantiates
  14456. * {@link form.FormController FormController}.
  14457. *
  14458. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14459. * this name.
  14460. *
  14461. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14462. *
  14463. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14464. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14465. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14466. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14467. * using Angular validation directives in forms that are dynamically generated using the
  14468. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14469. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14470. * `ngForm` directive and nest these in an outer `form` element.
  14471. *
  14472. *
  14473. * # CSS classes
  14474. * - `ng-valid` is set if the form is valid.
  14475. * - `ng-invalid` is set if the form is invalid.
  14476. * - `ng-pristine` is set if the form is pristine.
  14477. * - `ng-dirty` is set if the form is dirty.
  14478. *
  14479. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14480. *
  14481. *
  14482. * # Submitting a form and preventing the default action
  14483. *
  14484. * Since the role of forms in client-side Angular applications is different than in classical
  14485. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14486. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14487. * to handle the form submission in an application-specific way.
  14488. *
  14489. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14490. * `<form>` element has an `action` attribute specified.
  14491. *
  14492. * You can use one of the following two ways to specify what javascript method should be called when
  14493. * a form is submitted:
  14494. *
  14495. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14496. * - {@link ng.directive:ngClick ngClick} directive on the first
  14497. * button or input field of type submit (input[type=submit])
  14498. *
  14499. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14500. * or {@link ng.directive:ngClick ngClick} directives.
  14501. * This is because of the following form submission rules in the HTML specification:
  14502. *
  14503. * - If a form has only one input field then hitting enter in this field triggers form submit
  14504. * (`ngSubmit`)
  14505. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14506. * doesn't trigger submit
  14507. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14508. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14509. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14510. *
  14511. * @param {string=} name Name of the form. If specified, the form controller will be published into
  14512. * related scope, under this name.
  14513. *
  14514. * ## Animation Hooks
  14515. *
  14516. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  14517. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  14518. * other validations that are performed within the form. Animations in ngForm are similar to how
  14519. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  14520. * as JS animations.
  14521. *
  14522. * The following example shows a simple way to utilize CSS transitions to style a form element
  14523. * that has been rendered as invalid after it has been validated:
  14524. *
  14525. * <pre>
  14526. * //be sure to include ngAnimate as a module to hook into more
  14527. * //advanced animations
  14528. * .my-form {
  14529. * transition:0.5s linear all;
  14530. * background: white;
  14531. * }
  14532. * .my-form.ng-invalid {
  14533. * background: red;
  14534. * color:white;
  14535. * }
  14536. * </pre>
  14537. *
  14538. * @example
  14539. <example deps="angular-animate.js" animations="true" fixBase="true">
  14540. <file name="index.html">
  14541. <script>
  14542. function Ctrl($scope) {
  14543. $scope.userType = 'guest';
  14544. }
  14545. </script>
  14546. <style>
  14547. .my-form {
  14548. -webkit-transition:all linear 0.5s;
  14549. transition:all linear 0.5s;
  14550. background: transparent;
  14551. }
  14552. .my-form.ng-invalid {
  14553. background: red;
  14554. }
  14555. </style>
  14556. <form name="myForm" ng-controller="Ctrl" class="my-form">
  14557. userType: <input name="input" ng-model="userType" required>
  14558. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  14559. <tt>userType = {{userType}}</tt><br>
  14560. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  14561. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  14562. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14563. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14564. </form>
  14565. </file>
  14566. <file name="protractor.js" type="protractor">
  14567. it('should initialize to model', function() {
  14568. var userType = element(by.binding('userType'));
  14569. var valid = element(by.binding('myForm.input.$valid'));
  14570. expect(userType.getText()).toContain('guest');
  14571. expect(valid.getText()).toContain('true');
  14572. });
  14573. it('should be invalid if empty', function() {
  14574. var userType = element(by.binding('userType'));
  14575. var valid = element(by.binding('myForm.input.$valid'));
  14576. var userInput = element(by.model('userType'));
  14577. userInput.clear();
  14578. userInput.sendKeys('');
  14579. expect(userType.getText()).toEqual('userType =');
  14580. expect(valid.getText()).toContain('false');
  14581. });
  14582. </file>
  14583. </example>
  14584. *
  14585. */
  14586. var formDirectiveFactory = function(isNgForm) {
  14587. return ['$timeout', function($timeout) {
  14588. var formDirective = {
  14589. name: 'form',
  14590. restrict: isNgForm ? 'EAC' : 'E',
  14591. controller: FormController,
  14592. compile: function() {
  14593. return {
  14594. pre: function(scope, formElement, attr, controller) {
  14595. if (!attr.action) {
  14596. // we can't use jq events because if a form is destroyed during submission the default
  14597. // action is not prevented. see #1238
  14598. //
  14599. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  14600. // page reload if the form was destroyed by submission of the form via a click handler
  14601. // on a button in the form. Looks like an IE9 specific bug.
  14602. var preventDefaultListener = function(event) {
  14603. event.preventDefault
  14604. ? event.preventDefault()
  14605. : event.returnValue = false; // IE
  14606. };
  14607. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14608. // unregister the preventDefault listener so that we don't not leak memory but in a
  14609. // way that will achieve the prevention of the default action.
  14610. formElement.on('$destroy', function() {
  14611. $timeout(function() {
  14612. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14613. }, 0, false);
  14614. });
  14615. }
  14616. var parentFormCtrl = formElement.parent().controller('form'),
  14617. alias = attr.name || attr.ngForm;
  14618. if (alias) {
  14619. setter(scope, alias, controller, alias);
  14620. }
  14621. if (parentFormCtrl) {
  14622. formElement.on('$destroy', function() {
  14623. parentFormCtrl.$removeControl(controller);
  14624. if (alias) {
  14625. setter(scope, alias, undefined, alias);
  14626. }
  14627. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  14628. });
  14629. }
  14630. }
  14631. };
  14632. }
  14633. };
  14634. return formDirective;
  14635. }];
  14636. };
  14637. var formDirective = formDirectiveFactory();
  14638. var ngFormDirective = formDirectiveFactory(true);
  14639. /* global
  14640. -VALID_CLASS,
  14641. -INVALID_CLASS,
  14642. -PRISTINE_CLASS,
  14643. -DIRTY_CLASS
  14644. */
  14645. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  14646. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;
  14647. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  14648. var inputType = {
  14649. /**
  14650. * @ngdoc input
  14651. * @name input[text]
  14652. *
  14653. * @description
  14654. * Standard HTML text input with angular data binding.
  14655. *
  14656. * @param {string} ngModel Assignable angular expression to data-bind to.
  14657. * @param {string=} name Property name of the form under which the control is published.
  14658. * @param {string=} required Adds `required` validation error key if the value is not entered.
  14659. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14660. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14661. * `required` when you want to data-bind to the `required` attribute.
  14662. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14663. * minlength.
  14664. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14665. * maxlength.
  14666. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14667. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14668. * patterns defined as scope expressions.
  14669. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14670. * interaction with the input element.
  14671. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  14672. *
  14673. * @example
  14674. <example name="text-input-directive">
  14675. <file name="index.html">
  14676. <script>
  14677. function Ctrl($scope) {
  14678. $scope.text = 'guest';
  14679. $scope.word = /^\s*\w*\s*$/;
  14680. }
  14681. </script>
  14682. <form name="myForm" ng-controller="Ctrl">
  14683. Single word: <input type="text" name="input" ng-model="text"
  14684. ng-pattern="word" required ng-trim="false">
  14685. <span class="error" ng-show="myForm.input.$error.required">
  14686. Required!</span>
  14687. <span class="error" ng-show="myForm.input.$error.pattern">
  14688. Single word only!</span>
  14689. <tt>text = {{text}}</tt><br/>
  14690. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14691. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14692. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14693. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14694. </form>
  14695. </file>
  14696. <file name="protractor.js" type="protractor">
  14697. var text = element(by.binding('text'));
  14698. var valid = element(by.binding('myForm.input.$valid'));
  14699. var input = element(by.model('text'));
  14700. it('should initialize to model', function() {
  14701. expect(text.getText()).toContain('guest');
  14702. expect(valid.getText()).toContain('true');
  14703. });
  14704. it('should be invalid if empty', function() {
  14705. input.clear();
  14706. input.sendKeys('');
  14707. expect(text.getText()).toEqual('text =');
  14708. expect(valid.getText()).toContain('false');
  14709. });
  14710. it('should be invalid if multi word', function() {
  14711. input.clear();
  14712. input.sendKeys('hello world');
  14713. expect(valid.getText()).toContain('false');
  14714. });
  14715. </file>
  14716. </example>
  14717. */
  14718. 'text': textInputType,
  14719. /**
  14720. * @ngdoc input
  14721. * @name input[number]
  14722. *
  14723. * @description
  14724. * Text input with number validation and transformation. Sets the `number` validation
  14725. * error if not a valid number.
  14726. *
  14727. * @param {string} ngModel Assignable angular expression to data-bind to.
  14728. * @param {string=} name Property name of the form under which the control is published.
  14729. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  14730. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  14731. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14732. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14733. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14734. * `required` when you want to data-bind to the `required` attribute.
  14735. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14736. * minlength.
  14737. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14738. * maxlength.
  14739. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14740. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14741. * patterns defined as scope expressions.
  14742. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14743. * interaction with the input element.
  14744. *
  14745. * @example
  14746. <example name="number-input-directive">
  14747. <file name="index.html">
  14748. <script>
  14749. function Ctrl($scope) {
  14750. $scope.value = 12;
  14751. }
  14752. </script>
  14753. <form name="myForm" ng-controller="Ctrl">
  14754. Number: <input type="number" name="input" ng-model="value"
  14755. min="0" max="99" required>
  14756. <span class="error" ng-show="myForm.input.$error.required">
  14757. Required!</span>
  14758. <span class="error" ng-show="myForm.input.$error.number">
  14759. Not valid number!</span>
  14760. <tt>value = {{value}}</tt><br/>
  14761. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14762. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14763. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14764. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14765. </form>
  14766. </file>
  14767. <file name="protractor.js" type="protractor">
  14768. var value = element(by.binding('value'));
  14769. var valid = element(by.binding('myForm.input.$valid'));
  14770. var input = element(by.model('value'));
  14771. it('should initialize to model', function() {
  14772. expect(value.getText()).toContain('12');
  14773. expect(valid.getText()).toContain('true');
  14774. });
  14775. it('should be invalid if empty', function() {
  14776. input.clear();
  14777. input.sendKeys('');
  14778. expect(value.getText()).toEqual('value =');
  14779. expect(valid.getText()).toContain('false');
  14780. });
  14781. it('should be invalid if over max', function() {
  14782. input.clear();
  14783. input.sendKeys('123');
  14784. expect(value.getText()).toEqual('value =');
  14785. expect(valid.getText()).toContain('false');
  14786. });
  14787. </file>
  14788. </example>
  14789. */
  14790. 'number': numberInputType,
  14791. /**
  14792. * @ngdoc input
  14793. * @name input[url]
  14794. *
  14795. * @description
  14796. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  14797. * valid URL.
  14798. *
  14799. * @param {string} ngModel Assignable angular expression to data-bind to.
  14800. * @param {string=} name Property name of the form under which the control is published.
  14801. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14802. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14803. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14804. * `required` when you want to data-bind to the `required` attribute.
  14805. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14806. * minlength.
  14807. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14808. * maxlength.
  14809. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14810. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14811. * patterns defined as scope expressions.
  14812. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14813. * interaction with the input element.
  14814. *
  14815. * @example
  14816. <example name="url-input-directive">
  14817. <file name="index.html">
  14818. <script>
  14819. function Ctrl($scope) {
  14820. $scope.text = 'http://google.com';
  14821. }
  14822. </script>
  14823. <form name="myForm" ng-controller="Ctrl">
  14824. URL: <input type="url" name="input" ng-model="text" required>
  14825. <span class="error" ng-show="myForm.input.$error.required">
  14826. Required!</span>
  14827. <span class="error" ng-show="myForm.input.$error.url">
  14828. Not valid url!</span>
  14829. <tt>text = {{text}}</tt><br/>
  14830. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14831. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14832. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14833. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14834. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  14835. </form>
  14836. </file>
  14837. <file name="protractor.js" type="protractor">
  14838. var text = element(by.binding('text'));
  14839. var valid = element(by.binding('myForm.input.$valid'));
  14840. var input = element(by.model('text'));
  14841. it('should initialize to model', function() {
  14842. expect(text.getText()).toContain('http://google.com');
  14843. expect(valid.getText()).toContain('true');
  14844. });
  14845. it('should be invalid if empty', function() {
  14846. input.clear();
  14847. input.sendKeys('');
  14848. expect(text.getText()).toEqual('text =');
  14849. expect(valid.getText()).toContain('false');
  14850. });
  14851. it('should be invalid if not url', function() {
  14852. input.clear();
  14853. input.sendKeys('box');
  14854. expect(valid.getText()).toContain('false');
  14855. });
  14856. </file>
  14857. </example>
  14858. */
  14859. 'url': urlInputType,
  14860. /**
  14861. * @ngdoc input
  14862. * @name input[email]
  14863. *
  14864. * @description
  14865. * Text input with email validation. Sets the `email` validation error key if not a valid email
  14866. * address.
  14867. *
  14868. * @param {string} ngModel Assignable angular expression to data-bind to.
  14869. * @param {string=} name Property name of the form under which the control is published.
  14870. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14871. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14872. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14873. * `required` when you want to data-bind to the `required` attribute.
  14874. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14875. * minlength.
  14876. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14877. * maxlength.
  14878. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14879. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14880. * patterns defined as scope expressions.
  14881. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14882. * interaction with the input element.
  14883. *
  14884. * @example
  14885. <example name="email-input-directive">
  14886. <file name="index.html">
  14887. <script>
  14888. function Ctrl($scope) {
  14889. $scope.text = 'me@example.com';
  14890. }
  14891. </script>
  14892. <form name="myForm" ng-controller="Ctrl">
  14893. Email: <input type="email" name="input" ng-model="text" required>
  14894. <span class="error" ng-show="myForm.input.$error.required">
  14895. Required!</span>
  14896. <span class="error" ng-show="myForm.input.$error.email">
  14897. Not valid email!</span>
  14898. <tt>text = {{text}}</tt><br/>
  14899. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14900. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14901. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14902. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14903. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  14904. </form>
  14905. </file>
  14906. <file name="protractor.js" type="protractor">
  14907. var text = element(by.binding('text'));
  14908. var valid = element(by.binding('myForm.input.$valid'));
  14909. var input = element(by.model('text'));
  14910. it('should initialize to model', function() {
  14911. expect(text.getText()).toContain('me@example.com');
  14912. expect(valid.getText()).toContain('true');
  14913. });
  14914. it('should be invalid if empty', function() {
  14915. input.clear();
  14916. input.sendKeys('');
  14917. expect(text.getText()).toEqual('text =');
  14918. expect(valid.getText()).toContain('false');
  14919. });
  14920. it('should be invalid if not email', function() {
  14921. input.clear();
  14922. input.sendKeys('xxx');
  14923. expect(valid.getText()).toContain('false');
  14924. });
  14925. </file>
  14926. </example>
  14927. */
  14928. 'email': emailInputType,
  14929. /**
  14930. * @ngdoc input
  14931. * @name input[radio]
  14932. *
  14933. * @description
  14934. * HTML radio button.
  14935. *
  14936. * @param {string} ngModel Assignable angular expression to data-bind to.
  14937. * @param {string} value The value to which the expression should be set when selected.
  14938. * @param {string=} name Property name of the form under which the control is published.
  14939. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14940. * interaction with the input element.
  14941. * @param {string} ngValue Angular expression which sets the value to which the expression should
  14942. * be set when selected.
  14943. *
  14944. * @example
  14945. <example name="radio-input-directive">
  14946. <file name="index.html">
  14947. <script>
  14948. function Ctrl($scope) {
  14949. $scope.color = 'blue';
  14950. $scope.specialValue = {
  14951. "id": "12345",
  14952. "value": "green"
  14953. };
  14954. }
  14955. </script>
  14956. <form name="myForm" ng-controller="Ctrl">
  14957. <input type="radio" ng-model="color" value="red"> Red <br/>
  14958. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  14959. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  14960. <tt>color = {{color | json}}</tt><br/>
  14961. </form>
  14962. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  14963. </file>
  14964. <file name="protractor.js" type="protractor">
  14965. it('should change state', function() {
  14966. var color = element(by.binding('color'));
  14967. expect(color.getText()).toContain('blue');
  14968. element.all(by.model('color')).get(0).click();
  14969. expect(color.getText()).toContain('red');
  14970. });
  14971. </file>
  14972. </example>
  14973. */
  14974. 'radio': radioInputType,
  14975. /**
  14976. * @ngdoc input
  14977. * @name input[checkbox]
  14978. *
  14979. * @description
  14980. * HTML checkbox.
  14981. *
  14982. * @param {string} ngModel Assignable angular expression to data-bind to.
  14983. * @param {string=} name Property name of the form under which the control is published.
  14984. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  14985. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  14986. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14987. * interaction with the input element.
  14988. *
  14989. * @example
  14990. <example name="checkbox-input-directive">
  14991. <file name="index.html">
  14992. <script>
  14993. function Ctrl($scope) {
  14994. $scope.value1 = true;
  14995. $scope.value2 = 'YES'
  14996. }
  14997. </script>
  14998. <form name="myForm" ng-controller="Ctrl">
  14999. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15000. Value2: <input type="checkbox" ng-model="value2"
  15001. ng-true-value="YES" ng-false-value="NO"> <br/>
  15002. <tt>value1 = {{value1}}</tt><br/>
  15003. <tt>value2 = {{value2}}</tt><br/>
  15004. </form>
  15005. </file>
  15006. <file name="protractor.js" type="protractor">
  15007. it('should change state', function() {
  15008. var value1 = element(by.binding('value1'));
  15009. var value2 = element(by.binding('value2'));
  15010. expect(value1.getText()).toContain('true');
  15011. expect(value2.getText()).toContain('YES');
  15012. element(by.model('value1')).click();
  15013. element(by.model('value2')).click();
  15014. expect(value1.getText()).toContain('false');
  15015. expect(value2.getText()).toContain('NO');
  15016. });
  15017. </file>
  15018. </example>
  15019. */
  15020. 'checkbox': checkboxInputType,
  15021. 'hidden': noop,
  15022. 'button': noop,
  15023. 'submit': noop,
  15024. 'reset': noop,
  15025. 'file': noop
  15026. };
  15027. // A helper function to call $setValidity and return the value / undefined,
  15028. // a pattern that is repeated a lot in the input validation logic.
  15029. function validate(ctrl, validatorName, validity, value){
  15030. ctrl.$setValidity(validatorName, validity);
  15031. return validity ? value : undefined;
  15032. }
  15033. function addNativeHtml5Validators(ctrl, validatorName, element) {
  15034. var validity = element.prop('validity');
  15035. if (isObject(validity)) {
  15036. var validator = function(value) {
  15037. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15038. // perform the required validation)
  15039. if (!ctrl.$error[validatorName] && (validity.badInput || validity.customError ||
  15040. validity.typeMismatch) && !validity.valueMissing) {
  15041. ctrl.$setValidity(validatorName, false);
  15042. return;
  15043. }
  15044. return value;
  15045. };
  15046. ctrl.$parsers.push(validator);
  15047. }
  15048. }
  15049. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15050. var validity = element.prop('validity');
  15051. // In composition mode, users are still inputing intermediate text buffer,
  15052. // hold the listener until composition is done.
  15053. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15054. if (!$sniffer.android) {
  15055. var composing = false;
  15056. element.on('compositionstart', function(data) {
  15057. composing = true;
  15058. });
  15059. element.on('compositionend', function() {
  15060. composing = false;
  15061. listener();
  15062. });
  15063. }
  15064. var listener = function() {
  15065. if (composing) return;
  15066. var value = element.val();
  15067. // By default we will trim the value
  15068. // If the attribute ng-trim exists we will avoid trimming
  15069. // e.g. <input ng-model="foo" ng-trim="false">
  15070. if (toBoolean(attr.ngTrim || 'T')) {
  15071. value = trim(value);
  15072. }
  15073. if (ctrl.$viewValue !== value ||
  15074. // If the value is still empty/falsy, and there is no `required` error, run validators
  15075. // again. This enables HTML5 constraint validation errors to affect Angular validation
  15076. // even when the first character entered causes an error.
  15077. (validity && value === '' && !validity.valueMissing)) {
  15078. if (scope.$$phase) {
  15079. ctrl.$setViewValue(value);
  15080. } else {
  15081. scope.$apply(function() {
  15082. ctrl.$setViewValue(value);
  15083. });
  15084. }
  15085. }
  15086. };
  15087. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15088. // input event on backspace, delete or cut
  15089. if ($sniffer.hasEvent('input')) {
  15090. element.on('input', listener);
  15091. } else {
  15092. var timeout;
  15093. var deferListener = function() {
  15094. if (!timeout) {
  15095. timeout = $browser.defer(function() {
  15096. listener();
  15097. timeout = null;
  15098. });
  15099. }
  15100. };
  15101. element.on('keydown', function(event) {
  15102. var key = event.keyCode;
  15103. // ignore
  15104. // command modifiers arrows
  15105. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15106. deferListener();
  15107. });
  15108. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15109. if ($sniffer.hasEvent('paste')) {
  15110. element.on('paste cut', deferListener);
  15111. }
  15112. }
  15113. // if user paste into input using mouse on older browser
  15114. // or form autocomplete on newer browser, we need "change" event to catch it
  15115. element.on('change', listener);
  15116. ctrl.$render = function() {
  15117. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15118. };
  15119. // pattern validator
  15120. var pattern = attr.ngPattern,
  15121. patternValidator,
  15122. match;
  15123. if (pattern) {
  15124. var validateRegex = function(regexp, value) {
  15125. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15126. };
  15127. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15128. if (match) {
  15129. pattern = new RegExp(match[1], match[2]);
  15130. patternValidator = function(value) {
  15131. return validateRegex(pattern, value);
  15132. };
  15133. } else {
  15134. patternValidator = function(value) {
  15135. var patternObj = scope.$eval(pattern);
  15136. if (!patternObj || !patternObj.test) {
  15137. throw minErr('ngPattern')('noregexp',
  15138. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15139. patternObj, startingTag(element));
  15140. }
  15141. return validateRegex(patternObj, value);
  15142. };
  15143. }
  15144. ctrl.$formatters.push(patternValidator);
  15145. ctrl.$parsers.push(patternValidator);
  15146. }
  15147. // min length validator
  15148. if (attr.ngMinlength) {
  15149. var minlength = int(attr.ngMinlength);
  15150. var minLengthValidator = function(value) {
  15151. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15152. };
  15153. ctrl.$parsers.push(minLengthValidator);
  15154. ctrl.$formatters.push(minLengthValidator);
  15155. }
  15156. // max length validator
  15157. if (attr.ngMaxlength) {
  15158. var maxlength = int(attr.ngMaxlength);
  15159. var maxLengthValidator = function(value) {
  15160. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15161. };
  15162. ctrl.$parsers.push(maxLengthValidator);
  15163. ctrl.$formatters.push(maxLengthValidator);
  15164. }
  15165. }
  15166. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15167. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15168. ctrl.$parsers.push(function(value) {
  15169. var empty = ctrl.$isEmpty(value);
  15170. if (empty || NUMBER_REGEXP.test(value)) {
  15171. ctrl.$setValidity('number', true);
  15172. return value === '' ? null : (empty ? value : parseFloat(value));
  15173. } else {
  15174. ctrl.$setValidity('number', false);
  15175. return undefined;
  15176. }
  15177. });
  15178. addNativeHtml5Validators(ctrl, 'number', element);
  15179. ctrl.$formatters.push(function(value) {
  15180. return ctrl.$isEmpty(value) ? '' : '' + value;
  15181. });
  15182. if (attr.min) {
  15183. var minValidator = function(value) {
  15184. var min = parseFloat(attr.min);
  15185. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15186. };
  15187. ctrl.$parsers.push(minValidator);
  15188. ctrl.$formatters.push(minValidator);
  15189. }
  15190. if (attr.max) {
  15191. var maxValidator = function(value) {
  15192. var max = parseFloat(attr.max);
  15193. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15194. };
  15195. ctrl.$parsers.push(maxValidator);
  15196. ctrl.$formatters.push(maxValidator);
  15197. }
  15198. ctrl.$formatters.push(function(value) {
  15199. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15200. });
  15201. }
  15202. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15203. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15204. var urlValidator = function(value) {
  15205. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15206. };
  15207. ctrl.$formatters.push(urlValidator);
  15208. ctrl.$parsers.push(urlValidator);
  15209. }
  15210. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15211. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15212. var emailValidator = function(value) {
  15213. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15214. };
  15215. ctrl.$formatters.push(emailValidator);
  15216. ctrl.$parsers.push(emailValidator);
  15217. }
  15218. function radioInputType(scope, element, attr, ctrl) {
  15219. // make the name unique, if not defined
  15220. if (isUndefined(attr.name)) {
  15221. element.attr('name', nextUid());
  15222. }
  15223. element.on('click', function() {
  15224. if (element[0].checked) {
  15225. scope.$apply(function() {
  15226. ctrl.$setViewValue(attr.value);
  15227. });
  15228. }
  15229. });
  15230. ctrl.$render = function() {
  15231. var value = attr.value;
  15232. element[0].checked = (value == ctrl.$viewValue);
  15233. };
  15234. attr.$observe('value', ctrl.$render);
  15235. }
  15236. function checkboxInputType(scope, element, attr, ctrl) {
  15237. var trueValue = attr.ngTrueValue,
  15238. falseValue = attr.ngFalseValue;
  15239. if (!isString(trueValue)) trueValue = true;
  15240. if (!isString(falseValue)) falseValue = false;
  15241. element.on('click', function() {
  15242. scope.$apply(function() {
  15243. ctrl.$setViewValue(element[0].checked);
  15244. });
  15245. });
  15246. ctrl.$render = function() {
  15247. element[0].checked = ctrl.$viewValue;
  15248. };
  15249. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15250. ctrl.$isEmpty = function(value) {
  15251. return value !== trueValue;
  15252. };
  15253. ctrl.$formatters.push(function(value) {
  15254. return value === trueValue;
  15255. });
  15256. ctrl.$parsers.push(function(value) {
  15257. return value ? trueValue : falseValue;
  15258. });
  15259. }
  15260. /**
  15261. * @ngdoc directive
  15262. * @name textarea
  15263. * @restrict E
  15264. *
  15265. * @description
  15266. * HTML textarea element control with angular data-binding. The data-binding and validation
  15267. * properties of this element are exactly the same as those of the
  15268. * {@link ng.directive:input input element}.
  15269. *
  15270. * @param {string} ngModel Assignable angular expression to data-bind to.
  15271. * @param {string=} name Property name of the form under which the control is published.
  15272. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15273. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15274. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15275. * `required` when you want to data-bind to the `required` attribute.
  15276. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15277. * minlength.
  15278. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15279. * maxlength.
  15280. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15281. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15282. * patterns defined as scope expressions.
  15283. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15284. * interaction with the input element.
  15285. */
  15286. /**
  15287. * @ngdoc directive
  15288. * @name input
  15289. * @restrict E
  15290. *
  15291. * @description
  15292. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15293. * and polyfills the HTML5 validation behavior for older browsers.
  15294. *
  15295. * @param {string} ngModel Assignable angular expression to data-bind to.
  15296. * @param {string=} name Property name of the form under which the control is published.
  15297. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15298. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15299. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15300. * minlength.
  15301. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15302. * maxlength.
  15303. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15304. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15305. * patterns defined as scope expressions.
  15306. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15307. * interaction with the input element.
  15308. *
  15309. * @example
  15310. <example name="input-directive">
  15311. <file name="index.html">
  15312. <script>
  15313. function Ctrl($scope) {
  15314. $scope.user = {name: 'guest', last: 'visitor'};
  15315. }
  15316. </script>
  15317. <div ng-controller="Ctrl">
  15318. <form name="myForm">
  15319. User name: <input type="text" name="userName" ng-model="user.name" required>
  15320. <span class="error" ng-show="myForm.userName.$error.required">
  15321. Required!</span><br>
  15322. Last name: <input type="text" name="lastName" ng-model="user.last"
  15323. ng-minlength="3" ng-maxlength="10">
  15324. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15325. Too short!</span>
  15326. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15327. Too long!</span><br>
  15328. </form>
  15329. <hr>
  15330. <tt>user = {{user}}</tt><br/>
  15331. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15332. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15333. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15334. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15335. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15336. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15337. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15338. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15339. </div>
  15340. </file>
  15341. <file name="protractor.js" type="protractor">
  15342. var user = element(by.binding('{{user}}'));
  15343. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15344. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15345. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15346. var formValid = element(by.binding('myForm.$valid'));
  15347. var userNameInput = element(by.model('user.name'));
  15348. var userLastInput = element(by.model('user.last'));
  15349. it('should initialize to model', function() {
  15350. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15351. expect(userNameValid.getText()).toContain('true');
  15352. expect(formValid.getText()).toContain('true');
  15353. });
  15354. it('should be invalid if empty when required', function() {
  15355. userNameInput.clear();
  15356. userNameInput.sendKeys('');
  15357. expect(user.getText()).toContain('{"last":"visitor"}');
  15358. expect(userNameValid.getText()).toContain('false');
  15359. expect(formValid.getText()).toContain('false');
  15360. });
  15361. it('should be valid if empty when min length is set', function() {
  15362. userLastInput.clear();
  15363. userLastInput.sendKeys('');
  15364. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15365. expect(lastNameValid.getText()).toContain('true');
  15366. expect(formValid.getText()).toContain('true');
  15367. });
  15368. it('should be invalid if less than required min length', function() {
  15369. userLastInput.clear();
  15370. userLastInput.sendKeys('xx');
  15371. expect(user.getText()).toContain('{"name":"guest"}');
  15372. expect(lastNameValid.getText()).toContain('false');
  15373. expect(lastNameError.getText()).toContain('minlength');
  15374. expect(formValid.getText()).toContain('false');
  15375. });
  15376. it('should be invalid if longer than max length', function() {
  15377. userLastInput.clear();
  15378. userLastInput.sendKeys('some ridiculously long name');
  15379. expect(user.getText()).toContain('{"name":"guest"}');
  15380. expect(lastNameValid.getText()).toContain('false');
  15381. expect(lastNameError.getText()).toContain('maxlength');
  15382. expect(formValid.getText()).toContain('false');
  15383. });
  15384. </file>
  15385. </example>
  15386. */
  15387. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15388. return {
  15389. restrict: 'E',
  15390. require: '?ngModel',
  15391. link: function(scope, element, attr, ctrl) {
  15392. if (ctrl) {
  15393. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15394. $browser);
  15395. }
  15396. }
  15397. };
  15398. }];
  15399. var VALID_CLASS = 'ng-valid',
  15400. INVALID_CLASS = 'ng-invalid',
  15401. PRISTINE_CLASS = 'ng-pristine',
  15402. DIRTY_CLASS = 'ng-dirty';
  15403. /**
  15404. * @ngdoc type
  15405. * @name ngModel.NgModelController
  15406. *
  15407. * @property {string} $viewValue Actual string value in the view.
  15408. * @property {*} $modelValue The value in the model, that the control is bound to.
  15409. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15410. the control reads value from the DOM. Each function is called, in turn, passing the value
  15411. through to the next. The last return value is used to populate the model.
  15412. Used to sanitize / convert the value as well as validation. For validation,
  15413. the parsers should update the validity state using
  15414. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15415. and return `undefined` for invalid values.
  15416. *
  15417. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15418. the model value changes. Each function is called, in turn, passing the value through to the
  15419. next. Used to format / convert values for display in the control and validation.
  15420. * ```js
  15421. * function formatter(value) {
  15422. * if (value) {
  15423. * return value.toUpperCase();
  15424. * }
  15425. * }
  15426. * ngModel.$formatters.push(formatter);
  15427. * ```
  15428. *
  15429. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15430. * view value has changed. It is called with no arguments, and its return value is ignored.
  15431. * This can be used in place of additional $watches against the model value.
  15432. *
  15433. * @property {Object} $error An object hash with all errors as keys.
  15434. *
  15435. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15436. * @property {boolean} $dirty True if user has already interacted with the control.
  15437. * @property {boolean} $valid True if there is no error.
  15438. * @property {boolean} $invalid True if at least one error on the control.
  15439. *
  15440. * @description
  15441. *
  15442. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15443. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15444. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15445. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15446. * `NgModelController` for data-binding.
  15447. *
  15448. * ## Custom Control Example
  15449. * This example shows how to use `NgModelController` with a custom control to achieve
  15450. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  15451. * collaborate together to achieve the desired result.
  15452. *
  15453. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  15454. * contents be edited in place by the user. This will not work on older browsers.
  15455. *
  15456. * <example name="NgModelController" module="customControl">
  15457. <file name="style.css">
  15458. [contenteditable] {
  15459. border: 1px solid black;
  15460. background-color: white;
  15461. min-height: 20px;
  15462. }
  15463. .ng-invalid {
  15464. border: 1px solid red;
  15465. }
  15466. </file>
  15467. <file name="script.js">
  15468. angular.module('customControl', []).
  15469. directive('contenteditable', function() {
  15470. return {
  15471. restrict: 'A', // only activate on element attribute
  15472. require: '?ngModel', // get a hold of NgModelController
  15473. link: function(scope, element, attrs, ngModel) {
  15474. if(!ngModel) return; // do nothing if no ng-model
  15475. // Specify how UI should be updated
  15476. ngModel.$render = function() {
  15477. element.html(ngModel.$viewValue || '');
  15478. };
  15479. // Listen for change events to enable binding
  15480. element.on('blur keyup change', function() {
  15481. scope.$apply(read);
  15482. });
  15483. read(); // initialize
  15484. // Write data to the model
  15485. function read() {
  15486. var html = element.html();
  15487. // When we clear the content editable the browser leaves a <br> behind
  15488. // If strip-br attribute is provided then we strip this out
  15489. if( attrs.stripBr && html == '<br>' ) {
  15490. html = '';
  15491. }
  15492. ngModel.$setViewValue(html);
  15493. }
  15494. }
  15495. };
  15496. });
  15497. </file>
  15498. <file name="index.html">
  15499. <form name="myForm">
  15500. <div contenteditable
  15501. name="myWidget" ng-model="userContent"
  15502. strip-br="true"
  15503. required>Change me!</div>
  15504. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  15505. <hr>
  15506. <textarea ng-model="userContent"></textarea>
  15507. </form>
  15508. </file>
  15509. <file name="protractor.js" type="protractor">
  15510. it('should data-bind and become invalid', function() {
  15511. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  15512. // SafariDriver can't handle contenteditable
  15513. // and Firefox driver can't clear contenteditables very well
  15514. return;
  15515. }
  15516. var contentEditable = element(by.css('[contenteditable]'));
  15517. var content = 'Change me!';
  15518. expect(contentEditable.getText()).toEqual(content);
  15519. contentEditable.clear();
  15520. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  15521. expect(contentEditable.getText()).toEqual('');
  15522. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  15523. });
  15524. </file>
  15525. * </example>
  15526. *
  15527. *
  15528. */
  15529. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  15530. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  15531. this.$viewValue = Number.NaN;
  15532. this.$modelValue = Number.NaN;
  15533. this.$parsers = [];
  15534. this.$formatters = [];
  15535. this.$viewChangeListeners = [];
  15536. this.$pristine = true;
  15537. this.$dirty = false;
  15538. this.$valid = true;
  15539. this.$invalid = false;
  15540. this.$name = $attr.name;
  15541. var ngModelGet = $parse($attr.ngModel),
  15542. ngModelSet = ngModelGet.assign;
  15543. if (!ngModelSet) {
  15544. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  15545. $attr.ngModel, startingTag($element));
  15546. }
  15547. /**
  15548. * @ngdoc method
  15549. * @name ngModel.NgModelController#$render
  15550. *
  15551. * @description
  15552. * Called when the view needs to be updated. It is expected that the user of the ng-model
  15553. * directive will implement this method.
  15554. */
  15555. this.$render = noop;
  15556. /**
  15557. * @ngdoc method
  15558. * @name ngModel.NgModelController#$isEmpty
  15559. *
  15560. * @description
  15561. * This is called when we need to determine if the value of the input is empty.
  15562. *
  15563. * For instance, the required directive does this to work out if the input has data or not.
  15564. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  15565. *
  15566. * You can override this for input directives whose concept of being empty is different to the
  15567. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  15568. * implies empty.
  15569. *
  15570. * @param {*} value Reference to check.
  15571. * @returns {boolean} True if `value` is empty.
  15572. */
  15573. this.$isEmpty = function(value) {
  15574. return isUndefined(value) || value === '' || value === null || value !== value;
  15575. };
  15576. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  15577. invalidCount = 0, // used to easily determine if we are valid
  15578. $error = this.$error = {}; // keep invalid keys here
  15579. // Setup initial state of the control
  15580. $element.addClass(PRISTINE_CLASS);
  15581. toggleValidCss(true);
  15582. // convenience method for easy toggling of classes
  15583. function toggleValidCss(isValid, validationErrorKey) {
  15584. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  15585. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  15586. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  15587. }
  15588. /**
  15589. * @ngdoc method
  15590. * @name ngModel.NgModelController#$setValidity
  15591. *
  15592. * @description
  15593. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  15594. * does not notify form if given validator is already marked as invalid).
  15595. *
  15596. * This method should be called by validators - i.e. the parser or formatter functions.
  15597. *
  15598. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  15599. * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
  15600. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  15601. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  15602. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  15603. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  15604. */
  15605. this.$setValidity = function(validationErrorKey, isValid) {
  15606. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  15607. // jshint -W018
  15608. if ($error[validationErrorKey] === !isValid) return;
  15609. // jshint +W018
  15610. if (isValid) {
  15611. if ($error[validationErrorKey]) invalidCount--;
  15612. if (!invalidCount) {
  15613. toggleValidCss(true);
  15614. this.$valid = true;
  15615. this.$invalid = false;
  15616. }
  15617. } else {
  15618. toggleValidCss(false);
  15619. this.$invalid = true;
  15620. this.$valid = false;
  15621. invalidCount++;
  15622. }
  15623. $error[validationErrorKey] = !isValid;
  15624. toggleValidCss(isValid, validationErrorKey);
  15625. parentForm.$setValidity(validationErrorKey, isValid, this);
  15626. };
  15627. /**
  15628. * @ngdoc method
  15629. * @name ngModel.NgModelController#$setPristine
  15630. *
  15631. * @description
  15632. * Sets the control to its pristine state.
  15633. *
  15634. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  15635. * state (ng-pristine class).
  15636. */
  15637. this.$setPristine = function () {
  15638. this.$dirty = false;
  15639. this.$pristine = true;
  15640. $animate.removeClass($element, DIRTY_CLASS);
  15641. $animate.addClass($element, PRISTINE_CLASS);
  15642. };
  15643. /**
  15644. * @ngdoc method
  15645. * @name ngModel.NgModelController#$setViewValue
  15646. *
  15647. * @description
  15648. * Update the view value.
  15649. *
  15650. * This method should be called when the view value changes, typically from within a DOM event handler.
  15651. * For example {@link ng.directive:input input} and
  15652. * {@link ng.directive:select select} directives call it.
  15653. *
  15654. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  15655. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  15656. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  15657. *
  15658. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  15659. *
  15660. * Note that calling this function does not trigger a `$digest`.
  15661. *
  15662. * @param {string} value Value from the view.
  15663. */
  15664. this.$setViewValue = function(value) {
  15665. this.$viewValue = value;
  15666. // change to dirty
  15667. if (this.$pristine) {
  15668. this.$dirty = true;
  15669. this.$pristine = false;
  15670. $animate.removeClass($element, PRISTINE_CLASS);
  15671. $animate.addClass($element, DIRTY_CLASS);
  15672. parentForm.$setDirty();
  15673. }
  15674. forEach(this.$parsers, function(fn) {
  15675. value = fn(value);
  15676. });
  15677. if (this.$modelValue !== value) {
  15678. this.$modelValue = value;
  15679. ngModelSet($scope, value);
  15680. forEach(this.$viewChangeListeners, function(listener) {
  15681. try {
  15682. listener();
  15683. } catch(e) {
  15684. $exceptionHandler(e);
  15685. }
  15686. });
  15687. }
  15688. };
  15689. // model -> value
  15690. var ctrl = this;
  15691. $scope.$watch(function ngModelWatch() {
  15692. var value = ngModelGet($scope);
  15693. // if scope model value and ngModel value are out of sync
  15694. if (ctrl.$modelValue !== value) {
  15695. var formatters = ctrl.$formatters,
  15696. idx = formatters.length;
  15697. ctrl.$modelValue = value;
  15698. while(idx--) {
  15699. value = formatters[idx](value);
  15700. }
  15701. if (ctrl.$viewValue !== value) {
  15702. ctrl.$viewValue = value;
  15703. ctrl.$render();
  15704. }
  15705. }
  15706. return value;
  15707. });
  15708. }];
  15709. /**
  15710. * @ngdoc directive
  15711. * @name ngModel
  15712. *
  15713. * @element input
  15714. *
  15715. * @description
  15716. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  15717. * property on the scope using {@link ngModel.NgModelController NgModelController},
  15718. * which is created and exposed by this directive.
  15719. *
  15720. * `ngModel` is responsible for:
  15721. *
  15722. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  15723. * require.
  15724. * - Providing validation behavior (i.e. required, number, email, url).
  15725. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  15726. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  15727. * - Registering the control with its parent {@link ng.directive:form form}.
  15728. *
  15729. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  15730. * current scope. If the property doesn't already exist on this scope, it will be created
  15731. * implicitly and added to the scope.
  15732. *
  15733. * For best practices on using `ngModel`, see:
  15734. *
  15735. * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
  15736. *
  15737. * For basic examples, how to use `ngModel`, see:
  15738. *
  15739. * - {@link ng.directive:input input}
  15740. * - {@link input[text] text}
  15741. * - {@link input[checkbox] checkbox}
  15742. * - {@link input[radio] radio}
  15743. * - {@link input[number] number}
  15744. * - {@link input[email] email}
  15745. * - {@link input[url] url}
  15746. * - {@link ng.directive:select select}
  15747. * - {@link ng.directive:textarea textarea}
  15748. *
  15749. * # CSS classes
  15750. * The following CSS classes are added and removed on the associated input/select/textarea element
  15751. * depending on the validity of the model.
  15752. *
  15753. * - `ng-valid` is set if the model is valid.
  15754. * - `ng-invalid` is set if the model is invalid.
  15755. * - `ng-pristine` is set if the model is pristine.
  15756. * - `ng-dirty` is set if the model is dirty.
  15757. *
  15758. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  15759. *
  15760. * ## Animation Hooks
  15761. *
  15762. * Animations within models are triggered when any of the associated CSS classes are added and removed
  15763. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  15764. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  15765. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  15766. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  15767. *
  15768. * The following example shows a simple way to utilize CSS transitions to style an input element
  15769. * that has been rendered as invalid after it has been validated:
  15770. *
  15771. * <pre>
  15772. * //be sure to include ngAnimate as a module to hook into more
  15773. * //advanced animations
  15774. * .my-input {
  15775. * transition:0.5s linear all;
  15776. * background: white;
  15777. * }
  15778. * .my-input.ng-invalid {
  15779. * background: red;
  15780. * color:white;
  15781. * }
  15782. * </pre>
  15783. *
  15784. * @example
  15785. * <example deps="angular-animate.js" animations="true" fixBase="true">
  15786. <file name="index.html">
  15787. <script>
  15788. function Ctrl($scope) {
  15789. $scope.val = '1';
  15790. }
  15791. </script>
  15792. <style>
  15793. .my-input {
  15794. -webkit-transition:all linear 0.5s;
  15795. transition:all linear 0.5s;
  15796. background: transparent;
  15797. }
  15798. .my-input.ng-invalid {
  15799. color:white;
  15800. background: red;
  15801. }
  15802. </style>
  15803. Update input to see transitions when valid/invalid.
  15804. Integer is a valid value.
  15805. <form name="testForm" ng-controller="Ctrl">
  15806. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  15807. </form>
  15808. </file>
  15809. * </example>
  15810. */
  15811. var ngModelDirective = function() {
  15812. return {
  15813. require: ['ngModel', '^?form'],
  15814. controller: NgModelController,
  15815. link: function(scope, element, attr, ctrls) {
  15816. // notify others, especially parent forms
  15817. var modelCtrl = ctrls[0],
  15818. formCtrl = ctrls[1] || nullFormCtrl;
  15819. formCtrl.$addControl(modelCtrl);
  15820. scope.$on('$destroy', function() {
  15821. formCtrl.$removeControl(modelCtrl);
  15822. });
  15823. }
  15824. };
  15825. };
  15826. /**
  15827. * @ngdoc directive
  15828. * @name ngChange
  15829. *
  15830. * @description
  15831. * Evaluate the given expression when the user changes the input.
  15832. * The expression is evaluated immediately, unlike the JavaScript onchange event
  15833. * which only triggers at the end of a change (usually, when the user leaves the
  15834. * form element or presses the return key).
  15835. * The expression is not evaluated when the value change is coming from the model.
  15836. *
  15837. * Note, this directive requires `ngModel` to be present.
  15838. *
  15839. * @element input
  15840. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  15841. * in input value.
  15842. *
  15843. * @example
  15844. * <example name="ngChange-directive">
  15845. * <file name="index.html">
  15846. * <script>
  15847. * function Controller($scope) {
  15848. * $scope.counter = 0;
  15849. * $scope.change = function() {
  15850. * $scope.counter++;
  15851. * };
  15852. * }
  15853. * </script>
  15854. * <div ng-controller="Controller">
  15855. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  15856. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  15857. * <label for="ng-change-example2">Confirmed</label><br />
  15858. * <tt>debug = {{confirmed}}</tt><br/>
  15859. * <tt>counter = {{counter}}</tt><br/>
  15860. * </div>
  15861. * </file>
  15862. * <file name="protractor.js" type="protractor">
  15863. * var counter = element(by.binding('counter'));
  15864. * var debug = element(by.binding('confirmed'));
  15865. *
  15866. * it('should evaluate the expression if changing from view', function() {
  15867. * expect(counter.getText()).toContain('0');
  15868. *
  15869. * element(by.id('ng-change-example1')).click();
  15870. *
  15871. * expect(counter.getText()).toContain('1');
  15872. * expect(debug.getText()).toContain('true');
  15873. * });
  15874. *
  15875. * it('should not evaluate the expression if changing from model', function() {
  15876. * element(by.id('ng-change-example2')).click();
  15877. * expect(counter.getText()).toContain('0');
  15878. * expect(debug.getText()).toContain('true');
  15879. * });
  15880. * </file>
  15881. * </example>
  15882. */
  15883. var ngChangeDirective = valueFn({
  15884. require: 'ngModel',
  15885. link: function(scope, element, attr, ctrl) {
  15886. ctrl.$viewChangeListeners.push(function() {
  15887. scope.$eval(attr.ngChange);
  15888. });
  15889. }
  15890. });
  15891. var requiredDirective = function() {
  15892. return {
  15893. require: '?ngModel',
  15894. link: function(scope, elm, attr, ctrl) {
  15895. if (!ctrl) return;
  15896. attr.required = true; // force truthy in case we are on non input element
  15897. var validator = function(value) {
  15898. if (attr.required && ctrl.$isEmpty(value)) {
  15899. ctrl.$setValidity('required', false);
  15900. return;
  15901. } else {
  15902. ctrl.$setValidity('required', true);
  15903. return value;
  15904. }
  15905. };
  15906. ctrl.$formatters.push(validator);
  15907. ctrl.$parsers.unshift(validator);
  15908. attr.$observe('required', function() {
  15909. validator(ctrl.$viewValue);
  15910. });
  15911. }
  15912. };
  15913. };
  15914. /**
  15915. * @ngdoc directive
  15916. * @name ngList
  15917. *
  15918. * @description
  15919. * Text input that converts between a delimited string and an array of strings. The delimiter
  15920. * can be a fixed string (by default a comma) or a regular expression.
  15921. *
  15922. * @element input
  15923. * @param {string=} ngList optional delimiter that should be used to split the value. If
  15924. * specified in form `/something/` then the value will be converted into a regular expression.
  15925. *
  15926. * @example
  15927. <example name="ngList-directive">
  15928. <file name="index.html">
  15929. <script>
  15930. function Ctrl($scope) {
  15931. $scope.names = ['igor', 'misko', 'vojta'];
  15932. }
  15933. </script>
  15934. <form name="myForm" ng-controller="Ctrl">
  15935. List: <input name="namesInput" ng-model="names" ng-list required>
  15936. <span class="error" ng-show="myForm.namesInput.$error.required">
  15937. Required!</span>
  15938. <br>
  15939. <tt>names = {{names}}</tt><br/>
  15940. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  15941. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  15942. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15943. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15944. </form>
  15945. </file>
  15946. <file name="protractor.js" type="protractor">
  15947. var listInput = element(by.model('names'));
  15948. var names = element(by.binding('{{names}}'));
  15949. var valid = element(by.binding('myForm.namesInput.$valid'));
  15950. var error = element(by.css('span.error'));
  15951. it('should initialize to model', function() {
  15952. expect(names.getText()).toContain('["igor","misko","vojta"]');
  15953. expect(valid.getText()).toContain('true');
  15954. expect(error.getCssValue('display')).toBe('none');
  15955. });
  15956. it('should be invalid if empty', function() {
  15957. listInput.clear();
  15958. listInput.sendKeys('');
  15959. expect(names.getText()).toContain('');
  15960. expect(valid.getText()).toContain('false');
  15961. expect(error.getCssValue('display')).not.toBe('none'); });
  15962. </file>
  15963. </example>
  15964. */
  15965. var ngListDirective = function() {
  15966. return {
  15967. require: 'ngModel',
  15968. link: function(scope, element, attr, ctrl) {
  15969. var match = /\/(.*)\//.exec(attr.ngList),
  15970. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  15971. var parse = function(viewValue) {
  15972. // If the viewValue is invalid (say required but empty) it will be `undefined`
  15973. if (isUndefined(viewValue)) return;
  15974. var list = [];
  15975. if (viewValue) {
  15976. forEach(viewValue.split(separator), function(value) {
  15977. if (value) list.push(trim(value));
  15978. });
  15979. }
  15980. return list;
  15981. };
  15982. ctrl.$parsers.push(parse);
  15983. ctrl.$formatters.push(function(value) {
  15984. if (isArray(value)) {
  15985. return value.join(', ');
  15986. }
  15987. return undefined;
  15988. });
  15989. // Override the standard $isEmpty because an empty array means the input is empty.
  15990. ctrl.$isEmpty = function(value) {
  15991. return !value || !value.length;
  15992. };
  15993. }
  15994. };
  15995. };
  15996. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  15997. /**
  15998. * @ngdoc directive
  15999. * @name ngValue
  16000. *
  16001. * @description
  16002. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16003. * that when the element is selected, the `ngModel` of that element is set to the
  16004. * bound value.
  16005. *
  16006. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16007. * shown below.
  16008. *
  16009. * @element input
  16010. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16011. * of the `input` element
  16012. *
  16013. * @example
  16014. <example name="ngValue-directive">
  16015. <file name="index.html">
  16016. <script>
  16017. function Ctrl($scope) {
  16018. $scope.names = ['pizza', 'unicorns', 'robots'];
  16019. $scope.my = { favorite: 'unicorns' };
  16020. }
  16021. </script>
  16022. <form ng-controller="Ctrl">
  16023. <h2>Which is your favorite?</h2>
  16024. <label ng-repeat="name in names" for="{{name}}">
  16025. {{name}}
  16026. <input type="radio"
  16027. ng-model="my.favorite"
  16028. ng-value="name"
  16029. id="{{name}}"
  16030. name="favorite">
  16031. </label>
  16032. <div>You chose {{my.favorite}}</div>
  16033. </form>
  16034. </file>
  16035. <file name="protractor.js" type="protractor">
  16036. var favorite = element(by.binding('my.favorite'));
  16037. it('should initialize to model', function() {
  16038. expect(favorite.getText()).toContain('unicorns');
  16039. });
  16040. it('should bind the values to the inputs', function() {
  16041. element.all(by.model('my.favorite')).get(0).click();
  16042. expect(favorite.getText()).toContain('pizza');
  16043. });
  16044. </file>
  16045. </example>
  16046. */
  16047. var ngValueDirective = function() {
  16048. return {
  16049. priority: 100,
  16050. compile: function(tpl, tplAttr) {
  16051. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16052. return function ngValueConstantLink(scope, elm, attr) {
  16053. attr.$set('value', scope.$eval(attr.ngValue));
  16054. };
  16055. } else {
  16056. return function ngValueLink(scope, elm, attr) {
  16057. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16058. attr.$set('value', value);
  16059. });
  16060. };
  16061. }
  16062. }
  16063. };
  16064. };
  16065. /**
  16066. * @ngdoc directive
  16067. * @name ngBind
  16068. * @restrict AC
  16069. *
  16070. * @description
  16071. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16072. * with the value of a given expression, and to update the text content when the value of that
  16073. * expression changes.
  16074. *
  16075. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16076. * `{{ expression }}` which is similar but less verbose.
  16077. *
  16078. * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
  16079. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16080. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16081. *
  16082. * An alternative solution to this problem would be using the
  16083. * {@link ng.directive:ngCloak ngCloak} directive.
  16084. *
  16085. *
  16086. * @element ANY
  16087. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16088. *
  16089. * @example
  16090. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16091. <example>
  16092. <file name="index.html">
  16093. <script>
  16094. function Ctrl($scope) {
  16095. $scope.name = 'Whirled';
  16096. }
  16097. </script>
  16098. <div ng-controller="Ctrl">
  16099. Enter name: <input type="text" ng-model="name"><br>
  16100. Hello <span ng-bind="name"></span>!
  16101. </div>
  16102. </file>
  16103. <file name="protractor.js" type="protractor">
  16104. it('should check ng-bind', function() {
  16105. var nameInput = element(by.model('name'));
  16106. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16107. nameInput.clear();
  16108. nameInput.sendKeys('world');
  16109. expect(element(by.binding('name')).getText()).toBe('world');
  16110. });
  16111. </file>
  16112. </example>
  16113. */
  16114. var ngBindDirective = ngDirective(function(scope, element, attr) {
  16115. element.addClass('ng-binding').data('$binding', attr.ngBind);
  16116. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16117. // We are purposefully using == here rather than === because we want to
  16118. // catch when value is "null or undefined"
  16119. // jshint -W041
  16120. element.text(value == undefined ? '' : value);
  16121. });
  16122. });
  16123. /**
  16124. * @ngdoc directive
  16125. * @name ngBindTemplate
  16126. *
  16127. * @description
  16128. * The `ngBindTemplate` directive specifies that the element
  16129. * text content should be replaced with the interpolation of the template
  16130. * in the `ngBindTemplate` attribute.
  16131. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16132. * expressions. This directive is needed since some HTML elements
  16133. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16134. *
  16135. * @element ANY
  16136. * @param {string} ngBindTemplate template of form
  16137. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16138. *
  16139. * @example
  16140. * Try it here: enter text in text box and watch the greeting change.
  16141. <example>
  16142. <file name="index.html">
  16143. <script>
  16144. function Ctrl($scope) {
  16145. $scope.salutation = 'Hello';
  16146. $scope.name = 'World';
  16147. }
  16148. </script>
  16149. <div ng-controller="Ctrl">
  16150. Salutation: <input type="text" ng-model="salutation"><br>
  16151. Name: <input type="text" ng-model="name"><br>
  16152. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16153. </div>
  16154. </file>
  16155. <file name="protractor.js" type="protractor">
  16156. it('should check ng-bind', function() {
  16157. var salutationElem = element(by.binding('salutation'));
  16158. var salutationInput = element(by.model('salutation'));
  16159. var nameInput = element(by.model('name'));
  16160. expect(salutationElem.getText()).toBe('Hello World!');
  16161. salutationInput.clear();
  16162. salutationInput.sendKeys('Greetings');
  16163. nameInput.clear();
  16164. nameInput.sendKeys('user');
  16165. expect(salutationElem.getText()).toBe('Greetings user!');
  16166. });
  16167. </file>
  16168. </example>
  16169. */
  16170. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16171. return function(scope, element, attr) {
  16172. // TODO: move this to scenario runner
  16173. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16174. element.addClass('ng-binding').data('$binding', interpolateFn);
  16175. attr.$observe('ngBindTemplate', function(value) {
  16176. element.text(value);
  16177. });
  16178. };
  16179. }];
  16180. /**
  16181. * @ngdoc directive
  16182. * @name ngBindHtml
  16183. *
  16184. * @description
  16185. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16186. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16187. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16188. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16189. * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
  16190. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16191. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16192. *
  16193. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16194. * will have an exception (instead of an exploit.)
  16195. *
  16196. * @element ANY
  16197. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16198. *
  16199. * @example
  16200. Try it here: enter text in text box and watch the greeting change.
  16201. <example module="ngBindHtmlExample" deps="angular-sanitize.js">
  16202. <file name="index.html">
  16203. <div ng-controller="ngBindHtmlCtrl">
  16204. <p ng-bind-html="myHTML"></p>
  16205. </div>
  16206. </file>
  16207. <file name="script.js">
  16208. angular.module('ngBindHtmlExample', ['ngSanitize'])
  16209. .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
  16210. $scope.myHTML =
  16211. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
  16212. }]);
  16213. </file>
  16214. <file name="protractor.js" type="protractor">
  16215. it('should check ng-bind-html', function() {
  16216. expect(element(by.binding('myHTML')).getText()).toBe(
  16217. 'I am an HTMLstring with links! and other stuff');
  16218. });
  16219. </file>
  16220. </example>
  16221. */
  16222. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16223. return function(scope, element, attr) {
  16224. element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
  16225. var parsed = $parse(attr.ngBindHtml);
  16226. function getStringValue() { return (parsed(scope) || '').toString(); }
  16227. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16228. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16229. });
  16230. };
  16231. }];
  16232. function classDirective(name, selector) {
  16233. name = 'ngClass' + name;
  16234. return ['$animate', function($animate) {
  16235. return {
  16236. restrict: 'AC',
  16237. link: function(scope, element, attr) {
  16238. var oldVal;
  16239. scope.$watch(attr[name], ngClassWatchAction, true);
  16240. attr.$observe('class', function(value) {
  16241. ngClassWatchAction(scope.$eval(attr[name]));
  16242. });
  16243. if (name !== 'ngClass') {
  16244. scope.$watch('$index', function($index, old$index) {
  16245. // jshint bitwise: false
  16246. var mod = $index & 1;
  16247. if (mod !== old$index & 1) {
  16248. var classes = arrayClasses(scope.$eval(attr[name]));
  16249. mod === selector ?
  16250. addClasses(classes) :
  16251. removeClasses(classes);
  16252. }
  16253. });
  16254. }
  16255. function addClasses(classes) {
  16256. var newClasses = digestClassCounts(classes, 1);
  16257. attr.$addClass(newClasses);
  16258. }
  16259. function removeClasses(classes) {
  16260. var newClasses = digestClassCounts(classes, -1);
  16261. attr.$removeClass(newClasses);
  16262. }
  16263. function digestClassCounts (classes, count) {
  16264. var classCounts = element.data('$classCounts') || {};
  16265. var classesToUpdate = [];
  16266. forEach(classes, function (className) {
  16267. if (count > 0 || classCounts[className]) {
  16268. classCounts[className] = (classCounts[className] || 0) + count;
  16269. if (classCounts[className] === +(count > 0)) {
  16270. classesToUpdate.push(className);
  16271. }
  16272. }
  16273. });
  16274. element.data('$classCounts', classCounts);
  16275. return classesToUpdate.join(' ');
  16276. }
  16277. function updateClasses (oldClasses, newClasses) {
  16278. var toAdd = arrayDifference(newClasses, oldClasses);
  16279. var toRemove = arrayDifference(oldClasses, newClasses);
  16280. toRemove = digestClassCounts(toRemove, -1);
  16281. toAdd = digestClassCounts(toAdd, 1);
  16282. if (toAdd.length === 0) {
  16283. $animate.removeClass(element, toRemove);
  16284. } else if (toRemove.length === 0) {
  16285. $animate.addClass(element, toAdd);
  16286. } else {
  16287. $animate.setClass(element, toAdd, toRemove);
  16288. }
  16289. }
  16290. function ngClassWatchAction(newVal) {
  16291. if (selector === true || scope.$index % 2 === selector) {
  16292. var newClasses = arrayClasses(newVal || []);
  16293. if (!oldVal) {
  16294. addClasses(newClasses);
  16295. } else if (!equals(newVal,oldVal)) {
  16296. var oldClasses = arrayClasses(oldVal);
  16297. updateClasses(oldClasses, newClasses);
  16298. }
  16299. }
  16300. oldVal = copy(newVal);
  16301. }
  16302. }
  16303. };
  16304. function arrayDifference(tokens1, tokens2) {
  16305. var values = [];
  16306. outer:
  16307. for(var i = 0; i < tokens1.length; i++) {
  16308. var token = tokens1[i];
  16309. for(var j = 0; j < tokens2.length; j++) {
  16310. if(token == tokens2[j]) continue outer;
  16311. }
  16312. values.push(token);
  16313. }
  16314. return values;
  16315. }
  16316. function arrayClasses (classVal) {
  16317. if (isArray(classVal)) {
  16318. return classVal;
  16319. } else if (isString(classVal)) {
  16320. return classVal.split(' ');
  16321. } else if (isObject(classVal)) {
  16322. var classes = [], i = 0;
  16323. forEach(classVal, function(v, k) {
  16324. if (v) {
  16325. classes.push(k);
  16326. }
  16327. });
  16328. return classes;
  16329. }
  16330. return classVal;
  16331. }
  16332. }];
  16333. }
  16334. /**
  16335. * @ngdoc directive
  16336. * @name ngClass
  16337. * @restrict AC
  16338. *
  16339. * @description
  16340. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16341. * an expression that represents all classes to be added.
  16342. *
  16343. * The directive operates in three different ways, depending on which of three types the expression
  16344. * evaluates to:
  16345. *
  16346. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16347. * names.
  16348. *
  16349. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16350. * one or more space-delimited class names.
  16351. *
  16352. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16353. * object with a truthy value the corresponding key is used as a class name.
  16354. *
  16355. * The directive won't add duplicate classes if a particular class was already set.
  16356. *
  16357. * When the expression changes, the previously added classes are removed and only then the
  16358. * new classes are added.
  16359. *
  16360. * @animations
  16361. * add - happens just before the class is applied to the element
  16362. * remove - happens just before the class is removed from the element
  16363. *
  16364. * @element ANY
  16365. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16366. * of the evaluation can be a string representing space delimited class
  16367. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16368. * names of the properties whose values are truthy will be added as css classes to the
  16369. * element.
  16370. *
  16371. * @example Example that demonstrates basic bindings via ngClass directive.
  16372. <example>
  16373. <file name="index.html">
  16374. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16375. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16376. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16377. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16378. <hr>
  16379. <p ng-class="style">Using String Syntax</p>
  16380. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16381. <hr>
  16382. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16383. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16384. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16385. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16386. </file>
  16387. <file name="style.css">
  16388. .strike {
  16389. text-decoration: line-through;
  16390. }
  16391. .bold {
  16392. font-weight: bold;
  16393. }
  16394. .red {
  16395. color: red;
  16396. }
  16397. </file>
  16398. <file name="protractor.js" type="protractor">
  16399. var ps = element.all(by.css('p'));
  16400. it('should let you toggle the class', function() {
  16401. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16402. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16403. element(by.model('important')).click();
  16404. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16405. element(by.model('error')).click();
  16406. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16407. });
  16408. it('should let you toggle string example', function() {
  16409. expect(ps.get(1).getAttribute('class')).toBe('');
  16410. element(by.model('style')).clear();
  16411. element(by.model('style')).sendKeys('red');
  16412. expect(ps.get(1).getAttribute('class')).toBe('red');
  16413. });
  16414. it('array example should have 3 classes', function() {
  16415. expect(ps.last().getAttribute('class')).toBe('');
  16416. element(by.model('style1')).sendKeys('bold');
  16417. element(by.model('style2')).sendKeys('strike');
  16418. element(by.model('style3')).sendKeys('red');
  16419. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16420. });
  16421. </file>
  16422. </example>
  16423. ## Animations
  16424. The example below demonstrates how to perform animations using ngClass.
  16425. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  16426. <file name="index.html">
  16427. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  16428. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  16429. <br>
  16430. <span class="base-class" ng-class="myVar">Sample Text</span>
  16431. </file>
  16432. <file name="style.css">
  16433. .base-class {
  16434. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16435. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16436. }
  16437. .base-class.my-class {
  16438. color: red;
  16439. font-size:3em;
  16440. }
  16441. </file>
  16442. <file name="protractor.js" type="protractor">
  16443. it('should check ng-class', function() {
  16444. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16445. toMatch(/my-class/);
  16446. element(by.id('setbtn')).click();
  16447. expect(element(by.css('.base-class')).getAttribute('class')).
  16448. toMatch(/my-class/);
  16449. element(by.id('clearbtn')).click();
  16450. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16451. toMatch(/my-class/);
  16452. });
  16453. </file>
  16454. </example>
  16455. ## ngClass and pre-existing CSS3 Transitions/Animations
  16456. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  16457. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  16458. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  16459. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  16460. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  16461. */
  16462. var ngClassDirective = classDirective('', true);
  16463. /**
  16464. * @ngdoc directive
  16465. * @name ngClassOdd
  16466. * @restrict AC
  16467. *
  16468. * @description
  16469. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16470. * {@link ng.directive:ngClass ngClass}, except they work in
  16471. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16472. *
  16473. * This directive can be applied only within the scope of an
  16474. * {@link ng.directive:ngRepeat ngRepeat}.
  16475. *
  16476. * @element ANY
  16477. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  16478. * of the evaluation can be a string representing space delimited class names or an array.
  16479. *
  16480. * @example
  16481. <example>
  16482. <file name="index.html">
  16483. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16484. <li ng-repeat="name in names">
  16485. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16486. {{name}}
  16487. </span>
  16488. </li>
  16489. </ol>
  16490. </file>
  16491. <file name="style.css">
  16492. .odd {
  16493. color: red;
  16494. }
  16495. .even {
  16496. color: blue;
  16497. }
  16498. </file>
  16499. <file name="protractor.js" type="protractor">
  16500. it('should check ng-class-odd and ng-class-even', function() {
  16501. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16502. toMatch(/odd/);
  16503. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16504. toMatch(/even/);
  16505. });
  16506. </file>
  16507. </example>
  16508. */
  16509. var ngClassOddDirective = classDirective('Odd', 0);
  16510. /**
  16511. * @ngdoc directive
  16512. * @name ngClassEven
  16513. * @restrict AC
  16514. *
  16515. * @description
  16516. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16517. * {@link ng.directive:ngClass ngClass}, except they work in
  16518. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16519. *
  16520. * This directive can be applied only within the scope of an
  16521. * {@link ng.directive:ngRepeat ngRepeat}.
  16522. *
  16523. * @element ANY
  16524. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  16525. * result of the evaluation can be a string representing space delimited class names or an array.
  16526. *
  16527. * @example
  16528. <example>
  16529. <file name="index.html">
  16530. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16531. <li ng-repeat="name in names">
  16532. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16533. {{name}} &nbsp; &nbsp; &nbsp;
  16534. </span>
  16535. </li>
  16536. </ol>
  16537. </file>
  16538. <file name="style.css">
  16539. .odd {
  16540. color: red;
  16541. }
  16542. .even {
  16543. color: blue;
  16544. }
  16545. </file>
  16546. <file name="protractor.js" type="protractor">
  16547. it('should check ng-class-odd and ng-class-even', function() {
  16548. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16549. toMatch(/odd/);
  16550. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16551. toMatch(/even/);
  16552. });
  16553. </file>
  16554. </example>
  16555. */
  16556. var ngClassEvenDirective = classDirective('Even', 1);
  16557. /**
  16558. * @ngdoc directive
  16559. * @name ngCloak
  16560. * @restrict AC
  16561. *
  16562. * @description
  16563. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  16564. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  16565. * directive to avoid the undesirable flicker effect caused by the html template display.
  16566. *
  16567. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  16568. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  16569. * of the browser view.
  16570. *
  16571. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  16572. * `angular.min.js`.
  16573. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  16574. *
  16575. * ```css
  16576. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  16577. * display: none !important;
  16578. * }
  16579. * ```
  16580. *
  16581. * When this css rule is loaded by the browser, all html elements (including their children) that
  16582. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  16583. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  16584. * the compiled element visible.
  16585. *
  16586. * For the best result, the `angular.js` script must be loaded in the head section of the html
  16587. * document; alternatively, the css rule above must be included in the external stylesheet of the
  16588. * application.
  16589. *
  16590. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  16591. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  16592. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  16593. *
  16594. * @element ANY
  16595. *
  16596. * @example
  16597. <example>
  16598. <file name="index.html">
  16599. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  16600. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  16601. </file>
  16602. <file name="protractor.js" type="protractor">
  16603. it('should remove the template directive and css class', function() {
  16604. expect($('#template1').getAttribute('ng-cloak')).
  16605. toBeNull();
  16606. expect($('#template2').getAttribute('ng-cloak')).
  16607. toBeNull();
  16608. });
  16609. </file>
  16610. </example>
  16611. *
  16612. */
  16613. var ngCloakDirective = ngDirective({
  16614. compile: function(element, attr) {
  16615. attr.$set('ngCloak', undefined);
  16616. element.removeClass('ng-cloak');
  16617. }
  16618. });
  16619. /**
  16620. * @ngdoc directive
  16621. * @name ngController
  16622. *
  16623. * @description
  16624. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  16625. * supports the principles behind the Model-View-Controller design pattern.
  16626. *
  16627. * MVC components in angular:
  16628. *
  16629. * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
  16630. * are accessed through bindings.
  16631. * * View — The template (HTML with data bindings) that is rendered into the View.
  16632. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  16633. * logic behind the application to decorate the scope with functions and values
  16634. *
  16635. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  16636. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  16637. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  16638. * and executed twice.
  16639. *
  16640. * @element ANY
  16641. * @scope
  16642. * @param {expression} ngController Name of a globally accessible constructor function or an
  16643. * {@link guide/expression expression} that on the current scope evaluates to a
  16644. * constructor function. The controller instance can be published into a scope property
  16645. * by specifying `as propertyName`.
  16646. *
  16647. * @example
  16648. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  16649. * greeting are methods declared on the controller (see source tab). These methods can
  16650. * easily be called from the angular markup. Notice that the scope becomes the `this` for the
  16651. * controller's instance. This allows for easy access to the view data from the controller. Also
  16652. * notice that any changes to the data are automatically reflected in the View without the need
  16653. * for a manual update. The example is shown in two different declaration styles you may use
  16654. * according to preference.
  16655. <example>
  16656. <file name="index.html">
  16657. <script>
  16658. function SettingsController1() {
  16659. this.name = "John Smith";
  16660. this.contacts = [
  16661. {type: 'phone', value: '408 555 1212'},
  16662. {type: 'email', value: 'john.smith@example.org'} ];
  16663. };
  16664. SettingsController1.prototype.greet = function() {
  16665. alert(this.name);
  16666. };
  16667. SettingsController1.prototype.addContact = function() {
  16668. this.contacts.push({type: 'email', value: 'yourname@example.org'});
  16669. };
  16670. SettingsController1.prototype.removeContact = function(contactToRemove) {
  16671. var index = this.contacts.indexOf(contactToRemove);
  16672. this.contacts.splice(index, 1);
  16673. };
  16674. SettingsController1.prototype.clearContact = function(contact) {
  16675. contact.type = 'phone';
  16676. contact.value = '';
  16677. };
  16678. </script>
  16679. <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  16680. Name: <input type="text" ng-model="settings.name"/>
  16681. [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  16682. Contact:
  16683. <ul>
  16684. <li ng-repeat="contact in settings.contacts">
  16685. <select ng-model="contact.type">
  16686. <option>phone</option>
  16687. <option>email</option>
  16688. </select>
  16689. <input type="text" ng-model="contact.value"/>
  16690. [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  16691. | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  16692. </li>
  16693. <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  16694. </ul>
  16695. </div>
  16696. </file>
  16697. <file name="protractor.js" type="protractor">
  16698. it('should check controller as', function() {
  16699. var container = element(by.id('ctrl-as-exmpl'));
  16700. expect(container.findElement(by.model('settings.name'))
  16701. .getAttribute('value')).toBe('John Smith');
  16702. var firstRepeat =
  16703. container.findElement(by.repeater('contact in settings.contacts').row(0));
  16704. var secondRepeat =
  16705. container.findElement(by.repeater('contact in settings.contacts').row(1));
  16706. expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16707. .toBe('408 555 1212');
  16708. expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16709. .toBe('john.smith@example.org');
  16710. firstRepeat.findElement(by.linkText('clear')).click();
  16711. expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16712. .toBe('');
  16713. container.findElement(by.linkText('add')).click();
  16714. expect(container.findElement(by.repeater('contact in settings.contacts').row(2))
  16715. .findElement(by.model('contact.value'))
  16716. .getAttribute('value'))
  16717. .toBe('yourname@example.org');
  16718. });
  16719. </file>
  16720. </example>
  16721. <example>
  16722. <file name="index.html">
  16723. <script>
  16724. function SettingsController2($scope) {
  16725. $scope.name = "John Smith";
  16726. $scope.contacts = [
  16727. {type:'phone', value:'408 555 1212'},
  16728. {type:'email', value:'john.smith@example.org'} ];
  16729. $scope.greet = function() {
  16730. alert(this.name);
  16731. };
  16732. $scope.addContact = function() {
  16733. this.contacts.push({type:'email', value:'yourname@example.org'});
  16734. };
  16735. $scope.removeContact = function(contactToRemove) {
  16736. var index = this.contacts.indexOf(contactToRemove);
  16737. this.contacts.splice(index, 1);
  16738. };
  16739. $scope.clearContact = function(contact) {
  16740. contact.type = 'phone';
  16741. contact.value = '';
  16742. };
  16743. }
  16744. </script>
  16745. <div id="ctrl-exmpl" ng-controller="SettingsController2">
  16746. Name: <input type="text" ng-model="name"/>
  16747. [ <a href="" ng-click="greet()">greet</a> ]<br/>
  16748. Contact:
  16749. <ul>
  16750. <li ng-repeat="contact in contacts">
  16751. <select ng-model="contact.type">
  16752. <option>phone</option>
  16753. <option>email</option>
  16754. </select>
  16755. <input type="text" ng-model="contact.value"/>
  16756. [ <a href="" ng-click="clearContact(contact)">clear</a>
  16757. | <a href="" ng-click="removeContact(contact)">X</a> ]
  16758. </li>
  16759. <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  16760. </ul>
  16761. </div>
  16762. </file>
  16763. <file name="protractor.js" type="protractor">
  16764. it('should check controller', function() {
  16765. var container = element(by.id('ctrl-exmpl'));
  16766. expect(container.findElement(by.model('name'))
  16767. .getAttribute('value')).toBe('John Smith');
  16768. var firstRepeat =
  16769. container.findElement(by.repeater('contact in contacts').row(0));
  16770. var secondRepeat =
  16771. container.findElement(by.repeater('contact in contacts').row(1));
  16772. expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16773. .toBe('408 555 1212');
  16774. expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16775. .toBe('john.smith@example.org');
  16776. firstRepeat.findElement(by.linkText('clear')).click();
  16777. expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
  16778. .toBe('');
  16779. container.findElement(by.linkText('add')).click();
  16780. expect(container.findElement(by.repeater('contact in contacts').row(2))
  16781. .findElement(by.model('contact.value'))
  16782. .getAttribute('value'))
  16783. .toBe('yourname@example.org');
  16784. });
  16785. </file>
  16786. </example>
  16787. */
  16788. var ngControllerDirective = [function() {
  16789. return {
  16790. scope: true,
  16791. controller: '@',
  16792. priority: 500
  16793. };
  16794. }];
  16795. /**
  16796. * @ngdoc directive
  16797. * @name ngCsp
  16798. *
  16799. * @element html
  16800. * @description
  16801. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  16802. *
  16803. * This is necessary when developing things like Google Chrome Extensions.
  16804. *
  16805. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  16806. * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
  16807. * any of these restrictions.
  16808. *
  16809. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  16810. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  16811. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  16812. * be raised.
  16813. *
  16814. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  16815. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  16816. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  16817. *
  16818. * In order to use this feature put the `ngCsp` directive on the root element of the application.
  16819. *
  16820. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  16821. *
  16822. * @example
  16823. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  16824. ```html
  16825. <!doctype html>
  16826. <html ng-app ng-csp>
  16827. ...
  16828. ...
  16829. </html>
  16830. ```
  16831. */
  16832. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
  16833. // the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
  16834. // anywhere in the current doc
  16835. /**
  16836. * @ngdoc directive
  16837. * @name ngClick
  16838. *
  16839. * @description
  16840. * The ngClick directive allows you to specify custom behavior when
  16841. * an element is clicked.
  16842. *
  16843. * @element ANY
  16844. * @priority 0
  16845. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  16846. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  16847. *
  16848. * @example
  16849. <example>
  16850. <file name="index.html">
  16851. <button ng-click="count = count + 1" ng-init="count=0">
  16852. Increment
  16853. </button>
  16854. count: {{count}}
  16855. </file>
  16856. <file name="protractor.js" type="protractor">
  16857. it('should check ng-click', function() {
  16858. expect(element(by.binding('count')).getText()).toMatch('0');
  16859. element(by.css('button')).click();
  16860. expect(element(by.binding('count')).getText()).toMatch('1');
  16861. });
  16862. </file>
  16863. </example>
  16864. */
  16865. /*
  16866. * A directive that allows creation of custom onclick handlers that are defined as angular
  16867. * expressions and are compiled and executed within the current scope.
  16868. *
  16869. * Events that are handled via these handler are always configured not to propagate further.
  16870. */
  16871. var ngEventDirectives = {};
  16872. forEach(
  16873. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  16874. function(name) {
  16875. var directiveName = directiveNormalize('ng-' + name);
  16876. ngEventDirectives[directiveName] = ['$parse', function($parse) {
  16877. return {
  16878. compile: function($element, attr) {
  16879. var fn = $parse(attr[directiveName]);
  16880. return function(scope, element, attr) {
  16881. element.on(lowercase(name), function(event) {
  16882. scope.$apply(function() {
  16883. fn(scope, {$event:event});
  16884. });
  16885. });
  16886. };
  16887. }
  16888. };
  16889. }];
  16890. }
  16891. );
  16892. /**
  16893. * @ngdoc directive
  16894. * @name ngDblclick
  16895. *
  16896. * @description
  16897. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  16898. *
  16899. * @element ANY
  16900. * @priority 0
  16901. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  16902. * a dblclick. (The Event object is available as `$event`)
  16903. *
  16904. * @example
  16905. <example>
  16906. <file name="index.html">
  16907. <button ng-dblclick="count = count + 1" ng-init="count=0">
  16908. Increment (on double click)
  16909. </button>
  16910. count: {{count}}
  16911. </file>
  16912. </example>
  16913. */
  16914. /**
  16915. * @ngdoc directive
  16916. * @name ngMousedown
  16917. *
  16918. * @description
  16919. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  16920. *
  16921. * @element ANY
  16922. * @priority 0
  16923. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  16924. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  16925. *
  16926. * @example
  16927. <example>
  16928. <file name="index.html">
  16929. <button ng-mousedown="count = count + 1" ng-init="count=0">
  16930. Increment (on mouse down)
  16931. </button>
  16932. count: {{count}}
  16933. </file>
  16934. </example>
  16935. */
  16936. /**
  16937. * @ngdoc directive
  16938. * @name ngMouseup
  16939. *
  16940. * @description
  16941. * Specify custom behavior on mouseup event.
  16942. *
  16943. * @element ANY
  16944. * @priority 0
  16945. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  16946. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  16947. *
  16948. * @example
  16949. <example>
  16950. <file name="index.html">
  16951. <button ng-mouseup="count = count + 1" ng-init="count=0">
  16952. Increment (on mouse up)
  16953. </button>
  16954. count: {{count}}
  16955. </file>
  16956. </example>
  16957. */
  16958. /**
  16959. * @ngdoc directive
  16960. * @name ngMouseover
  16961. *
  16962. * @description
  16963. * Specify custom behavior on mouseover event.
  16964. *
  16965. * @element ANY
  16966. * @priority 0
  16967. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  16968. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  16969. *
  16970. * @example
  16971. <example>
  16972. <file name="index.html">
  16973. <button ng-mouseover="count = count + 1" ng-init="count=0">
  16974. Increment (when mouse is over)
  16975. </button>
  16976. count: {{count}}
  16977. </file>
  16978. </example>
  16979. */
  16980. /**
  16981. * @ngdoc directive
  16982. * @name ngMouseenter
  16983. *
  16984. * @description
  16985. * Specify custom behavior on mouseenter event.
  16986. *
  16987. * @element ANY
  16988. * @priority 0
  16989. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  16990. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  16991. *
  16992. * @example
  16993. <example>
  16994. <file name="index.html">
  16995. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  16996. Increment (when mouse enters)
  16997. </button>
  16998. count: {{count}}
  16999. </file>
  17000. </example>
  17001. */
  17002. /**
  17003. * @ngdoc directive
  17004. * @name ngMouseleave
  17005. *
  17006. * @description
  17007. * Specify custom behavior on mouseleave event.
  17008. *
  17009. * @element ANY
  17010. * @priority 0
  17011. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17012. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17013. *
  17014. * @example
  17015. <example>
  17016. <file name="index.html">
  17017. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17018. Increment (when mouse leaves)
  17019. </button>
  17020. count: {{count}}
  17021. </file>
  17022. </example>
  17023. */
  17024. /**
  17025. * @ngdoc directive
  17026. * @name ngMousemove
  17027. *
  17028. * @description
  17029. * Specify custom behavior on mousemove event.
  17030. *
  17031. * @element ANY
  17032. * @priority 0
  17033. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17034. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17035. *
  17036. * @example
  17037. <example>
  17038. <file name="index.html">
  17039. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17040. Increment (when mouse moves)
  17041. </button>
  17042. count: {{count}}
  17043. </file>
  17044. </example>
  17045. */
  17046. /**
  17047. * @ngdoc directive
  17048. * @name ngKeydown
  17049. *
  17050. * @description
  17051. * Specify custom behavior on keydown event.
  17052. *
  17053. * @element ANY
  17054. * @priority 0
  17055. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17056. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17057. *
  17058. * @example
  17059. <example>
  17060. <file name="index.html">
  17061. <input ng-keydown="count = count + 1" ng-init="count=0">
  17062. key down count: {{count}}
  17063. </file>
  17064. </example>
  17065. */
  17066. /**
  17067. * @ngdoc directive
  17068. * @name ngKeyup
  17069. *
  17070. * @description
  17071. * Specify custom behavior on keyup event.
  17072. *
  17073. * @element ANY
  17074. * @priority 0
  17075. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17076. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17077. *
  17078. * @example
  17079. <example>
  17080. <file name="index.html">
  17081. <input ng-keyup="count = count + 1" ng-init="count=0">
  17082. key up count: {{count}}
  17083. </file>
  17084. </example>
  17085. */
  17086. /**
  17087. * @ngdoc directive
  17088. * @name ngKeypress
  17089. *
  17090. * @description
  17091. * Specify custom behavior on keypress event.
  17092. *
  17093. * @element ANY
  17094. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17095. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17096. * and can be interrogated for keyCode, altKey, etc.)
  17097. *
  17098. * @example
  17099. <example>
  17100. <file name="index.html">
  17101. <input ng-keypress="count = count + 1" ng-init="count=0">
  17102. key press count: {{count}}
  17103. </file>
  17104. </example>
  17105. */
  17106. /**
  17107. * @ngdoc directive
  17108. * @name ngSubmit
  17109. *
  17110. * @description
  17111. * Enables binding angular expressions to onsubmit events.
  17112. *
  17113. * Additionally it prevents the default action (which for form means sending the request to the
  17114. * server and reloading the current page), but only if the form does not contain `action`,
  17115. * `data-action`, or `x-action` attributes.
  17116. *
  17117. * @element form
  17118. * @priority 0
  17119. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17120. * ({@link guide/expression#-event- Event object is available as `$event`})
  17121. *
  17122. * @example
  17123. <example>
  17124. <file name="index.html">
  17125. <script>
  17126. function Ctrl($scope) {
  17127. $scope.list = [];
  17128. $scope.text = 'hello';
  17129. $scope.submit = function() {
  17130. if ($scope.text) {
  17131. $scope.list.push(this.text);
  17132. $scope.text = '';
  17133. }
  17134. };
  17135. }
  17136. </script>
  17137. <form ng-submit="submit()" ng-controller="Ctrl">
  17138. Enter text and hit enter:
  17139. <input type="text" ng-model="text" name="text" />
  17140. <input type="submit" id="submit" value="Submit" />
  17141. <pre>list={{list}}</pre>
  17142. </form>
  17143. </file>
  17144. <file name="protractor.js" type="protractor">
  17145. it('should check ng-submit', function() {
  17146. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17147. element(by.css('#submit')).click();
  17148. expect(element(by.binding('list')).getText()).toContain('hello');
  17149. expect(element(by.input('text')).getAttribute('value')).toBe('');
  17150. });
  17151. it('should ignore empty strings', function() {
  17152. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17153. element(by.css('#submit')).click();
  17154. element(by.css('#submit')).click();
  17155. expect(element(by.binding('list')).getText()).toContain('hello');
  17156. });
  17157. </file>
  17158. </example>
  17159. */
  17160. /**
  17161. * @ngdoc directive
  17162. * @name ngFocus
  17163. *
  17164. * @description
  17165. * Specify custom behavior on focus event.
  17166. *
  17167. * @element window, input, select, textarea, a
  17168. * @priority 0
  17169. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17170. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17171. *
  17172. * @example
  17173. * See {@link ng.directive:ngClick ngClick}
  17174. */
  17175. /**
  17176. * @ngdoc directive
  17177. * @name ngBlur
  17178. *
  17179. * @description
  17180. * Specify custom behavior on blur event.
  17181. *
  17182. * @element window, input, select, textarea, a
  17183. * @priority 0
  17184. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17185. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17186. *
  17187. * @example
  17188. * See {@link ng.directive:ngClick ngClick}
  17189. */
  17190. /**
  17191. * @ngdoc directive
  17192. * @name ngCopy
  17193. *
  17194. * @description
  17195. * Specify custom behavior on copy event.
  17196. *
  17197. * @element window, input, select, textarea, a
  17198. * @priority 0
  17199. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17200. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17201. *
  17202. * @example
  17203. <example>
  17204. <file name="index.html">
  17205. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17206. copied: {{copied}}
  17207. </file>
  17208. </example>
  17209. */
  17210. /**
  17211. * @ngdoc directive
  17212. * @name ngCut
  17213. *
  17214. * @description
  17215. * Specify custom behavior on cut event.
  17216. *
  17217. * @element window, input, select, textarea, a
  17218. * @priority 0
  17219. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17220. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17221. *
  17222. * @example
  17223. <example>
  17224. <file name="index.html">
  17225. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17226. cut: {{cut}}
  17227. </file>
  17228. </example>
  17229. */
  17230. /**
  17231. * @ngdoc directive
  17232. * @name ngPaste
  17233. *
  17234. * @description
  17235. * Specify custom behavior on paste event.
  17236. *
  17237. * @element window, input, select, textarea, a
  17238. * @priority 0
  17239. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17240. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17241. *
  17242. * @example
  17243. <example>
  17244. <file name="index.html">
  17245. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17246. pasted: {{paste}}
  17247. </file>
  17248. </example>
  17249. */
  17250. /**
  17251. * @ngdoc directive
  17252. * @name ngIf
  17253. * @restrict A
  17254. *
  17255. * @description
  17256. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17257. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17258. * value then the element is removed from the DOM, otherwise a clone of the
  17259. * element is reinserted into the DOM.
  17260. *
  17261. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17262. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17263. * case when this difference is significant is when using css selectors that rely on an element's
  17264. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17265. *
  17266. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17267. * is created when the element is restored. The scope created within `ngIf` inherits from
  17268. * its parent scope using
  17269. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance).
  17270. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17271. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17272. * variable within the child scope will override (hide) the value in the parent scope.
  17273. *
  17274. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17275. * is if an element's class attribute is directly modified after it's compiled, using something like
  17276. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17277. * the added class will be lost because the original compiled state is used to regenerate the element.
  17278. *
  17279. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17280. * and `leave` effects.
  17281. *
  17282. * @animations
  17283. * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
  17284. * leave - happens just before the ngIf contents are removed from the DOM
  17285. *
  17286. * @element ANY
  17287. * @scope
  17288. * @priority 600
  17289. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17290. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17291. * element is added to the DOM tree.
  17292. *
  17293. * @example
  17294. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17295. <file name="index.html">
  17296. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17297. Show when checked:
  17298. <span ng-if="checked" class="animate-if">
  17299. I'm removed when the checkbox is unchecked.
  17300. </span>
  17301. </file>
  17302. <file name="animations.css">
  17303. .animate-if {
  17304. background:white;
  17305. border:1px solid black;
  17306. padding:10px;
  17307. }
  17308. .animate-if.ng-enter, .animate-if.ng-leave {
  17309. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17310. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17311. }
  17312. .animate-if.ng-enter,
  17313. .animate-if.ng-leave.ng-leave-active {
  17314. opacity:0;
  17315. }
  17316. .animate-if.ng-leave,
  17317. .animate-if.ng-enter.ng-enter-active {
  17318. opacity:1;
  17319. }
  17320. </file>
  17321. </example>
  17322. */
  17323. var ngIfDirective = ['$animate', function($animate) {
  17324. return {
  17325. transclude: 'element',
  17326. priority: 600,
  17327. terminal: true,
  17328. restrict: 'A',
  17329. $$tlb: true,
  17330. link: function ($scope, $element, $attr, ctrl, $transclude) {
  17331. var block, childScope, previousElements;
  17332. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  17333. if (toBoolean(value)) {
  17334. if (!childScope) {
  17335. childScope = $scope.$new();
  17336. $transclude(childScope, function (clone) {
  17337. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  17338. // Note: We only need the first/last node of the cloned nodes.
  17339. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17340. // by a directive with templateUrl when it's template arrives.
  17341. block = {
  17342. clone: clone
  17343. };
  17344. $animate.enter(clone, $element.parent(), $element);
  17345. });
  17346. }
  17347. } else {
  17348. if(previousElements) {
  17349. previousElements.remove();
  17350. previousElements = null;
  17351. }
  17352. if(childScope) {
  17353. childScope.$destroy();
  17354. childScope = null;
  17355. }
  17356. if(block) {
  17357. previousElements = getBlockElements(block.clone);
  17358. $animate.leave(previousElements, function() {
  17359. previousElements = null;
  17360. });
  17361. block = null;
  17362. }
  17363. }
  17364. });
  17365. }
  17366. };
  17367. }];
  17368. /**
  17369. * @ngdoc directive
  17370. * @name ngInclude
  17371. * @restrict ECA
  17372. *
  17373. * @description
  17374. * Fetches, compiles and includes an external HTML fragment.
  17375. *
  17376. * By default, the template URL is restricted to the same domain and protocol as the
  17377. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17378. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  17379. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  17380. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  17381. * ng.$sce Strict Contextual Escaping}.
  17382. *
  17383. * In addition, the browser's
  17384. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17385. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17386. * policy may further restrict whether the template is successfully loaded.
  17387. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  17388. * access on some browsers.
  17389. *
  17390. * @animations
  17391. * enter - animation is used to bring new content into the browser.
  17392. * leave - animation is used to animate existing content away.
  17393. *
  17394. * The enter and leave animation occur concurrently.
  17395. *
  17396. * @scope
  17397. * @priority 400
  17398. *
  17399. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  17400. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  17401. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  17402. *
  17403. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  17404. * $anchorScroll} to scroll the viewport after the content is loaded.
  17405. *
  17406. * - If the attribute is not set, disable scrolling.
  17407. * - If the attribute is set without value, enable scrolling.
  17408. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  17409. *
  17410. * @example
  17411. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17412. <file name="index.html">
  17413. <div ng-controller="Ctrl">
  17414. <select ng-model="template" ng-options="t.name for t in templates">
  17415. <option value="">(blank)</option>
  17416. </select>
  17417. url of the template: <tt>{{template.url}}</tt>
  17418. <hr/>
  17419. <div class="slide-animate-container">
  17420. <div class="slide-animate" ng-include="template.url"></div>
  17421. </div>
  17422. </div>
  17423. </file>
  17424. <file name="script.js">
  17425. function Ctrl($scope) {
  17426. $scope.templates =
  17427. [ { name: 'template1.html', url: 'template1.html'},
  17428. { name: 'template2.html', url: 'template2.html'} ];
  17429. $scope.template = $scope.templates[0];
  17430. }
  17431. </file>
  17432. <file name="template1.html">
  17433. Content of template1.html
  17434. </file>
  17435. <file name="template2.html">
  17436. Content of template2.html
  17437. </file>
  17438. <file name="animations.css">
  17439. .slide-animate-container {
  17440. position:relative;
  17441. background:white;
  17442. border:1px solid black;
  17443. height:40px;
  17444. overflow:hidden;
  17445. }
  17446. .slide-animate {
  17447. padding:10px;
  17448. }
  17449. .slide-animate.ng-enter, .slide-animate.ng-leave {
  17450. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17451. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17452. position:absolute;
  17453. top:0;
  17454. left:0;
  17455. right:0;
  17456. bottom:0;
  17457. display:block;
  17458. padding:10px;
  17459. }
  17460. .slide-animate.ng-enter {
  17461. top:-50px;
  17462. }
  17463. .slide-animate.ng-enter.ng-enter-active {
  17464. top:0;
  17465. }
  17466. .slide-animate.ng-leave {
  17467. top:0;
  17468. }
  17469. .slide-animate.ng-leave.ng-leave-active {
  17470. top:50px;
  17471. }
  17472. </file>
  17473. <file name="protractor.js" type="protractor">
  17474. var templateSelect = element(by.model('template'));
  17475. var includeElem = element(by.css('[ng-include]'));
  17476. it('should load template1.html', function() {
  17477. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  17478. });
  17479. it('should load template2.html', function() {
  17480. if (browser.params.browser == 'firefox') {
  17481. // Firefox can't handle using selects
  17482. // See https://github.com/angular/protractor/issues/480
  17483. return;
  17484. }
  17485. templateSelect.click();
  17486. templateSelect.element.all(by.css('option')).get(2).click();
  17487. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  17488. });
  17489. it('should change to blank', function() {
  17490. if (browser.params.browser == 'firefox') {
  17491. // Firefox can't handle using selects
  17492. return;
  17493. }
  17494. templateSelect.click();
  17495. templateSelect.element.all(by.css('option')).get(0).click();
  17496. expect(includeElem.isPresent()).toBe(false);
  17497. });
  17498. </file>
  17499. </example>
  17500. */
  17501. /**
  17502. * @ngdoc event
  17503. * @name ngInclude#$includeContentRequested
  17504. * @eventType emit on the scope ngInclude was declared in
  17505. * @description
  17506. * Emitted every time the ngInclude content is requested.
  17507. */
  17508. /**
  17509. * @ngdoc event
  17510. * @name ngInclude#$includeContentLoaded
  17511. * @eventType emit on the current ngInclude scope
  17512. * @description
  17513. * Emitted every time the ngInclude content is reloaded.
  17514. */
  17515. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  17516. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  17517. return {
  17518. restrict: 'ECA',
  17519. priority: 400,
  17520. terminal: true,
  17521. transclude: 'element',
  17522. controller: angular.noop,
  17523. compile: function(element, attr) {
  17524. var srcExp = attr.ngInclude || attr.src,
  17525. onloadExp = attr.onload || '',
  17526. autoScrollExp = attr.autoscroll;
  17527. return function(scope, $element, $attr, ctrl, $transclude) {
  17528. var changeCounter = 0,
  17529. currentScope,
  17530. previousElement,
  17531. currentElement;
  17532. var cleanupLastIncludeContent = function() {
  17533. if(previousElement) {
  17534. previousElement.remove();
  17535. previousElement = null;
  17536. }
  17537. if(currentScope) {
  17538. currentScope.$destroy();
  17539. currentScope = null;
  17540. }
  17541. if(currentElement) {
  17542. $animate.leave(currentElement, function() {
  17543. previousElement = null;
  17544. });
  17545. previousElement = currentElement;
  17546. currentElement = null;
  17547. }
  17548. };
  17549. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  17550. var afterAnimation = function() {
  17551. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  17552. $anchorScroll();
  17553. }
  17554. };
  17555. var thisChangeId = ++changeCounter;
  17556. if (src) {
  17557. $http.get(src, {cache: $templateCache}).success(function(response) {
  17558. if (thisChangeId !== changeCounter) return;
  17559. var newScope = scope.$new();
  17560. ctrl.template = response;
  17561. // Note: This will also link all children of ng-include that were contained in the original
  17562. // html. If that content contains controllers, ... they could pollute/change the scope.
  17563. // However, using ng-include on an element with additional content does not make sense...
  17564. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  17565. // function is called before linking the content, which would apply child
  17566. // directives to non existing elements.
  17567. var clone = $transclude(newScope, function(clone) {
  17568. cleanupLastIncludeContent();
  17569. $animate.enter(clone, null, $element, afterAnimation);
  17570. });
  17571. currentScope = newScope;
  17572. currentElement = clone;
  17573. currentScope.$emit('$includeContentLoaded');
  17574. scope.$eval(onloadExp);
  17575. }).error(function() {
  17576. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  17577. });
  17578. scope.$emit('$includeContentRequested');
  17579. } else {
  17580. cleanupLastIncludeContent();
  17581. ctrl.template = null;
  17582. }
  17583. });
  17584. };
  17585. }
  17586. };
  17587. }];
  17588. // This directive is called during the $transclude call of the first `ngInclude` directive.
  17589. // It will replace and compile the content of the element with the loaded template.
  17590. // We need this directive so that the element content is already filled when
  17591. // the link function of another directive on the same element as ngInclude
  17592. // is called.
  17593. var ngIncludeFillContentDirective = ['$compile',
  17594. function($compile) {
  17595. return {
  17596. restrict: 'ECA',
  17597. priority: -400,
  17598. require: 'ngInclude',
  17599. link: function(scope, $element, $attr, ctrl) {
  17600. $element.html(ctrl.template);
  17601. $compile($element.contents())(scope);
  17602. }
  17603. };
  17604. }];
  17605. /**
  17606. * @ngdoc directive
  17607. * @name ngInit
  17608. * @restrict AC
  17609. *
  17610. * @description
  17611. * The `ngInit` directive allows you to evaluate an expression in the
  17612. * current scope.
  17613. *
  17614. * <div class="alert alert-error">
  17615. * The only appropriate use of `ngInit` is for aliasing special properties of
  17616. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  17617. * should use {@link guide/controller controllers} rather than `ngInit`
  17618. * to initialize values on a scope.
  17619. * </div>
  17620. * <div class="alert alert-warning">
  17621. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  17622. * sure you have parenthesis for correct precedence:
  17623. * <pre class="prettyprint">
  17624. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  17625. * </pre>
  17626. * </div>
  17627. *
  17628. * @priority 450
  17629. *
  17630. * @element ANY
  17631. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  17632. *
  17633. * @example
  17634. <example>
  17635. <file name="index.html">
  17636. <script>
  17637. function Ctrl($scope) {
  17638. $scope.list = [['a', 'b'], ['c', 'd']];
  17639. }
  17640. </script>
  17641. <div ng-controller="Ctrl">
  17642. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  17643. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  17644. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  17645. </div>
  17646. </div>
  17647. </div>
  17648. </file>
  17649. <file name="protractor.js" type="protractor">
  17650. it('should alias index positions', function() {
  17651. var elements = element.all(by.css('.example-init'));
  17652. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  17653. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  17654. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  17655. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  17656. });
  17657. </file>
  17658. </example>
  17659. */
  17660. var ngInitDirective = ngDirective({
  17661. priority: 450,
  17662. compile: function() {
  17663. return {
  17664. pre: function(scope, element, attrs) {
  17665. scope.$eval(attrs.ngInit);
  17666. }
  17667. };
  17668. }
  17669. });
  17670. /**
  17671. * @ngdoc directive
  17672. * @name ngNonBindable
  17673. * @restrict AC
  17674. * @priority 1000
  17675. *
  17676. * @description
  17677. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  17678. * DOM element. This is useful if the element contains what appears to be Angular directives and
  17679. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  17680. * displays snippets of code, for instance.
  17681. *
  17682. * @element ANY
  17683. *
  17684. * @example
  17685. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  17686. * but the one wrapped in `ngNonBindable` is left alone.
  17687. *
  17688. * @example
  17689. <example>
  17690. <file name="index.html">
  17691. <div>Normal: {{1 + 2}}</div>
  17692. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  17693. </file>
  17694. <file name="protractor.js" type="protractor">
  17695. it('should check ng-non-bindable', function() {
  17696. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  17697. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  17698. });
  17699. </file>
  17700. </example>
  17701. */
  17702. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  17703. /**
  17704. * @ngdoc directive
  17705. * @name ngPluralize
  17706. * @restrict EA
  17707. *
  17708. * @description
  17709. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  17710. * These rules are bundled with angular.js, but can be overridden
  17711. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  17712. * by specifying the mappings between
  17713. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  17714. * and the strings to be displayed.
  17715. *
  17716. * # Plural categories and explicit number rules
  17717. * There are two
  17718. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  17719. * in Angular's default en-US locale: "one" and "other".
  17720. *
  17721. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  17722. * any number that is not 1), an explicit number rule can only match one number. For example, the
  17723. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  17724. * and explicit number rules throughout the rest of this documentation.
  17725. *
  17726. * # Configuring ngPluralize
  17727. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  17728. * You can also provide an optional attribute, `offset`.
  17729. *
  17730. * The value of the `count` attribute can be either a string or an {@link guide/expression
  17731. * Angular expression}; these are evaluated on the current scope for its bound value.
  17732. *
  17733. * The `when` attribute specifies the mappings between plural categories and the actual
  17734. * string to be displayed. The value of the attribute should be a JSON object.
  17735. *
  17736. * The following example shows how to configure ngPluralize:
  17737. *
  17738. * ```html
  17739. * <ng-pluralize count="personCount"
  17740. when="{'0': 'Nobody is viewing.',
  17741. * 'one': '1 person is viewing.',
  17742. * 'other': '{} people are viewing.'}">
  17743. * </ng-pluralize>
  17744. *```
  17745. *
  17746. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  17747. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  17748. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  17749. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  17750. * show "a dozen people are viewing".
  17751. *
  17752. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  17753. * into pluralized strings. In the previous example, Angular will replace `{}` with
  17754. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  17755. * for <span ng-non-bindable>{{numberExpression}}</span>.
  17756. *
  17757. * # Configuring ngPluralize with offset
  17758. * The `offset` attribute allows further customization of pluralized text, which can result in
  17759. * a better user experience. For example, instead of the message "4 people are viewing this document",
  17760. * you might display "John, Kate and 2 others are viewing this document".
  17761. * The offset attribute allows you to offset a number by any desired value.
  17762. * Let's take a look at an example:
  17763. *
  17764. * ```html
  17765. * <ng-pluralize count="personCount" offset=2
  17766. * when="{'0': 'Nobody is viewing.',
  17767. * '1': '{{person1}} is viewing.',
  17768. * '2': '{{person1}} and {{person2}} are viewing.',
  17769. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  17770. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  17771. * </ng-pluralize>
  17772. * ```
  17773. *
  17774. * Notice that we are still using two plural categories(one, other), but we added
  17775. * three explicit number rules 0, 1 and 2.
  17776. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  17777. * When three people view the document, no explicit number rule is found, so
  17778. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  17779. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
  17780. * is shown.
  17781. *
  17782. * Note that when you specify offsets, you must provide explicit number rules for
  17783. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  17784. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  17785. * plural categories "one" and "other".
  17786. *
  17787. * @param {string|expression} count The variable to be bound to.
  17788. * @param {string} when The mapping between plural category to its corresponding strings.
  17789. * @param {number=} offset Offset to deduct from the total number.
  17790. *
  17791. * @example
  17792. <example>
  17793. <file name="index.html">
  17794. <script>
  17795. function Ctrl($scope) {
  17796. $scope.person1 = 'Igor';
  17797. $scope.person2 = 'Misko';
  17798. $scope.personCount = 1;
  17799. }
  17800. </script>
  17801. <div ng-controller="Ctrl">
  17802. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  17803. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  17804. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  17805. <!--- Example with simple pluralization rules for en locale --->
  17806. Without Offset:
  17807. <ng-pluralize count="personCount"
  17808. when="{'0': 'Nobody is viewing.',
  17809. 'one': '1 person is viewing.',
  17810. 'other': '{} people are viewing.'}">
  17811. </ng-pluralize><br>
  17812. <!--- Example with offset --->
  17813. With Offset(2):
  17814. <ng-pluralize count="personCount" offset=2
  17815. when="{'0': 'Nobody is viewing.',
  17816. '1': '{{person1}} is viewing.',
  17817. '2': '{{person1}} and {{person2}} are viewing.',
  17818. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  17819. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  17820. </ng-pluralize>
  17821. </div>
  17822. </file>
  17823. <file name="protractor.js" type="protractor">
  17824. it('should show correct pluralized string', function() {
  17825. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  17826. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  17827. var countInput = element(by.model('personCount'));
  17828. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  17829. expect(withOffset.getText()).toEqual('Igor is viewing.');
  17830. countInput.clear();
  17831. countInput.sendKeys('0');
  17832. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  17833. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  17834. countInput.clear();
  17835. countInput.sendKeys('2');
  17836. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  17837. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  17838. countInput.clear();
  17839. countInput.sendKeys('3');
  17840. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  17841. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  17842. countInput.clear();
  17843. countInput.sendKeys('4');
  17844. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  17845. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  17846. });
  17847. it('should show data-bound names', function() {
  17848. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  17849. var personCount = element(by.model('personCount'));
  17850. var person1 = element(by.model('person1'));
  17851. var person2 = element(by.model('person2'));
  17852. personCount.clear();
  17853. personCount.sendKeys('4');
  17854. person1.clear();
  17855. person1.sendKeys('Di');
  17856. person2.clear();
  17857. person2.sendKeys('Vojta');
  17858. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  17859. });
  17860. </file>
  17861. </example>
  17862. */
  17863. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  17864. var BRACE = /{}/g;
  17865. return {
  17866. restrict: 'EA',
  17867. link: function(scope, element, attr) {
  17868. var numberExp = attr.count,
  17869. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  17870. offset = attr.offset || 0,
  17871. whens = scope.$eval(whenExp) || {},
  17872. whensExpFns = {},
  17873. startSymbol = $interpolate.startSymbol(),
  17874. endSymbol = $interpolate.endSymbol(),
  17875. isWhen = /^when(Minus)?(.+)$/;
  17876. forEach(attr, function(expression, attributeName) {
  17877. if (isWhen.test(attributeName)) {
  17878. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  17879. element.attr(attr.$attr[attributeName]);
  17880. }
  17881. });
  17882. forEach(whens, function(expression, key) {
  17883. whensExpFns[key] =
  17884. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  17885. offset + endSymbol));
  17886. });
  17887. scope.$watch(function ngPluralizeWatch() {
  17888. var value = parseFloat(scope.$eval(numberExp));
  17889. if (!isNaN(value)) {
  17890. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  17891. //check it against pluralization rules in $locale service
  17892. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  17893. return whensExpFns[value](scope, element, true);
  17894. } else {
  17895. return '';
  17896. }
  17897. }, function ngPluralizeWatchAction(newVal) {
  17898. element.text(newVal);
  17899. });
  17900. }
  17901. };
  17902. }];
  17903. /**
  17904. * @ngdoc directive
  17905. * @name ngRepeat
  17906. *
  17907. * @description
  17908. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  17909. * instance gets its own scope, where the given loop variable is set to the current collection item,
  17910. * and `$index` is set to the item index or key.
  17911. *
  17912. * Special properties are exposed on the local scope of each template instance, including:
  17913. *
  17914. * | Variable | Type | Details |
  17915. * |-----------|-----------------|-----------------------------------------------------------------------------|
  17916. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  17917. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  17918. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  17919. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  17920. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  17921. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  17922. *
  17923. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  17924. * This may be useful when, for instance, nesting ngRepeats.
  17925. *
  17926. * # Special repeat start and end points
  17927. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  17928. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  17929. * 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)
  17930. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  17931. *
  17932. * The example below makes use of this feature:
  17933. * ```html
  17934. * <header ng-repeat-start="item in items">
  17935. * Header {{ item }}
  17936. * </header>
  17937. * <div class="body">
  17938. * Body {{ item }}
  17939. * </div>
  17940. * <footer ng-repeat-end>
  17941. * Footer {{ item }}
  17942. * </footer>
  17943. * ```
  17944. *
  17945. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  17946. * ```html
  17947. * <header>
  17948. * Header A
  17949. * </header>
  17950. * <div class="body">
  17951. * Body A
  17952. * </div>
  17953. * <footer>
  17954. * Footer A
  17955. * </footer>
  17956. * <header>
  17957. * Header B
  17958. * </header>
  17959. * <div class="body">
  17960. * Body B
  17961. * </div>
  17962. * <footer>
  17963. * Footer B
  17964. * </footer>
  17965. * ```
  17966. *
  17967. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  17968. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  17969. *
  17970. * @animations
  17971. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  17972. *
  17973. * **.leave** - when an item is removed from the list or when an item is filtered out
  17974. *
  17975. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  17976. *
  17977. * @element ANY
  17978. * @scope
  17979. * @priority 1000
  17980. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  17981. * formats are currently supported:
  17982. *
  17983. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  17984. * is a scope expression giving the collection to enumerate.
  17985. *
  17986. * For example: `album in artist.albums`.
  17987. *
  17988. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  17989. * and `expression` is the scope expression giving the collection to enumerate.
  17990. *
  17991. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  17992. *
  17993. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  17994. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  17995. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  17996. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  17997. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  17998. * before specifying a tracking expression.
  17999. *
  18000. * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
  18001. * will be associated by item identity in the array.
  18002. *
  18003. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18004. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18005. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18006. * element in the same way in the DOM.
  18007. *
  18008. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18009. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18010. * property is same.
  18011. *
  18012. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18013. * to items in conjunction with a tracking expression.
  18014. *
  18015. * @example
  18016. * This example initializes the scope to a list of names and
  18017. * then uses `ngRepeat` to display every person:
  18018. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18019. <file name="index.html">
  18020. <div ng-init="friends = [
  18021. {name:'John', age:25, gender:'boy'},
  18022. {name:'Jessie', age:30, gender:'girl'},
  18023. {name:'Johanna', age:28, gender:'girl'},
  18024. {name:'Joy', age:15, gender:'girl'},
  18025. {name:'Mary', age:28, gender:'girl'},
  18026. {name:'Peter', age:95, gender:'boy'},
  18027. {name:'Sebastian', age:50, gender:'boy'},
  18028. {name:'Erika', age:27, gender:'girl'},
  18029. {name:'Patrick', age:40, gender:'boy'},
  18030. {name:'Samantha', age:60, gender:'girl'}
  18031. ]">
  18032. I have {{friends.length}} friends. They are:
  18033. <input type="search" ng-model="q" placeholder="filter friends..." />
  18034. <ul class="example-animate-container">
  18035. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18036. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18037. </li>
  18038. </ul>
  18039. </div>
  18040. </file>
  18041. <file name="animations.css">
  18042. .example-animate-container {
  18043. background:white;
  18044. border:1px solid black;
  18045. list-style:none;
  18046. margin:0;
  18047. padding:0 10px;
  18048. }
  18049. .animate-repeat {
  18050. line-height:40px;
  18051. list-style:none;
  18052. box-sizing:border-box;
  18053. }
  18054. .animate-repeat.ng-move,
  18055. .animate-repeat.ng-enter,
  18056. .animate-repeat.ng-leave {
  18057. -webkit-transition:all linear 0.5s;
  18058. transition:all linear 0.5s;
  18059. }
  18060. .animate-repeat.ng-leave.ng-leave-active,
  18061. .animate-repeat.ng-move,
  18062. .animate-repeat.ng-enter {
  18063. opacity:0;
  18064. max-height:0;
  18065. }
  18066. .animate-repeat.ng-leave,
  18067. .animate-repeat.ng-move.ng-move-active,
  18068. .animate-repeat.ng-enter.ng-enter-active {
  18069. opacity:1;
  18070. max-height:40px;
  18071. }
  18072. </file>
  18073. <file name="protractor.js" type="protractor">
  18074. var friends = element.all(by.repeater('friend in friends'));
  18075. it('should render initial data set', function() {
  18076. expect(friends.count()).toBe(10);
  18077. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18078. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18079. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18080. expect(element(by.binding('friends.length')).getText())
  18081. .toMatch("I have 10 friends. They are:");
  18082. });
  18083. it('should update repeater when filter predicate changes', function() {
  18084. expect(friends.count()).toBe(10);
  18085. element(by.model('q')).sendKeys('ma');
  18086. expect(friends.count()).toBe(2);
  18087. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18088. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18089. });
  18090. </file>
  18091. </example>
  18092. */
  18093. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18094. var NG_REMOVED = '$$NG_REMOVED';
  18095. var ngRepeatMinErr = minErr('ngRepeat');
  18096. return {
  18097. transclude: 'element',
  18098. priority: 1000,
  18099. terminal: true,
  18100. $$tlb: true,
  18101. link: function($scope, $element, $attr, ctrl, $transclude){
  18102. var expression = $attr.ngRepeat;
  18103. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18104. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18105. lhs, rhs, valueIdentifier, keyIdentifier,
  18106. hashFnLocals = {$id: hashKey};
  18107. if (!match) {
  18108. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18109. expression);
  18110. }
  18111. lhs = match[1];
  18112. rhs = match[2];
  18113. trackByExp = match[3];
  18114. if (trackByExp) {
  18115. trackByExpGetter = $parse(trackByExp);
  18116. trackByIdExpFn = function(key, value, index) {
  18117. // assign key, value, and $index to the locals so that they can be used in hash functions
  18118. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18119. hashFnLocals[valueIdentifier] = value;
  18120. hashFnLocals.$index = index;
  18121. return trackByExpGetter($scope, hashFnLocals);
  18122. };
  18123. } else {
  18124. trackByIdArrayFn = function(key, value) {
  18125. return hashKey(value);
  18126. };
  18127. trackByIdObjFn = function(key) {
  18128. return key;
  18129. };
  18130. }
  18131. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18132. if (!match) {
  18133. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18134. lhs);
  18135. }
  18136. valueIdentifier = match[3] || match[1];
  18137. keyIdentifier = match[2];
  18138. // Store a list of elements from previous run. This is a hash where key is the item from the
  18139. // iterator, and the value is objects with following properties.
  18140. // - scope: bound scope
  18141. // - element: previous element.
  18142. // - index: position
  18143. var lastBlockMap = {};
  18144. //watch props
  18145. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18146. var index, length,
  18147. previousNode = $element[0], // current position of the node
  18148. nextNode,
  18149. // Same as lastBlockMap but it has the current state. It will become the
  18150. // lastBlockMap on the next iteration.
  18151. nextBlockMap = {},
  18152. arrayLength,
  18153. childScope,
  18154. key, value, // key/value of iteration
  18155. trackById,
  18156. trackByIdFn,
  18157. collectionKeys,
  18158. block, // last object information {scope, element, id}
  18159. nextBlockOrder = [],
  18160. elementsToRemove;
  18161. if (isArrayLike(collection)) {
  18162. collectionKeys = collection;
  18163. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18164. } else {
  18165. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18166. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18167. collectionKeys = [];
  18168. for (key in collection) {
  18169. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18170. collectionKeys.push(key);
  18171. }
  18172. }
  18173. collectionKeys.sort();
  18174. }
  18175. arrayLength = collectionKeys.length;
  18176. // locate existing items
  18177. length = nextBlockOrder.length = collectionKeys.length;
  18178. for(index = 0; index < length; index++) {
  18179. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18180. value = collection[key];
  18181. trackById = trackByIdFn(key, value, index);
  18182. assertNotHasOwnProperty(trackById, '`track by` id');
  18183. if(lastBlockMap.hasOwnProperty(trackById)) {
  18184. block = lastBlockMap[trackById];
  18185. delete lastBlockMap[trackById];
  18186. nextBlockMap[trackById] = block;
  18187. nextBlockOrder[index] = block;
  18188. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18189. // restore lastBlockMap
  18190. forEach(nextBlockOrder, function(block) {
  18191. if (block && block.scope) lastBlockMap[block.id] = block;
  18192. });
  18193. // This is a duplicate and we need to throw an error
  18194. throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
  18195. expression, trackById);
  18196. } else {
  18197. // new never before seen block
  18198. nextBlockOrder[index] = { id: trackById };
  18199. nextBlockMap[trackById] = false;
  18200. }
  18201. }
  18202. // remove existing items
  18203. for (key in lastBlockMap) {
  18204. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18205. if (lastBlockMap.hasOwnProperty(key)) {
  18206. block = lastBlockMap[key];
  18207. elementsToRemove = getBlockElements(block.clone);
  18208. $animate.leave(elementsToRemove);
  18209. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18210. block.scope.$destroy();
  18211. }
  18212. }
  18213. // we are not using forEach for perf reasons (trying to avoid #call)
  18214. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18215. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18216. value = collection[key];
  18217. block = nextBlockOrder[index];
  18218. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18219. if (block.scope) {
  18220. // if we have already seen this object, then we need to reuse the
  18221. // associated scope/element
  18222. childScope = block.scope;
  18223. nextNode = previousNode;
  18224. do {
  18225. nextNode = nextNode.nextSibling;
  18226. } while(nextNode && nextNode[NG_REMOVED]);
  18227. if (getBlockStart(block) != nextNode) {
  18228. // existing item which got moved
  18229. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18230. }
  18231. previousNode = getBlockEnd(block);
  18232. } else {
  18233. // new item which we don't know about
  18234. childScope = $scope.$new();
  18235. }
  18236. childScope[valueIdentifier] = value;
  18237. if (keyIdentifier) childScope[keyIdentifier] = key;
  18238. childScope.$index = index;
  18239. childScope.$first = (index === 0);
  18240. childScope.$last = (index === (arrayLength - 1));
  18241. childScope.$middle = !(childScope.$first || childScope.$last);
  18242. // jshint bitwise: false
  18243. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18244. // jshint bitwise: true
  18245. if (!block.scope) {
  18246. $transclude(childScope, function(clone) {
  18247. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18248. $animate.enter(clone, null, jqLite(previousNode));
  18249. previousNode = clone;
  18250. block.scope = childScope;
  18251. // Note: We only need the first/last node of the cloned nodes.
  18252. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18253. // by a directive with templateUrl when it's template arrives.
  18254. block.clone = clone;
  18255. nextBlockMap[block.id] = block;
  18256. });
  18257. }
  18258. }
  18259. lastBlockMap = nextBlockMap;
  18260. });
  18261. }
  18262. };
  18263. function getBlockStart(block) {
  18264. return block.clone[0];
  18265. }
  18266. function getBlockEnd(block) {
  18267. return block.clone[block.clone.length - 1];
  18268. }
  18269. }];
  18270. /**
  18271. * @ngdoc directive
  18272. * @name ngShow
  18273. *
  18274. * @description
  18275. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18276. * provided to the ngShow attribute. The element is shown or hidden by removing or adding
  18277. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18278. * in AngularJS and sets the display style to none (using an !important flag).
  18279. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18280. *
  18281. * ```html
  18282. * <!-- when $scope.myValue is truthy (element is visible) -->
  18283. * <div ng-show="myValue"></div>
  18284. *
  18285. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18286. * <div ng-show="myValue" class="ng-hide"></div>
  18287. * ```
  18288. *
  18289. * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
  18290. * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
  18291. * from the element causing the element not to appear hidden.
  18292. *
  18293. * ## Why is !important used?
  18294. *
  18295. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18296. * can be easily overridden by heavier selectors. For example, something as simple
  18297. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18298. * This also becomes a bigger issue when dealing with CSS frameworks.
  18299. *
  18300. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18301. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18302. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18303. *
  18304. * ### Overriding .ng-hide
  18305. *
  18306. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  18307. * restating the styles for the .ng-hide class in CSS:
  18308. * ```css
  18309. * .ng-hide {
  18310. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  18311. * display:block!important;
  18312. *
  18313. * //this is just another form of hiding an element
  18314. * position:absolute;
  18315. * top:-9999px;
  18316. * left:-9999px;
  18317. * }
  18318. * ```
  18319. *
  18320. * Just remember to include the important flag so the CSS override will function.
  18321. *
  18322. * <div class="alert alert-warning">
  18323. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18324. * "f" / "0" / "false" / "no" / "n" / "[]"
  18325. * </div>
  18326. *
  18327. * ## A note about animations with ngShow
  18328. *
  18329. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18330. * is true and false. This system works like the animation system present with ngClass except that
  18331. * you must also include the !important flag to override the display property
  18332. * so that you can perform an animation when the element is hidden during the time of the animation.
  18333. *
  18334. * ```css
  18335. * //
  18336. * //a working example can be found at the bottom of this page
  18337. * //
  18338. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18339. * transition:0.5s linear all;
  18340. * display:block!important;
  18341. * }
  18342. *
  18343. * .my-element.ng-hide-add { ... }
  18344. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18345. * .my-element.ng-hide-remove { ... }
  18346. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18347. * ```
  18348. *
  18349. * @animations
  18350. * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
  18351. * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
  18352. *
  18353. * @element ANY
  18354. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  18355. * then the element is shown or hidden respectively.
  18356. *
  18357. * @example
  18358. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18359. <file name="index.html">
  18360. Click me: <input type="checkbox" ng-model="checked"><br/>
  18361. <div>
  18362. Show:
  18363. <div class="check-element animate-show" ng-show="checked">
  18364. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18365. </div>
  18366. </div>
  18367. <div>
  18368. Hide:
  18369. <div class="check-element animate-show" ng-hide="checked">
  18370. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18371. </div>
  18372. </div>
  18373. </file>
  18374. <file name="glyphicons.css">
  18375. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18376. </file>
  18377. <file name="animations.css">
  18378. .animate-show {
  18379. -webkit-transition:all linear 0.5s;
  18380. transition:all linear 0.5s;
  18381. line-height:20px;
  18382. opacity:1;
  18383. padding:10px;
  18384. border:1px solid black;
  18385. background:white;
  18386. }
  18387. .animate-show.ng-hide-add,
  18388. .animate-show.ng-hide-remove {
  18389. display:block!important;
  18390. }
  18391. .animate-show.ng-hide {
  18392. line-height:0;
  18393. opacity:0;
  18394. padding:0 10px;
  18395. }
  18396. .check-element {
  18397. padding:10px;
  18398. border:1px solid black;
  18399. background:white;
  18400. }
  18401. </file>
  18402. <file name="protractor.js" type="protractor">
  18403. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18404. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18405. it('should check ng-show / ng-hide', function() {
  18406. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18407. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18408. element(by.model('checked')).click();
  18409. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18410. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18411. });
  18412. </file>
  18413. </example>
  18414. */
  18415. var ngShowDirective = ['$animate', function($animate) {
  18416. return function(scope, element, attr) {
  18417. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  18418. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  18419. });
  18420. };
  18421. }];
  18422. /**
  18423. * @ngdoc directive
  18424. * @name ngHide
  18425. *
  18426. * @description
  18427. * The `ngHide` directive shows or hides the given HTML element based on the expression
  18428. * provided to the ngHide attribute. The element is shown or hidden by removing or adding
  18429. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18430. * in AngularJS and sets the display style to none (using an !important flag).
  18431. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18432. *
  18433. * ```html
  18434. * <!-- when $scope.myValue is truthy (element is hidden) -->
  18435. * <div ng-hide="myValue"></div>
  18436. *
  18437. * <!-- when $scope.myValue is falsy (element is visible) -->
  18438. * <div ng-hide="myValue" class="ng-hide"></div>
  18439. * ```
  18440. *
  18441. * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
  18442. * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
  18443. * from the element causing the element not to appear hidden.
  18444. *
  18445. * ## Why is !important used?
  18446. *
  18447. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18448. * can be easily overridden by heavier selectors. For example, something as simple
  18449. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18450. * This also becomes a bigger issue when dealing with CSS frameworks.
  18451. *
  18452. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18453. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18454. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18455. *
  18456. * ### Overriding .ng-hide
  18457. *
  18458. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  18459. * restating the styles for the .ng-hide class in CSS:
  18460. * ```css
  18461. * .ng-hide {
  18462. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  18463. * display:block!important;
  18464. *
  18465. * //this is just another form of hiding an element
  18466. * position:absolute;
  18467. * top:-9999px;
  18468. * left:-9999px;
  18469. * }
  18470. * ```
  18471. *
  18472. * Just remember to include the important flag so the CSS override will function.
  18473. *
  18474. * <div class="alert alert-warning">
  18475. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  18476. * "f" / "0" / "false" / "no" / "n" / "[]"
  18477. * </div>
  18478. *
  18479. * ## A note about animations with ngHide
  18480. *
  18481. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18482. * is true and false. This system works like the animation system present with ngClass, except that
  18483. * you must also include the !important flag to override the display property so
  18484. * that you can perform an animation when the element is hidden during the time of the animation.
  18485. *
  18486. * ```css
  18487. * //
  18488. * //a working example can be found at the bottom of this page
  18489. * //
  18490. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18491. * transition:0.5s linear all;
  18492. * display:block!important;
  18493. * }
  18494. *
  18495. * .my-element.ng-hide-add { ... }
  18496. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18497. * .my-element.ng-hide-remove { ... }
  18498. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18499. * ```
  18500. *
  18501. * @animations
  18502. * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
  18503. * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
  18504. *
  18505. * @element ANY
  18506. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  18507. * the element is shown or hidden respectively.
  18508. *
  18509. * @example
  18510. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18511. <file name="index.html">
  18512. Click me: <input type="checkbox" ng-model="checked"><br/>
  18513. <div>
  18514. Show:
  18515. <div class="check-element animate-hide" ng-show="checked">
  18516. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18517. </div>
  18518. </div>
  18519. <div>
  18520. Hide:
  18521. <div class="check-element animate-hide" ng-hide="checked">
  18522. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18523. </div>
  18524. </div>
  18525. </file>
  18526. <file name="glyphicons.css">
  18527. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18528. </file>
  18529. <file name="animations.css">
  18530. .animate-hide {
  18531. -webkit-transition:all linear 0.5s;
  18532. transition:all linear 0.5s;
  18533. line-height:20px;
  18534. opacity:1;
  18535. padding:10px;
  18536. border:1px solid black;
  18537. background:white;
  18538. }
  18539. .animate-hide.ng-hide-add,
  18540. .animate-hide.ng-hide-remove {
  18541. display:block!important;
  18542. }
  18543. .animate-hide.ng-hide {
  18544. line-height:0;
  18545. opacity:0;
  18546. padding:0 10px;
  18547. }
  18548. .check-element {
  18549. padding:10px;
  18550. border:1px solid black;
  18551. background:white;
  18552. }
  18553. </file>
  18554. <file name="protractor.js" type="protractor">
  18555. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18556. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18557. it('should check ng-show / ng-hide', function() {
  18558. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18559. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18560. element(by.model('checked')).click();
  18561. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18562. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18563. });
  18564. </file>
  18565. </example>
  18566. */
  18567. var ngHideDirective = ['$animate', function($animate) {
  18568. return function(scope, element, attr) {
  18569. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  18570. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  18571. });
  18572. };
  18573. }];
  18574. /**
  18575. * @ngdoc directive
  18576. * @name ngStyle
  18577. * @restrict AC
  18578. *
  18579. * @description
  18580. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  18581. *
  18582. * @element ANY
  18583. * @param {expression} ngStyle {@link guide/expression Expression} which evals to an
  18584. * object whose keys are CSS style names and values are corresponding values for those CSS
  18585. * keys.
  18586. *
  18587. * @example
  18588. <example>
  18589. <file name="index.html">
  18590. <input type="button" value="set" ng-click="myStyle={color:'red'}">
  18591. <input type="button" value="clear" ng-click="myStyle={}">
  18592. <br/>
  18593. <span ng-style="myStyle">Sample Text</span>
  18594. <pre>myStyle={{myStyle}}</pre>
  18595. </file>
  18596. <file name="style.css">
  18597. span {
  18598. color: black;
  18599. }
  18600. </file>
  18601. <file name="protractor.js" type="protractor">
  18602. var colorSpan = element(by.css('span'));
  18603. it('should check ng-style', function() {
  18604. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  18605. element(by.css('input[value=set]')).click();
  18606. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  18607. element(by.css('input[value=clear]')).click();
  18608. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  18609. });
  18610. </file>
  18611. </example>
  18612. */
  18613. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  18614. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  18615. if (oldStyles && (newStyles !== oldStyles)) {
  18616. forEach(oldStyles, function(val, style) { element.css(style, '');});
  18617. }
  18618. if (newStyles) element.css(newStyles);
  18619. }, true);
  18620. });
  18621. /**
  18622. * @ngdoc directive
  18623. * @name ngSwitch
  18624. * @restrict EA
  18625. *
  18626. * @description
  18627. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  18628. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  18629. * as specified in the template.
  18630. *
  18631. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  18632. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  18633. * matches the value obtained from the evaluated expression. In other words, you define a container element
  18634. * (where you place the directive), place an expression on the **`on="..."` attribute**
  18635. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  18636. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  18637. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  18638. * attribute is displayed.
  18639. *
  18640. * <div class="alert alert-info">
  18641. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  18642. * as literal string values to match against.
  18643. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  18644. * value of the expression `$scope.someVal`.
  18645. * </div>
  18646. * @animations
  18647. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  18648. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  18649. *
  18650. * @usage
  18651. * <ANY ng-switch="expression">
  18652. * <ANY ng-switch-when="matchValue1">...</ANY>
  18653. * <ANY ng-switch-when="matchValue2">...</ANY>
  18654. * <ANY ng-switch-default>...</ANY>
  18655. * </ANY>
  18656. *
  18657. *
  18658. * @scope
  18659. * @priority 800
  18660. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  18661. * On child elements add:
  18662. *
  18663. * * `ngSwitchWhen`: the case statement to match against. If match then this
  18664. * case will be displayed. If the same match appears multiple times, all the
  18665. * elements will be displayed.
  18666. * * `ngSwitchDefault`: the default case when no other case match. If there
  18667. * are multiple default cases, all of them will be displayed when no other
  18668. * case match.
  18669. *
  18670. *
  18671. * @example
  18672. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18673. <file name="index.html">
  18674. <div ng-controller="Ctrl">
  18675. <select ng-model="selection" ng-options="item for item in items">
  18676. </select>
  18677. <tt>selection={{selection}}</tt>
  18678. <hr/>
  18679. <div class="animate-switch-container"
  18680. ng-switch on="selection">
  18681. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  18682. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  18683. <div class="animate-switch" ng-switch-default>default</div>
  18684. </div>
  18685. </div>
  18686. </file>
  18687. <file name="script.js">
  18688. function Ctrl($scope) {
  18689. $scope.items = ['settings', 'home', 'other'];
  18690. $scope.selection = $scope.items[0];
  18691. }
  18692. </file>
  18693. <file name="animations.css">
  18694. .animate-switch-container {
  18695. position:relative;
  18696. background:white;
  18697. border:1px solid black;
  18698. height:40px;
  18699. overflow:hidden;
  18700. }
  18701. .animate-switch {
  18702. padding:10px;
  18703. }
  18704. .animate-switch.ng-animate {
  18705. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18706. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  18707. position:absolute;
  18708. top:0;
  18709. left:0;
  18710. right:0;
  18711. bottom:0;
  18712. }
  18713. .animate-switch.ng-leave.ng-leave-active,
  18714. .animate-switch.ng-enter {
  18715. top:-50px;
  18716. }
  18717. .animate-switch.ng-leave,
  18718. .animate-switch.ng-enter.ng-enter-active {
  18719. top:0;
  18720. }
  18721. </file>
  18722. <file name="protractor.js" type="protractor">
  18723. var switchElem = element(by.css('[ng-switch]'));
  18724. var select = element(by.model('selection'));
  18725. it('should start in settings', function() {
  18726. expect(switchElem.getText()).toMatch(/Settings Div/);
  18727. });
  18728. it('should change to home', function() {
  18729. select.element.all(by.css('option')).get(1).click();
  18730. expect(switchElem.getText()).toMatch(/Home Span/);
  18731. });
  18732. it('should select default', function() {
  18733. select.element.all(by.css('option')).get(2).click();
  18734. expect(switchElem.getText()).toMatch(/default/);
  18735. });
  18736. </file>
  18737. </example>
  18738. */
  18739. var ngSwitchDirective = ['$animate', function($animate) {
  18740. return {
  18741. restrict: 'EA',
  18742. require: 'ngSwitch',
  18743. // asks for $scope to fool the BC controller module
  18744. controller: ['$scope', function ngSwitchController() {
  18745. this.cases = {};
  18746. }],
  18747. link: function(scope, element, attr, ngSwitchController) {
  18748. var watchExpr = attr.ngSwitch || attr.on,
  18749. selectedTranscludes,
  18750. selectedElements,
  18751. previousElements,
  18752. selectedScopes = [];
  18753. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  18754. var i, ii = selectedScopes.length;
  18755. if(ii > 0) {
  18756. if(previousElements) {
  18757. for (i = 0; i < ii; i++) {
  18758. previousElements[i].remove();
  18759. }
  18760. previousElements = null;
  18761. }
  18762. previousElements = [];
  18763. for (i= 0; i<ii; i++) {
  18764. var selected = selectedElements[i];
  18765. selectedScopes[i].$destroy();
  18766. previousElements[i] = selected;
  18767. $animate.leave(selected, function() {
  18768. previousElements.splice(i, 1);
  18769. if(previousElements.length === 0) {
  18770. previousElements = null;
  18771. }
  18772. });
  18773. }
  18774. }
  18775. selectedElements = [];
  18776. selectedScopes = [];
  18777. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  18778. scope.$eval(attr.change);
  18779. forEach(selectedTranscludes, function(selectedTransclude) {
  18780. var selectedScope = scope.$new();
  18781. selectedScopes.push(selectedScope);
  18782. selectedTransclude.transclude(selectedScope, function(caseElement) {
  18783. var anchor = selectedTransclude.element;
  18784. selectedElements.push(caseElement);
  18785. $animate.enter(caseElement, anchor.parent(), anchor);
  18786. });
  18787. });
  18788. }
  18789. });
  18790. }
  18791. };
  18792. }];
  18793. var ngSwitchWhenDirective = ngDirective({
  18794. transclude: 'element',
  18795. priority: 800,
  18796. require: '^ngSwitch',
  18797. link: function(scope, element, attrs, ctrl, $transclude) {
  18798. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  18799. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  18800. }
  18801. });
  18802. var ngSwitchDefaultDirective = ngDirective({
  18803. transclude: 'element',
  18804. priority: 800,
  18805. require: '^ngSwitch',
  18806. link: function(scope, element, attr, ctrl, $transclude) {
  18807. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  18808. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  18809. }
  18810. });
  18811. /**
  18812. * @ngdoc directive
  18813. * @name ngTransclude
  18814. * @restrict AC
  18815. *
  18816. * @description
  18817. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  18818. *
  18819. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  18820. *
  18821. * @element ANY
  18822. *
  18823. * @example
  18824. <example module="transclude">
  18825. <file name="index.html">
  18826. <script>
  18827. function Ctrl($scope) {
  18828. $scope.title = 'Lorem Ipsum';
  18829. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  18830. }
  18831. angular.module('transclude', [])
  18832. .directive('pane', function(){
  18833. return {
  18834. restrict: 'E',
  18835. transclude: true,
  18836. scope: { title:'@' },
  18837. template: '<div style="border: 1px solid black;">' +
  18838. '<div style="background-color: gray">{{title}}</div>' +
  18839. '<div ng-transclude></div>' +
  18840. '</div>'
  18841. };
  18842. });
  18843. </script>
  18844. <div ng-controller="Ctrl">
  18845. <input ng-model="title"><br>
  18846. <textarea ng-model="text"></textarea> <br/>
  18847. <pane title="{{title}}">{{text}}</pane>
  18848. </div>
  18849. </file>
  18850. <file name="protractor.js" type="protractor">
  18851. it('should have transcluded', function() {
  18852. var titleElement = element(by.model('title'));
  18853. titleElement.clear();
  18854. titleElement.sendKeys('TITLE');
  18855. var textElement = element(by.model('text'));
  18856. textElement.clear();
  18857. textElement.sendKeys('TEXT');
  18858. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  18859. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  18860. });
  18861. </file>
  18862. </example>
  18863. *
  18864. */
  18865. var ngTranscludeDirective = ngDirective({
  18866. link: function($scope, $element, $attrs, controller, $transclude) {
  18867. if (!$transclude) {
  18868. throw minErr('ngTransclude')('orphan',
  18869. 'Illegal use of ngTransclude directive in the template! ' +
  18870. 'No parent directive that requires a transclusion found. ' +
  18871. 'Element: {0}',
  18872. startingTag($element));
  18873. }
  18874. $transclude(function(clone) {
  18875. $element.empty();
  18876. $element.append(clone);
  18877. });
  18878. }
  18879. });
  18880. /**
  18881. * @ngdoc directive
  18882. * @name script
  18883. * @restrict E
  18884. *
  18885. * @description
  18886. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  18887. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  18888. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  18889. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  18890. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  18891. *
  18892. * @param {string} type Must be set to `'text/ng-template'`.
  18893. * @param {string} id Cache name of the template.
  18894. *
  18895. * @example
  18896. <example>
  18897. <file name="index.html">
  18898. <script type="text/ng-template" id="/tpl.html">
  18899. Content of the template.
  18900. </script>
  18901. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  18902. <div id="tpl-content" ng-include src="currentTpl"></div>
  18903. </file>
  18904. <file name="protractor.js" type="protractor">
  18905. it('should load template defined inside script tag', function() {
  18906. element(by.css('#tpl-link')).click();
  18907. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  18908. });
  18909. </file>
  18910. </example>
  18911. */
  18912. var scriptDirective = ['$templateCache', function($templateCache) {
  18913. return {
  18914. restrict: 'E',
  18915. terminal: true,
  18916. compile: function(element, attr) {
  18917. if (attr.type == 'text/ng-template') {
  18918. var templateUrl = attr.id,
  18919. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  18920. text = element[0].text;
  18921. $templateCache.put(templateUrl, text);
  18922. }
  18923. }
  18924. };
  18925. }];
  18926. var ngOptionsMinErr = minErr('ngOptions');
  18927. /**
  18928. * @ngdoc directive
  18929. * @name select
  18930. * @restrict E
  18931. *
  18932. * @description
  18933. * HTML `SELECT` element with angular data-binding.
  18934. *
  18935. * # `ngOptions`
  18936. *
  18937. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  18938. * elements for the `<select>` element using the array or object obtained by evaluating the
  18939. * `ngOptions` comprehension_expression.
  18940. *
  18941. * When an item in the `<select>` menu is selected, the array element or object property
  18942. * represented by the selected option will be bound to the model identified by the `ngModel`
  18943. * directive.
  18944. *
  18945. * <div class="alert alert-warning">
  18946. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  18947. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  18948. * </div>
  18949. *
  18950. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  18951. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  18952. * option. See example below for demonstration.
  18953. *
  18954. * <div class="alert alert-warning">
  18955. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  18956. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  18957. * `select` model to be bound to a non-string value. This is because an option element can only
  18958. * be bound to string values at present.
  18959. * </div>
  18960. *
  18961. * @param {string} ngModel Assignable angular expression to data-bind to.
  18962. * @param {string=} name Property name of the form under which the control is published.
  18963. * @param {string=} required The control is considered valid only if value is entered.
  18964. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18965. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18966. * `required` when you want to data-bind to the `required` attribute.
  18967. * @param {comprehension_expression=} ngOptions in one of the following forms:
  18968. *
  18969. * * for array data sources:
  18970. * * `label` **`for`** `value` **`in`** `array`
  18971. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  18972. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  18973. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  18974. * * for object data sources:
  18975. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  18976. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  18977. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  18978. * * `select` **`as`** `label` **`group by`** `group`
  18979. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  18980. *
  18981. * Where:
  18982. *
  18983. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  18984. * * `value`: local variable which will refer to each item in the `array` or each property value
  18985. * of `object` during iteration.
  18986. * * `key`: local variable which will refer to a property name in `object` during iteration.
  18987. * * `label`: The result of this expression will be the label for `<option>` element. The
  18988. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  18989. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  18990. * element. If not specified, `select` expression will default to `value`.
  18991. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  18992. * DOM element.
  18993. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  18994. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  18995. * `value` variable (e.g. `value.propertyName`).
  18996. *
  18997. * @example
  18998. <example>
  18999. <file name="index.html">
  19000. <script>
  19001. function MyCntrl($scope) {
  19002. $scope.colors = [
  19003. {name:'black', shade:'dark'},
  19004. {name:'white', shade:'light'},
  19005. {name:'red', shade:'dark'},
  19006. {name:'blue', shade:'dark'},
  19007. {name:'yellow', shade:'light'}
  19008. ];
  19009. $scope.color = $scope.colors[2]; // red
  19010. }
  19011. </script>
  19012. <div ng-controller="MyCntrl">
  19013. <ul>
  19014. <li ng-repeat="color in colors">
  19015. Name: <input ng-model="color.name">
  19016. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19017. </li>
  19018. <li>
  19019. [<a href ng-click="colors.push({})">add</a>]
  19020. </li>
  19021. </ul>
  19022. <hr/>
  19023. Color (null not allowed):
  19024. <select ng-model="color" ng-options="c.name for c in colors"></select><br>
  19025. Color (null allowed):
  19026. <span class="nullable">
  19027. <select ng-model="color" ng-options="c.name for c in colors">
  19028. <option value="">-- choose color --</option>
  19029. </select>
  19030. </span><br/>
  19031. Color grouped by shade:
  19032. <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
  19033. </select><br/>
  19034. Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
  19035. <hr/>
  19036. Currently selected: {{ {selected_color:color} }}
  19037. <div style="border:solid 1px black; height:20px"
  19038. ng-style="{'background-color':color.name}">
  19039. </div>
  19040. </div>
  19041. </file>
  19042. <file name="protractor.js" type="protractor">
  19043. it('should check ng-options', function() {
  19044. expect(element(by.binding('{selected_color:color}')).getText()).toMatch('red');
  19045. element.all(by.select('color')).first().click();
  19046. element.all(by.css('select[ng-model="color"] option')).first().click();
  19047. expect(element(by.binding('{selected_color:color}')).getText()).toMatch('black');
  19048. element(by.css('.nullable select[ng-model="color"]')).click();
  19049. element.all(by.css('.nullable select[ng-model="color"] option')).first().click();
  19050. expect(element(by.binding('{selected_color:color}')).getText()).toMatch('null');
  19051. });
  19052. </file>
  19053. </example>
  19054. */
  19055. var ngOptionsDirective = valueFn({ terminal: true });
  19056. // jshint maxlen: false
  19057. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19058. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19059. 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]+?))?$/,
  19060. nullModelCtrl = {$setViewValue: noop};
  19061. // jshint maxlen: 100
  19062. return {
  19063. restrict: 'E',
  19064. require: ['select', '?ngModel'],
  19065. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19066. var self = this,
  19067. optionsMap = {},
  19068. ngModelCtrl = nullModelCtrl,
  19069. nullOption,
  19070. unknownOption;
  19071. self.databound = $attrs.ngModel;
  19072. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19073. ngModelCtrl = ngModelCtrl_;
  19074. nullOption = nullOption_;
  19075. unknownOption = unknownOption_;
  19076. };
  19077. self.addOption = function(value) {
  19078. assertNotHasOwnProperty(value, '"option value"');
  19079. optionsMap[value] = true;
  19080. if (ngModelCtrl.$viewValue == value) {
  19081. $element.val(value);
  19082. if (unknownOption.parent()) unknownOption.remove();
  19083. }
  19084. };
  19085. self.removeOption = function(value) {
  19086. if (this.hasOption(value)) {
  19087. delete optionsMap[value];
  19088. if (ngModelCtrl.$viewValue == value) {
  19089. this.renderUnknownOption(value);
  19090. }
  19091. }
  19092. };
  19093. self.renderUnknownOption = function(val) {
  19094. var unknownVal = '? ' + hashKey(val) + ' ?';
  19095. unknownOption.val(unknownVal);
  19096. $element.prepend(unknownOption);
  19097. $element.val(unknownVal);
  19098. unknownOption.prop('selected', true); // needed for IE
  19099. };
  19100. self.hasOption = function(value) {
  19101. return optionsMap.hasOwnProperty(value);
  19102. };
  19103. $scope.$on('$destroy', function() {
  19104. // disable unknown option so that we don't do work when the whole select is being destroyed
  19105. self.renderUnknownOption = noop;
  19106. });
  19107. }],
  19108. link: function(scope, element, attr, ctrls) {
  19109. // if ngModel is not defined, we don't need to do anything
  19110. if (!ctrls[1]) return;
  19111. var selectCtrl = ctrls[0],
  19112. ngModelCtrl = ctrls[1],
  19113. multiple = attr.multiple,
  19114. optionsExp = attr.ngOptions,
  19115. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19116. emptyOption,
  19117. // we can't just jqLite('<option>') since jqLite is not smart enough
  19118. // to create it in <select> and IE barfs otherwise.
  19119. optionTemplate = jqLite(document.createElement('option')),
  19120. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19121. unknownOption = optionTemplate.clone();
  19122. // find "null" option
  19123. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19124. if (children[i].value === '') {
  19125. emptyOption = nullOption = children.eq(i);
  19126. break;
  19127. }
  19128. }
  19129. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19130. // required validator
  19131. if (multiple) {
  19132. ngModelCtrl.$isEmpty = function(value) {
  19133. return !value || value.length === 0;
  19134. };
  19135. }
  19136. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19137. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19138. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19139. ////////////////////////////
  19140. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19141. ngModelCtrl.$render = function() {
  19142. var viewValue = ngModelCtrl.$viewValue;
  19143. if (selectCtrl.hasOption(viewValue)) {
  19144. if (unknownOption.parent()) unknownOption.remove();
  19145. selectElement.val(viewValue);
  19146. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19147. } else {
  19148. if (isUndefined(viewValue) && emptyOption) {
  19149. selectElement.val('');
  19150. } else {
  19151. selectCtrl.renderUnknownOption(viewValue);
  19152. }
  19153. }
  19154. };
  19155. selectElement.on('change', function() {
  19156. scope.$apply(function() {
  19157. if (unknownOption.parent()) unknownOption.remove();
  19158. ngModelCtrl.$setViewValue(selectElement.val());
  19159. });
  19160. });
  19161. }
  19162. function setupAsMultiple(scope, selectElement, ctrl) {
  19163. var lastView;
  19164. ctrl.$render = function() {
  19165. var items = new HashMap(ctrl.$viewValue);
  19166. forEach(selectElement.find('option'), function(option) {
  19167. option.selected = isDefined(items.get(option.value));
  19168. });
  19169. };
  19170. // we have to do it on each watch since ngModel watches reference, but
  19171. // we need to work of an array, so we need to see if anything was inserted/removed
  19172. scope.$watch(function selectMultipleWatch() {
  19173. if (!equals(lastView, ctrl.$viewValue)) {
  19174. lastView = copy(ctrl.$viewValue);
  19175. ctrl.$render();
  19176. }
  19177. });
  19178. selectElement.on('change', function() {
  19179. scope.$apply(function() {
  19180. var array = [];
  19181. forEach(selectElement.find('option'), function(option) {
  19182. if (option.selected) {
  19183. array.push(option.value);
  19184. }
  19185. });
  19186. ctrl.$setViewValue(array);
  19187. });
  19188. });
  19189. }
  19190. function setupAsOptions(scope, selectElement, ctrl) {
  19191. var match;
  19192. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19193. throw ngOptionsMinErr('iexp',
  19194. "Expected expression in form of " +
  19195. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19196. " but got '{0}'. Element: {1}",
  19197. optionsExp, startingTag(selectElement));
  19198. }
  19199. var displayFn = $parse(match[2] || match[1]),
  19200. valueName = match[4] || match[6],
  19201. keyName = match[5],
  19202. groupByFn = $parse(match[3] || ''),
  19203. valueFn = $parse(match[2] ? match[1] : valueName),
  19204. valuesFn = $parse(match[7]),
  19205. track = match[8],
  19206. trackFn = track ? $parse(match[8]) : null,
  19207. // This is an array of array of existing option groups in DOM.
  19208. // We try to reuse these if possible
  19209. // - optionGroupsCache[0] is the options with no option group
  19210. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19211. optionGroupsCache = [[{element: selectElement, label:''}]];
  19212. if (nullOption) {
  19213. // compile the element since there might be bindings in it
  19214. $compile(nullOption)(scope);
  19215. // remove the class, which is added automatically because we recompile the element and it
  19216. // becomes the compilation root
  19217. nullOption.removeClass('ng-scope');
  19218. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19219. // remove the label from the element. wtf?
  19220. nullOption.remove();
  19221. }
  19222. // clear contents, we'll add what's needed based on the model
  19223. selectElement.empty();
  19224. selectElement.on('change', function() {
  19225. scope.$apply(function() {
  19226. var optionGroup,
  19227. collection = valuesFn(scope) || [],
  19228. locals = {},
  19229. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19230. if (multiple) {
  19231. value = [];
  19232. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19233. groupIndex < groupLength;
  19234. groupIndex++) {
  19235. // list of options for that group. (first item has the parent)
  19236. optionGroup = optionGroupsCache[groupIndex];
  19237. for(index = 1, length = optionGroup.length; index < length; index++) {
  19238. if ((optionElement = optionGroup[index].element)[0].selected) {
  19239. key = optionElement.val();
  19240. if (keyName) locals[keyName] = key;
  19241. if (trackFn) {
  19242. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19243. locals[valueName] = collection[trackIndex];
  19244. if (trackFn(scope, locals) == key) break;
  19245. }
  19246. } else {
  19247. locals[valueName] = collection[key];
  19248. }
  19249. value.push(valueFn(scope, locals));
  19250. }
  19251. }
  19252. }
  19253. } else {
  19254. key = selectElement.val();
  19255. if (key == '?') {
  19256. value = undefined;
  19257. } else if (key === ''){
  19258. value = null;
  19259. } else {
  19260. if (trackFn) {
  19261. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19262. locals[valueName] = collection[trackIndex];
  19263. if (trackFn(scope, locals) == key) {
  19264. value = valueFn(scope, locals);
  19265. break;
  19266. }
  19267. }
  19268. } else {
  19269. locals[valueName] = collection[key];
  19270. if (keyName) locals[keyName] = key;
  19271. value = valueFn(scope, locals);
  19272. }
  19273. }
  19274. // Update the null option's selected property here so $render cleans it up correctly
  19275. if (optionGroupsCache[0].length > 1) {
  19276. if (optionGroupsCache[0][1].id !== key) {
  19277. optionGroupsCache[0][1].selected = false;
  19278. }
  19279. }
  19280. }
  19281. ctrl.$setViewValue(value);
  19282. });
  19283. });
  19284. ctrl.$render = render;
  19285. // TODO(vojta): can't we optimize this ?
  19286. scope.$watch(render);
  19287. function render() {
  19288. // Temporary location for the option groups before we render them
  19289. var optionGroups = {'':[]},
  19290. optionGroupNames = [''],
  19291. optionGroupName,
  19292. optionGroup,
  19293. option,
  19294. existingParent, existingOptions, existingOption,
  19295. modelValue = ctrl.$modelValue,
  19296. values = valuesFn(scope) || [],
  19297. keys = keyName ? sortedKeys(values) : values,
  19298. key,
  19299. groupLength, length,
  19300. groupIndex, index,
  19301. locals = {},
  19302. selected,
  19303. selectedSet = false, // nothing is selected yet
  19304. lastElement,
  19305. element,
  19306. label;
  19307. if (multiple) {
  19308. if (trackFn && isArray(modelValue)) {
  19309. selectedSet = new HashMap([]);
  19310. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19311. locals[valueName] = modelValue[trackIndex];
  19312. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19313. }
  19314. } else {
  19315. selectedSet = new HashMap(modelValue);
  19316. }
  19317. }
  19318. // We now build up the list of options we need (we merge later)
  19319. for (index = 0; length = keys.length, index < length; index++) {
  19320. key = index;
  19321. if (keyName) {
  19322. key = keys[index];
  19323. if ( key.charAt(0) === '$' ) continue;
  19324. locals[keyName] = key;
  19325. }
  19326. locals[valueName] = values[key];
  19327. optionGroupName = groupByFn(scope, locals) || '';
  19328. if (!(optionGroup = optionGroups[optionGroupName])) {
  19329. optionGroup = optionGroups[optionGroupName] = [];
  19330. optionGroupNames.push(optionGroupName);
  19331. }
  19332. if (multiple) {
  19333. selected = isDefined(
  19334. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  19335. );
  19336. } else {
  19337. if (trackFn) {
  19338. var modelCast = {};
  19339. modelCast[valueName] = modelValue;
  19340. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  19341. } else {
  19342. selected = modelValue === valueFn(scope, locals);
  19343. }
  19344. selectedSet = selectedSet || selected; // see if at least one item is selected
  19345. }
  19346. label = displayFn(scope, locals); // what will be seen by the user
  19347. // doing displayFn(scope, locals) || '' overwrites zero values
  19348. label = isDefined(label) ? label : '';
  19349. optionGroup.push({
  19350. // either the index into array or key from object
  19351. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  19352. label: label,
  19353. selected: selected // determine if we should be selected
  19354. });
  19355. }
  19356. if (!multiple) {
  19357. if (nullOption || modelValue === null) {
  19358. // insert null option if we have a placeholder, or the model is null
  19359. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  19360. } else if (!selectedSet) {
  19361. // option could not be found, we have to insert the undefined item
  19362. optionGroups[''].unshift({id:'?', label:'', selected:true});
  19363. }
  19364. }
  19365. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  19366. for (groupIndex = 0, groupLength = optionGroupNames.length;
  19367. groupIndex < groupLength;
  19368. groupIndex++) {
  19369. // current option group name or '' if no group
  19370. optionGroupName = optionGroupNames[groupIndex];
  19371. // list of options for that group. (first item has the parent)
  19372. optionGroup = optionGroups[optionGroupName];
  19373. if (optionGroupsCache.length <= groupIndex) {
  19374. // we need to grow the optionGroups
  19375. existingParent = {
  19376. element: optGroupTemplate.clone().attr('label', optionGroupName),
  19377. label: optionGroup.label
  19378. };
  19379. existingOptions = [existingParent];
  19380. optionGroupsCache.push(existingOptions);
  19381. selectElement.append(existingParent.element);
  19382. } else {
  19383. existingOptions = optionGroupsCache[groupIndex];
  19384. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  19385. // update the OPTGROUP label if not the same.
  19386. if (existingParent.label != optionGroupName) {
  19387. existingParent.element.attr('label', existingParent.label = optionGroupName);
  19388. }
  19389. }
  19390. lastElement = null; // start at the beginning
  19391. for(index = 0, length = optionGroup.length; index < length; index++) {
  19392. option = optionGroup[index];
  19393. if ((existingOption = existingOptions[index+1])) {
  19394. // reuse elements
  19395. lastElement = existingOption.element;
  19396. if (existingOption.label !== option.label) {
  19397. lastElement.text(existingOption.label = option.label);
  19398. }
  19399. if (existingOption.id !== option.id) {
  19400. lastElement.val(existingOption.id = option.id);
  19401. }
  19402. // lastElement.prop('selected') provided by jQuery has side-effects
  19403. if (existingOption.selected !== option.selected) {
  19404. lastElement.prop('selected', (existingOption.selected = option.selected));
  19405. }
  19406. } else {
  19407. // grow elements
  19408. // if it's a null option
  19409. if (option.id === '' && nullOption) {
  19410. // put back the pre-compiled element
  19411. element = nullOption;
  19412. } else {
  19413. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  19414. // in this version of jQuery on some browser the .text() returns a string
  19415. // rather then the element.
  19416. (element = optionTemplate.clone())
  19417. .val(option.id)
  19418. .attr('selected', option.selected)
  19419. .text(option.label);
  19420. }
  19421. existingOptions.push(existingOption = {
  19422. element: element,
  19423. label: option.label,
  19424. id: option.id,
  19425. selected: option.selected
  19426. });
  19427. if (lastElement) {
  19428. lastElement.after(element);
  19429. } else {
  19430. existingParent.element.append(element);
  19431. }
  19432. lastElement = element;
  19433. }
  19434. }
  19435. // remove any excessive OPTIONs in a group
  19436. index++; // increment since the existingOptions[0] is parent element not OPTION
  19437. while(existingOptions.length > index) {
  19438. existingOptions.pop().element.remove();
  19439. }
  19440. }
  19441. // remove any excessive OPTGROUPs from select
  19442. while(optionGroupsCache.length > groupIndex) {
  19443. optionGroupsCache.pop()[0].element.remove();
  19444. }
  19445. }
  19446. }
  19447. }
  19448. };
  19449. }];
  19450. var optionDirective = ['$interpolate', function($interpolate) {
  19451. var nullSelectCtrl = {
  19452. addOption: noop,
  19453. removeOption: noop
  19454. };
  19455. return {
  19456. restrict: 'E',
  19457. priority: 100,
  19458. compile: function(element, attr) {
  19459. if (isUndefined(attr.value)) {
  19460. var interpolateFn = $interpolate(element.text(), true);
  19461. if (!interpolateFn) {
  19462. attr.$set('value', element.text());
  19463. }
  19464. }
  19465. return function (scope, element, attr) {
  19466. var selectCtrlName = '$selectController',
  19467. parent = element.parent(),
  19468. selectCtrl = parent.data(selectCtrlName) ||
  19469. parent.parent().data(selectCtrlName); // in case we are in optgroup
  19470. if (selectCtrl && selectCtrl.databound) {
  19471. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  19472. // We don't want the view to drive the initialization of the model anyway.
  19473. element.prop('selected', false);
  19474. } else {
  19475. selectCtrl = nullSelectCtrl;
  19476. }
  19477. if (interpolateFn) {
  19478. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  19479. attr.$set('value', newVal);
  19480. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  19481. selectCtrl.addOption(newVal);
  19482. });
  19483. } else {
  19484. selectCtrl.addOption(attr.value);
  19485. }
  19486. element.on('$destroy', function() {
  19487. selectCtrl.removeOption(attr.value);
  19488. });
  19489. };
  19490. }
  19491. };
  19492. }];
  19493. var styleDirective = valueFn({
  19494. restrict: 'E',
  19495. terminal: true
  19496. });
  19497. if (window.angular.bootstrap) {
  19498. //AngularJS is already loaded, so we can return here...
  19499. console.log('WARNING: Tried to load angular more than once.');
  19500. return;
  19501. }
  19502. //try to bind to jquery now so that one can write angular.element().read()
  19503. //but we will rebind on bootstrap again.
  19504. bindJQuery();
  19505. publishExternalAPI(angular);
  19506. jqLite(document).ready(function() {
  19507. angularInit(document, bootstrap);
  19508. });
  19509. })(window, document);
  19510. !angular.$$csp() && 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;}</style>');